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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1240  ! raeburn     4: # $Id: lonnet.pm,v 1.1239 2013/09/29 14:15:08 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.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1213    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.539     albertel   95: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.550     foxr      108: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.993     raeburn   232: sub get_server_loncaparev {
1.1073    raeburn   233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   234:     if (defined($lonhost)) {
                    235:         if (!defined(&hostname($lonhost))) {
                    236:             undef($lonhost);
                    237:         }
                    238:     }
                    239:     if (!defined($lonhost)) {
                    240:         if (defined(&domain($dom,'primary'))) {
                    241:             $lonhost=&domain($dom,'primary');
                    242:             if ($lonhost eq 'no_host') {
                    243:                 undef($lonhost);
                    244:             }
                    245:         }
                    246:     }
                    247:     if (defined($lonhost)) {
1.1073    raeburn   248:         my $cachetime = 12*3600;
                    249:         if (!$ignore_cache) {
                    250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    251:             if (defined($cached)) {
                    252:                 return $loncaparev;
                    253:             }
                    254:         }
                    255:         my ($answer,$loncaparev);
                    256:         my @ids=&current_machine_ids();
                    257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    258:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   260:                 $loncaparev = $1;
                    261:             }
                    262:         } else {
                    263:             $answer = &reply('serverloncaparev',$lonhost);
                    264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    265:                 if ($caller eq 'loncron') {
                    266:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   267:                     $ua->timeout(4);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
                    270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
                    359:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   361:     return $response;
                    362: }
                    363: 
1.1       albertel  364: # -------------------------------------------------- Non-critical communication
                    365: sub subreply {
                    366:     my ($cmd,$server)=@_;
1.838     albertel  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      368:     #
                    369:     #  With loncnew process trimming, there's a timing hole between lonc server
                    370:     #  process exit and the master server picking up the listen on the AF_UNIX
                    371:     #  socket.  In that time interval, a lock file will exist:
                    372: 
                    373:     my $lockfile=$peerfile.".lock";
                    374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    375: 	sleep(1);
                    376:     }
                    377:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      378:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      379:     #
1.550     foxr      380:     #   We'll give the connection a few tries before abandoning it.  If
                    381:     #   connection is not possible, we'll con_lost back to the client.
                    382:     #   
                    383:     my $client;
                    384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    386: 				      Type    => SOCK_STREAM,
                    387: 				      Timeout => 10);
1.869     albertel  388: 	if ($client) {
1.550     foxr      389: 	    last;		# Connected!
1.850     albertel  390: 	} else {
1.853     albertel  391: 	    &create_connection(&hostname($server),$server);
1.550     foxr      392: 	}
1.850     albertel  393:         sleep(1);		# Try again later if failed connection.
1.550     foxr      394:     }
                    395:     my $answer;
                    396:     if ($client) {
1.704     albertel  397: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      398: 	$answer=<$client>;
                    399: 	if (!$answer) { $answer="con_lost"; }
                    400: 	chomp($answer);
                    401:     } else {
                    402: 	$answer = 'con_lost';	# Failed connection.
                    403:     }
1.1       albertel  404:     return $answer;
                    405: }
                    406: 
                    407: sub reply {
                    408:     my ($cmd,$server)=@_;
1.838     albertel  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  410:     my $answer=subreply($cmd,$server);
1.65      www       411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  412:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       413:                 " $cmd to $server returned $answer</font>");
                    414:     }
1.1       albertel  415:     return $answer;
                    416: }
                    417: 
                    418: # ----------------------------------------------------------- Send USR1 to lonc
                    419: 
                    420: sub reconlonc {
1.891     albertel  421:     my ($lonid) = @_;
                    422:     my $hostname = &hostname($lonid);
                    423:     if ($lonid) {
                    424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    425: 	if ($hostname && -e $peerfile) {
                    426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    428: 					     Type    => SOCK_STREAM,
                    429: 					     Timeout => 10);
                    430: 	    if ($client) {
                    431: 		print $client ("reset_retries\n");
                    432: 		my $answer=<$client>;
                    433: 		#reset just this one.
                    434: 	    }
                    435: 	}
                    436: 	return;
                    437:     }
                    438: 
1.836     www       439:     &logthis("Trying to reconnect lonc");
1.1       albertel  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  441:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  442: 	my $loncpid=<$fh>;
                    443:         chomp($loncpid);
                    444:         if (kill 0 => $loncpid) {
                    445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    446:             kill USR1 => $loncpid;
                    447:             sleep 1;
1.836     www       448:          } else {
1.12      www       449: 	    &logthis(
1.672     albertel  450:                "<font color=\"blue\">WARNING:".
1.12      www       451:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  452:         }
                    453:     } else {
1.836     www       454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  455:     }
                    456: }
                    457: 
                    458: # ------------------------------------------------------ Critical communication
1.12      www       459: 
1.1       albertel  460: sub critical {
                    461:     my ($cmd,$server)=@_;
1.838     albertel  462:     unless (&hostname($server)) {
1.672     albertel  463:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       464:                " Critical message to unknown server ($server)</font>");
                    465:         return 'no_such_host';
                    466:     }
1.1       albertel  467:     my $answer=reply($cmd,$server);
                    468:     if ($answer eq 'con_lost') {
                    469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  470: 	my $answer=reply($cmd,$server);
1.1       albertel  471:         if ($answer eq 'con_lost') {
                    472:             my $now=time;
                    473:             my $middlename=$cmd;
1.5       www       474:             $middlename=substr($middlename,0,16);
1.1       albertel  475:             $middlename=~s/\W//g;
                    476:             my $dfilename=
1.305     www       477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    478:             $dumpcount++;
1.1       albertel  479:             {
1.448     albertel  480: 		my $dfh;
                    481: 		if (open($dfh,">$dfilename")) {
                    482: 		    print $dfh "$cmd\n"; 
                    483: 		    close($dfh);
                    484: 		}
1.1       albertel  485:             }
                    486:             sleep 2;
                    487:             my $wcmd='';
                    488:             {
1.448     albertel  489: 		my $dfh;
                    490: 		if (open($dfh,"<$dfilename")) {
                    491: 		    $wcmd=<$dfh>; 
                    492: 		    close($dfh);
                    493: 		}
1.1       albertel  494:             }
                    495:             chomp($wcmd);
1.7       www       496:             if ($wcmd eq $cmd) {
1.672     albertel  497: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       498:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  499:                 &logperm("D:$server:$cmd");
                    500: 	        return 'con_delayed';
                    501:             } else {
1.672     albertel  502:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       503:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  504:                 &logperm("F:$server:$cmd");
                    505:                 return 'con_failed';
                    506:             }
                    507:         }
                    508:     }
                    509:     return $answer;
1.405     albertel  510: }
                    511: 
1.755     albertel  512: # ------------------------------------------- check if return value is an error
                    513: 
                    514: sub error {
                    515:     my ($result) = @_;
1.756     albertel  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  517: 	if ($2 == 2) { return undef; }
                    518: 	return $1;
                    519:     }
                    520:     return undef;
                    521: }
                    522: 
1.783     albertel  523: sub convert_and_load_session_env {
                    524:     my ($lonidsdir,$handle)=@_;
                    525:     my @profile;
                    526:     {
1.917     albertel  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    528: 	if (!$opened) {
1.915     albertel  529: 	    return 0;
                    530: 	}
1.783     albertel  531: 	flock($idf,LOCK_SH);
                    532: 	@profile=<$idf>;
                    533: 	close($idf);
                    534:     }
                    535:     my %temp_env;
                    536:     foreach my $line (@profile) {
1.786     albertel  537: 	if ($line !~ m/=/) {
                    538: 	    return 0;
                    539: 	}
1.783     albertel  540: 	chomp($line);
                    541: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    543:     }
                    544:     unlink("$lonidsdir/$handle.id");
                    545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    546: 	    0640)) {
                    547: 	%disk_env = %temp_env;
                    548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    549: 	untie(%disk_env);
                    550:     }
1.786     albertel  551:     return 1;
1.783     albertel  552: }
                    553: 
1.374     www       554: # ------------------------------------------- Transfer profile into environment
1.780     albertel  555: my $env_loaded;
                    556: sub transfer_profile_to_env {
1.788     albertel  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    558:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       559: 
1.720     albertel  560:     if (!defined($lonidsdir)) {
                    561: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    562:     }
                    563:     if (!defined($handle)) {
                    564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    565:     }
                    566: 
1.786     albertel  567:     my $convert;
                    568:     {
1.917     albertel  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    570: 	if (!$opened) {
1.915     albertel  571: 	    return;
                    572: 	}
1.786     albertel  573: 	flock($idf,LOCK_SH);
                    574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    575: 		&GDBM_READER(),0640)) {
                    576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    577: 	    untie(%disk_env);
                    578: 	} else {
                    579: 	    $convert = 1;
                    580: 	}
                    581:     }
                    582:     if ($convert) {
                    583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    584: 	    &logthis("Failed to load session, or convert session.");
                    585: 	}
1.374     www       586:     }
1.783     albertel  587: 
1.786     albertel  588:     my %remove;
1.783     albertel  589:     while ( my $envname = each(%env) ) {
1.433     matthew   590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    591:             if ($time < time-300) {
1.783     albertel  592:                 $remove{$key}++;
1.433     matthew   593:             }
                    594:         }
                    595:     }
1.783     albertel  596: 
1.619     albertel  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  598:     $env_loaded=1;
1.783     albertel  599:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   600:         &delenv($expired_key);
1.374     www       601:     }
1.1       albertel  602: }
                    603: 
1.916     albertel  604: # ---------------------------------------------------- Check for valid session 
                    605: sub check_for_valid_session {
1.1155    raeburn   606:     my ($r,$name) = @_;
1.916     albertel  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   608:     if ($name eq '') {
                    609:         $name = 'lonID';
                    610:     }
                    611:     my $lonid=$cookies{$name};
1.916     albertel  612:     return undef if (!$lonid);
                    613: 
                    614:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   615:     my $lonidsdir;
                    616:     if ($name eq 'lonDAV') {
                    617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    618:     } else {
                    619:         $lonidsdir=$r->dir_config('lonIDsDir');
                    620:     }
1.916     albertel  621:     return undef if (!-e "$lonidsdir/$handle.id");
                    622: 
1.917     albertel  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    624:     return undef if (!$opened);
1.916     albertel  625: 
                    626:     flock($idf,LOCK_SH);
                    627:     my %disk_env;
                    628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    629: 	    &GDBM_READER(),0640)) {
                    630: 	return undef;	
                    631:     }
                    632: 
                    633:     if (!defined($disk_env{'user.name'})
                    634: 	|| !defined($disk_env{'user.domain'})) {
                    635: 	return undef;
                    636:     }
1.1213    raeburn   637:     if (($r->user() eq '') && ($apache >= 2.4)) {
1.1212    raeburn   638:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    639:             $r->user($disk_env{'user.name'});
                    640:         } else {
                    641:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    642:         }
                    643:     }
1.916     albertel  644:     return $handle;
                    645: }
                    646: 
1.830     albertel  647: sub timed_flock {
                    648:     my ($file,$lock_type) = @_;
                    649:     my $failed=0;
                    650:     eval {
                    651: 	local $SIG{__DIE__}='DEFAULT';
                    652: 	local $SIG{ALRM}=sub {
                    653: 	    $failed=1;
                    654: 	    die("failed lock");
                    655: 	};
                    656: 	alarm(13);
                    657: 	flock($file,$lock_type);
                    658: 	alarm(0);
                    659:     };
                    660:     if ($failed) {
                    661: 	return undef;
                    662:     } else {
                    663: 	return 1;
                    664:     }
                    665: }
                    666: 
1.5       www       667: # ---------------------------------------------------------- Append Environment
                    668: 
                    669: sub appenv {
1.949     raeburn   670:     my ($newenv,$roles) = @_;
                    671:     if (ref($newenv) eq 'HASH') {
                    672:         foreach my $key (keys(%{$newenv})) {
                    673:             my $refused = 0;
                    674: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    675:                 $refused = 1;
                    676:                 if (ref($roles) eq 'ARRAY') {
                    677:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    678:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    679:                         $refused = 0;
                    680:                     }
                    681:                 }
                    682:             }
                    683:             if ($refused) {
                    684:                 &logthis("<font color=\"blue\">WARNING: ".
                    685:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    686:                          .'</font>');
                    687: 	        delete($newenv->{$key});
                    688:             } else {
                    689:                 $env{$key}=$newenv->{$key};
                    690:             }
                    691:         }
                    692:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    693:         if ($opened
                    694: 	    && &timed_flock($env_file,LOCK_EX)
                    695: 	    &&
                    696: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    697: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    698: 	    while (my ($key,$value) = each(%{$newenv})) {
                    699: 	        $disk_env{$key} = $value;
                    700: 	    }
                    701: 	    untie(%disk_env);
1.35      www       702:         }
1.191     harris41  703:     }
1.56      www       704:     return 'ok';
                    705: }
                    706: # ----------------------------------------------------- Delete from Environment
                    707: 
                    708: sub delenv {
1.1104    raeburn   709:     my ($delthis,$regexp,$roles) = @_;
                    710:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    711:         my $refused = 1;
                    712:         if (ref($roles) eq 'ARRAY') {
                    713:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    714:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    715:                 $refused = 0;
                    716:             }
                    717:         }
                    718:         if ($refused) {
                    719:             &logthis("<font color=\"blue\">WARNING: ".
                    720:                      "Attempt to delete from environment ".$delthis);
                    721:             return 'error';
                    722:         }
1.56      www       723:     }
1.917     albertel  724:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    725:     if ($opened
1.915     albertel  726: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  727: 	&&
                    728: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    729: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  730: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   731: 	    if ($regexp) {
                    732:                 if ($key=~/^$delthis/) {
                    733:                     delete($env{$key});
                    734:                     delete($disk_env{$key});
                    735:                 } 
                    736:             } else {
                    737:                 if ($key=~/^\Q$delthis\E/) {
                    738: 		    delete($env{$key});
                    739: 		    delete($disk_env{$key});
                    740: 	        }
                    741:             }
1.448     albertel  742: 	}
1.783     albertel  743: 	untie(%disk_env);
1.5       www       744:     }
                    745:     return 'ok';
1.369     albertel  746: }
                    747: 
1.790     albertel  748: sub get_env_multiple {
                    749:     my ($name) = @_;
                    750:     my @values;
                    751:     if (defined($env{$name})) {
                    752:         # exists is it an array
                    753:         if (ref($env{$name})) {
                    754:             @values=@{ $env{$name} };
                    755:         } else {
                    756:             $values[0]=$env{$name};
                    757:         }
                    758:     }
                    759:     return(@values);
                    760: }
                    761: 
1.958     www       762: # ------------------------------------------------------------------- Locking
                    763: 
                    764: sub set_lock {
                    765:     my ($text)=@_;
                    766:     $locknum++;
                    767:     my $id=$$.'-'.$locknum;
                    768:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    769:              'session.lock.'.$id => $text});
                    770:     return $id;
                    771: }
                    772: 
                    773: sub get_locks {
                    774:     my $num=0;
                    775:     my %texts=();
                    776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    777:        if ($lock=~/\w/) {
                    778:           $num++;
                    779:           $texts{$lock}=$env{'session.lock.'.$lock};
                    780:        }
                    781:    }
                    782:    return ($num,%texts);
                    783: }
                    784: 
                    785: sub remove_lock {
                    786:     my ($id)=@_;
                    787:     my $newlocks='';
                    788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    789:        if (($lock=~/\w/) && ($lock ne $id)) {
                    790:           $newlocks.=','.$lock;
                    791:        }
                    792:     }
                    793:     &appenv({'session.locks' => $newlocks});
                    794:     &delenv('session.lock.'.$id);
                    795: }
                    796: 
                    797: sub remove_all_locks {
                    798:     my $activelocks=$env{'session.locks'};
                    799:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    800:        if ($lock=~/\w/) {
                    801:           &remove_lock($lock);
                    802:        }
                    803:     }
                    804: }
                    805: 
                    806: 
1.369     albertel  807: # ------------------------------------------ Find out current server userload
                    808: sub userload {
                    809:     my $numusers=0;
                    810:     {
                    811: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    812: 	my $filename;
                    813: 	my $curtime=time;
                    814: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  815: 	    next if ($filename eq '.' || $filename eq '..');
                    816: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  817: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  818: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  819: 	}
                    820: 	closedir(LONIDS);
                    821:     }
                    822:     my $userloadpercent=0;
                    823:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    824:     if ($maxuserload) {
1.371     albertel  825: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  826:     }
1.372     albertel  827:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  828:     return $userloadpercent;
1.283     www       829: }
                    830: 
1.1       albertel  831: # ------------------------------ Find server with least workload from spare.tab
1.11      www       832: 
1.1       albertel  833: sub spareserver {
1.1083    raeburn   834:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  835:     my $spare_server;
1.370     albertel  836:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  837:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    838:                                                      :  $userloadpercent;
1.1083    raeburn   839:     my ($uint_dom,$remotesessions);
                    840:     if (($udom ne '') && (&domain($udom) ne '')) {
                    841:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    842:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    843:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    844:         $remotesessions = $udomdefaults{'remotesessions'};
                    845:     }
1.1123    raeburn   846:     my $spareshash = &this_host_spares($udom);
                    847:     if (ref($spareshash) eq 'HASH') {
                    848:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    849:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    850:                 if ($uint_dom) {
                    851:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    852:                                                  $try_server));
                    853:                 }
                    854: 	        ($spare_server, $lowest_load) =
                    855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:             }
1.1083    raeburn   857:         }
1.784     albertel  858: 
1.1123    raeburn   859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    860: 
                    861:         if (!$found_server) {
                    862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    864:                     if ($uint_dom) {
                    865:                         next unless (&spare_can_host($udom,$uint_dom,
                    866:                                                      $remotesessions,$try_server));
                    867:                     }
                    868: 	            ($spare_server, $lowest_load) =
                    869: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    870:                 }
                    871: 	    }
                    872:         }
1.784     albertel  873:     }
                    874: 
                    875:     if (!$want_server_name) {
1.968     raeburn   876:         my $protocol = 'http';
                    877:         if ($protocol{$spare_server} eq 'https') {
                    878:             $protocol = $protocol{$spare_server};
                    879:         }
1.1001    raeburn   880:         if (defined($spare_server)) {
                    881:             my $hostname = &hostname($spare_server);
1.1083    raeburn   882:             if (defined($hostname)) {
1.1001    raeburn   883: 	        $spare_server = $protocol.'://'.$hostname;
                    884:             }
                    885:         }
1.784     albertel  886:     }
                    887:     return $spare_server;
                    888: }
                    889: 
                    890: sub compare_server_load {
                    891:     my ($try_server, $spare_server, $lowest_load) = @_;
                    892: 
                    893:     my $loadans     = &reply('load',    $try_server);
                    894:     my $userloadans = &reply('userload',$try_server);
                    895: 
                    896:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   897: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  898:     }
                    899: 
                    900:     my $load;
                    901:     if ($loadans =~ /\d/) {
                    902: 	if ($userloadans =~ /\d/) {
                    903: 	    #both are numbers, pick the bigger one
                    904: 	    $load = ($loadans > $userloadans) ? $loadans 
                    905: 		                              : $userloadans;
1.411     albertel  906: 	} else {
1.784     albertel  907: 	    $load = $loadans;
1.411     albertel  908: 	}
1.784     albertel  909:     } else {
                    910: 	$load = $userloadans;
                    911:     }
                    912: 
                    913:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    914: 	$spare_server = $try_server;
                    915: 	$lowest_load  = $load;
1.370     albertel  916:     }
1.784     albertel  917:     return ($spare_server,$lowest_load);
1.202     matthew   918: }
1.914     albertel  919: 
                    920: # --------------------------- ask offload servers if user already has a session
                    921: sub find_existing_session {
                    922:     my ($udom,$uname) = @_;
1.1123    raeburn   923:     my $spareshash = &this_host_spares($udom);
                    924:     if (ref($spareshash) eq 'HASH') {
                    925:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    926:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    927:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    928:             }
                    929:         }
                    930:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    931:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    932:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    933:             }
                    934:         }
1.914     albertel  935:     }
                    936:     return;
                    937: }
                    938: 
                    939: # -------------------------------- ask if server already has a session for user
                    940: sub has_user_session {
                    941:     my ($lonid,$udom,$uname) = @_;
                    942:     my $result = &reply(join(':','userhassession',
                    943: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    944:     return 1 if ($result eq 'ok');
                    945: 
                    946:     return 0;
                    947: }
                    948: 
1.1076    raeburn   949: # --------- determine least loaded server in a user's domain which allows login
                    950: 
                    951: sub choose_server {
1.1115    raeburn   952:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   953:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   954:     my %servers = &get_servers($udom);
1.1076    raeburn   955:     my $lowest_load = 30000;
1.1151    raeburn   956:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   957:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   958:         my $loginvia;
                    959:         if ($checkloginvia) {
                    960:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   961:             if ($loginvia) {
                    962:                 my ($server,$path) = split(/:/,$loginvia);
                    963:                 ($login_host, $lowest_load) =
                    964:                     &compare_server_load($server, $login_host, $lowest_load);
                    965:                 if ($login_host eq $server) {
                    966:                     $portal_path = $path;
1.1151    raeburn   967:                     $isredirect = 1;
1.1116    raeburn   968:                 }
                    969:             } else {
                    970:                 ($login_host, $lowest_load) =
                    971:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    972:                 if ($login_host eq $lonhost) {
                    973:                     $portal_path = '';
1.1151    raeburn   974:                     $isredirect = ''; 
1.1116    raeburn   975:                 }
                    976:             }
                    977:         } else {
1.1076    raeburn   978:             ($login_host, $lowest_load) =
1.1116    raeburn   979:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   980:         }
                    981:     }
                    982:     if ($login_host ne '') {
1.1116    raeburn   983:         $hostname = &hostname($login_host);
1.1076    raeburn   984:     }
1.1151    raeburn   985:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   986: }
                    987: 
1.202     matthew   988: # --------------------------------------------- Try to change a user's password
                    989: 
                    990: sub changepass {
1.799     raeburn   991:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   992:     $currentpass = &escape($currentpass);
                    993:     $newpass     = &escape($newpass);
1.1030    raeburn   994:     my $lonhost = $perlvar{'lonHostID'};
                    995:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   996: 		       $server);
                    997:     if (! $answer) {
                    998: 	&logthis("No reply on password change request to $server ".
                    999: 		 "by $uname in domain $udom.");
                   1000:     } elsif ($answer =~ "^ok") {
                   1001:         &logthis("$uname in $udom successfully changed their password ".
                   1002: 		 "on $server.");
                   1003:     } elsif ($answer =~ "^pwchange_failure") {
                   1004: 	&logthis("$uname in $udom was unable to change their password ".
                   1005: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1006: 		 "or pwchange");
                   1007:     } elsif ($answer =~ "^non_authorized") {
                   1008:         &logthis("$uname in $udom did not get their password correct when ".
                   1009: 		 "attempting to change it on $server.");
                   1010:     } elsif ($answer =~ "^auth_mode_error") {
                   1011:         &logthis("$uname in $udom attempted to change their password despite ".
                   1012: 		 "not being locally or internally authenticated on $server.");
                   1013:     } elsif ($answer =~ "^unknown_user") {
                   1014:         &logthis("$uname in $udom attempted to change their password ".
                   1015: 		 "on $server but were unable to because $server is not ".
                   1016: 		 "their home server.");
                   1017:     } elsif ($answer =~ "^refused") {
                   1018: 	&logthis("$server refused to change $uname in $udom password because ".
                   1019: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1020:     } elsif ($answer =~ "invalid_client") {
                   1021:         &logthis("$server refused to change $uname in $udom password because ".
                   1022:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1023:     }
                   1024:     return $answer;
1.1       albertel 1025: }
                   1026: 
1.169     harris41 1027: # ----------------------- Try to determine user's current authentication scheme
                   1028: 
                   1029: sub queryauthenticate {
                   1030:     my ($uname,$udom)=@_;
1.456     albertel 1031:     my $uhome=&homeserver($uname,$udom);
                   1032:     if (!$uhome) {
                   1033: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1034: 	return 'no_host';
                   1035:     }
                   1036:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1037:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1038: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1039:     }
1.456     albertel 1040:     return $answer;
1.169     harris41 1041: }
                   1042: 
1.1       albertel 1043: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1044: 
1.1       albertel 1045: sub authenticate {
1.1073    raeburn  1046:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1047:     $upass=&escape($upass);
                   1048:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1049:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1050:     my $newhome;
1.836     www      1051:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1052: # Maybe the machine was offline and only re-appeared again recently?
                   1053:         &reconlonc();
                   1054: # One more
1.952     raeburn  1055: 	$uhome=&homeserver($uname,$udom,1);
                   1056:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1057:             if (defined(&domain($udom,'primary'))) {
                   1058:                 $newhome=&domain($udom,'primary');
                   1059:             }
                   1060:             if ($newhome ne '') {
                   1061:                 $uhome = $newhome;
                   1062:             }
                   1063:         }
1.836     www      1064: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1065: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1066: 	    return 'no_host';
                   1067:         }
1.1       albertel 1068:     }
1.1073    raeburn  1069:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1070:     if ($answer eq 'authorized') {
1.952     raeburn  1071:         if ($newhome) {
                   1072:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1073:             return 'no_account_on_host'; 
                   1074:         } else {
                   1075:             &logthis("User $uname at $udom authorized by $uhome");
                   1076:             return $uhome;
                   1077:         }
1.471     albertel 1078:     }
                   1079:     if ($answer eq 'non_authorized') {
                   1080: 	&logthis("User $uname at $udom rejected by $uhome");
                   1081: 	return 'no_host'; 
1.9       www      1082:     }
1.471     albertel 1083:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1084:     return 'no_host';
                   1085: }
                   1086: 
1.1073    raeburn  1087: sub can_host_session {
1.1074    raeburn  1088:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1089:     my $canhost = 1;
1.1074    raeburn  1090:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1091:     if (ref($remotesessions) eq 'HASH') {
                   1092:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1094:                 $canhost = 0;
                   1095:             } else {
                   1096:                 $canhost = 1;
                   1097:             }
                   1098:         }
                   1099:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1100:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1101:                 $canhost = 1;
                   1102:             } else {
                   1103:                 $canhost = 0;
                   1104:             }
                   1105:         }
                   1106:         if ($canhost) {
                   1107:             if ($remotesessions->{'version'} ne '') {
                   1108:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1109:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1110:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1111:                         my $major = $1;
                   1112:                         my $minor = $2;
                   1113:                         if (($major < $reqmajor ) ||
                   1114:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1115:                             $canhost = 0;
                   1116:                         }
                   1117:                     } else {
                   1118:                         $canhost = 0;
                   1119:                     }
                   1120:                 }
                   1121:             }
                   1122:         }
                   1123:     }
                   1124:     if ($canhost) {
                   1125:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1126:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1127:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1128:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1129:                 if (($uint_dom ne '') && 
                   1130:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1131:                     $canhost = 0;
                   1132:                 } else {
                   1133:                     $canhost = 1;
                   1134:                 }
                   1135:             }
                   1136:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1137:                 if (($uint_dom ne '') && 
                   1138:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1139:                     $canhost = 1;
                   1140:                 } else {
                   1141:                     $canhost = 0;
                   1142:                 }
                   1143:             }
                   1144:         }
                   1145:     }
                   1146:     return $canhost;
                   1147: }
                   1148: 
1.1083    raeburn  1149: sub spare_can_host {
                   1150:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1151:     my $canhost=1;
                   1152:     my @intdoms;
                   1153:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1154:     if (ref($internet_names) eq 'ARRAY') {
                   1155:         @intdoms = @{$internet_names};
                   1156:     }
                   1157:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1158:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1159:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1160:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1161:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1162:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1163:                                      $remotesessions,
                   1164:                                      $defdomdefaults{'hostedsessions'});
                   1165:     }
                   1166:     return $canhost;
                   1167: }
                   1168: 
1.1123    raeburn  1169: sub this_host_spares {
                   1170:     my ($dom) = @_;
1.1126    raeburn  1171:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1172:     my @hosts = &current_machine_ids();
                   1173:     foreach my $lonhost (@hosts) {
                   1174:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1175:             $dom_in_use = $dom;
                   1176:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1177:             last;
                   1178:         }
                   1179:     }
1.1126    raeburn  1180:     if ($dom_in_use ne '') {
                   1181:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1182:     }
                   1183:     if (ref($result) ne 'HASH') {
                   1184:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1185:         $dom_in_use = &host_domain($lonhost_in_use);
                   1186:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1187:         if (ref($result) ne 'HASH') {
                   1188:             $result = \%spareid;
                   1189:         }
                   1190:     }
                   1191:     return $result;
                   1192: }
                   1193: 
                   1194: sub spares_for_offload  {
                   1195:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1196:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1197:     if (defined($cached)) {
                   1198:         return $result;
                   1199:     } else {
1.1126    raeburn  1200:         my $cachetime = 60*60*24;
                   1201:         my %domconfig =
                   1202:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1203:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1204:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1205:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1206:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1207:                 }
                   1208:             }
                   1209:         }
                   1210:     }
1.1126    raeburn  1211:     return;
1.1123    raeburn  1212: }
                   1213: 
1.1129    raeburn  1214: sub get_lonbalancer_config {
                   1215:     my ($servers) = @_;
                   1216:     my ($currbalancer,$currtargets);
                   1217:     if (ref($servers) eq 'HASH') {
                   1218:         foreach my $server (keys(%{$servers})) {
                   1219:             my %what = (
                   1220:                          spareid => 1,
                   1221:                          perlvar => 1,
                   1222:                        );
                   1223:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1224:             if ($result eq 'ok') {
                   1225:                 if (ref($returnhash) eq 'HASH') {
                   1226:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1227:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1228:                             $currbalancer = $server;
                   1229:                             $currtargets = {};
                   1230:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1231:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1232:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1233:                                 }
                   1234:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1235:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1236:                                 }
                   1237:                             }
                   1238:                             last;
                   1239:                         }
                   1240:                     }
                   1241:                 }
                   1242:             }
                   1243:         }
                   1244:     }
                   1245:     return ($currbalancer,$currtargets);
                   1246: }
                   1247: 
                   1248: sub check_loadbalancing {
                   1249:     my ($uname,$udom) = @_;
1.1191    raeburn  1250:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1251:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1252:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1253:     my @hosts = &current_machine_ids();
1.1129    raeburn  1254:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1255:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1256:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1257:     my $serverhomedom = &host_domain($lonhost);
                   1258: 
                   1259:     my $cachetime = 60*60*24;
                   1260: 
                   1261:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1262:         $dom_in_use = $udom;
                   1263:         $homeintdom = 1;
                   1264:     } else {
                   1265:         $dom_in_use = $serverhomedom;
                   1266:     }
                   1267:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1268:     unless (defined($cached)) {
                   1269:         my %domconfig =
                   1270:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1271:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1272:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1273:         }
                   1274:     }
                   1275:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1276:         ($is_balancer,$currtargets,$currrules) = 
                   1277:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1278:         if ($is_balancer) {
                   1279:             if (ref($currrules) eq 'HASH') {
                   1280:                 if ($homeintdom) {
                   1281:                     if ($uname ne '') {
                   1282:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1283:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1284:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1285:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1286:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1287:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1288:                             }
                   1289:                         }
                   1290:                         if ($rule_in_effect eq '') {
                   1291:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1292:                             if ($userenv{'inststatus'} ne '') {
                   1293:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1294:                                 my ($othertitle,$usertypes,$types) =
                   1295:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1296:                                 if (ref($types) eq 'ARRAY') {
                   1297:                                     foreach my $type (@{$types}) {
                   1298:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1299:                                             if (exists($currrules->{$type})) {
                   1300:                                                 $rule_in_effect = $currrules->{$type};
                   1301:                                             }
                   1302:                                         }
                   1303:                                     }
                   1304:                                 }
                   1305:                             } else {
                   1306:                                 if (exists($currrules->{'default'})) {
                   1307:                                     $rule_in_effect = $currrules->{'default'};
                   1308:                                 }
                   1309:                             }
                   1310:                         }
                   1311:                     } else {
                   1312:                         if (exists($currrules->{'default'})) {
                   1313:                             $rule_in_effect = $currrules->{'default'};
                   1314:                         }
                   1315:                     }
                   1316:                 } else {
                   1317:                     if ($currrules->{'_LC_external'} ne '') {
                   1318:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1319:                     }
                   1320:                 }
                   1321:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1322:                                                        $uname,$udom);
                   1323:             }
                   1324:         }
                   1325:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1326:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1327:         unless (defined($cached)) {
                   1328:             my %domconfig =
                   1329:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1330:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1331:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1332:             }
                   1333:         }
                   1334:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1335:             ($is_balancer,$currtargets,$currrules) = 
                   1336:                 &check_balancer_result($result,@hosts);
                   1337:             if ($is_balancer) {
1.1129    raeburn  1338:                 if (ref($currrules) eq 'HASH') {
                   1339:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1340:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1341:                     }
                   1342:                 }
                   1343:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1344:                                                        $uname,$udom);
                   1345:             }
                   1346:         } else {
                   1347:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1348:                 $is_balancer = 1;
                   1349:                 $offloadto = &this_host_spares($dom_in_use);
                   1350:             }
                   1351:         }
                   1352:     } else {
                   1353:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1354:             $is_balancer = 1;
                   1355:             $offloadto = &this_host_spares($dom_in_use);
                   1356:         }
                   1357:     }
1.1176    raeburn  1358:     if ($is_balancer) {
                   1359:         my $lowest_load = 30000;
                   1360:         if (ref($offloadto) eq 'HASH') {
                   1361:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1362:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1363:                     ($otherserver,$lowest_load) =
                   1364:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1365:                 }
1.1129    raeburn  1366:             }
1.1176    raeburn  1367:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1368: 
1.1176    raeburn  1369:             if (!$found_server) {
                   1370:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1371:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1372:                         ($otherserver,$lowest_load) =
                   1373:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1374:                     }
                   1375:                 }
                   1376:             }
                   1377:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1378:             if (@{$offloadto} == 1) {
                   1379:                 $otherserver = $offloadto->[0];
                   1380:             } elsif (@{$offloadto} > 1) {
                   1381:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1382:                     ($otherserver,$lowest_load) =
                   1383:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1384:                 }
                   1385:             }
                   1386:         }
1.1176    raeburn  1387:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1388:             $is_balancer = 0;
                   1389:             if ($uname ne '' && $udom ne '') {
                   1390:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1391:                     
                   1392:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1393:                              'user.loadbalcheck.time' => time});
                   1394:                 }
1.1129    raeburn  1395:             }
                   1396:         }
                   1397:     }
                   1398:     return ($is_balancer,$otherserver);
                   1399: }
                   1400: 
1.1191    raeburn  1401: sub check_balancer_result {
                   1402:     my ($result,@hosts) = @_;
                   1403:     my ($is_balancer,$currtargets,$currrules);
                   1404:     if (ref($result) eq 'HASH') {
                   1405:         if ($result->{'lonhost'} ne '') {
                   1406:             my $currbalancer = $result->{'lonhost'};
                   1407:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1408:                 $is_balancer = 1;
                   1409:                 $currtargets = $result->{'targets'};
                   1410:                 $currrules = $result->{'rules'};
                   1411:             }
                   1412:         } else {
                   1413:             foreach my $key (keys(%{$result})) {
                   1414:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1415:                     (ref($result->{$key}) eq 'HASH')) {
                   1416:                     $is_balancer = 1;
                   1417:                     $currrules = $result->{$key}{'rules'};
                   1418:                     $currtargets = $result->{$key}{'targets'};
                   1419:                     last;
                   1420:                 }
                   1421:             }
                   1422:         }
                   1423:     }
                   1424:     return ($is_balancer,$currtargets,$currrules);
                   1425: }
                   1426: 
1.1129    raeburn  1427: sub get_loadbalancer_targets {
                   1428:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1429:     my $offloadto;
1.1175    raeburn  1430:     if ($rule_in_effect eq 'none') {
                   1431:         return [$perlvar{'lonHostID'}];
                   1432:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1433:         $offloadto = $currtargets;
                   1434:     } else {
                   1435:         if ($rule_in_effect eq 'homeserver') {
                   1436:             my $homeserver = &homeserver($uname,$udom);
                   1437:             if ($homeserver ne 'no_host') {
                   1438:                 $offloadto = [$homeserver];
                   1439:             }
                   1440:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1441:             my %domconfig =
                   1442:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1443:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1444:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1445:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1446:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1447:                     }
                   1448:                 }
                   1449:             } else {
1.1178    raeburn  1450:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1451:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1452:                 if (&hostname($remotebalancer) ne '') {
                   1453:                     $offloadto = [$remotebalancer];
                   1454:                 }
                   1455:             }
                   1456:         } elsif (&hostname($rule_in_effect) ne '') {
                   1457:             $offloadto = [$rule_in_effect];
                   1458:         }
                   1459:     }
                   1460:     return $offloadto;
                   1461: }
                   1462: 
1.1127    raeburn  1463: sub internet_dom_servers {
                   1464:     my ($dom) = @_;
                   1465:     my (%uniqservers,%servers);
                   1466:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1467:     my @machinedoms = &machine_domains($primaryserver);
                   1468:     foreach my $mdom (@machinedoms) {
                   1469:         my %currservers = %servers;
                   1470:         my %server = &get_servers($mdom);
                   1471:         %servers = (%currservers,%server);
                   1472:     }
                   1473:     my %by_hostname;
                   1474:     foreach my $id (keys(%servers)) {
                   1475:         push(@{$by_hostname{$servers{$id}}},$id);
                   1476:     }
                   1477:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1478:         if (@{$by_hostname{$hostname}} > 1) {
                   1479:             my $match = 0;
                   1480:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1481:                 if (&host_domain($id) eq $dom) {
                   1482:                     $uniqservers{$id} = $hostname;
                   1483:                     $match = 1;
                   1484:                 }
                   1485:             }
                   1486:             unless ($match) {
                   1487:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1488:             }
                   1489:         } else {
                   1490:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1491:         }
                   1492:     }
                   1493:     return %uniqservers;
                   1494: }
                   1495: 
1.1       albertel 1496: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1497: 
1.599     albertel 1498: my %homecache;
1.1       albertel 1499: sub homeserver {
1.230     stredwic 1500:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1501:     my $index="$uname:$udom";
1.426     albertel 1502: 
1.599     albertel 1503:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1504: 
                   1505:     my %servers = &get_servers($udom,'library');
                   1506:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1507:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1508: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1509: 
                   1510: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1511: 	if ($answer eq 'found') {
                   1512: 	    delete($badServerCache{$tryserver}); 
                   1513: 	    return $homecache{$index}=$tryserver;
                   1514: 	} elsif ($answer eq 'no_host') {
                   1515: 	    $badServerCache{$tryserver}=1;
                   1516: 	}
1.1       albertel 1517:     }    
                   1518:     return 'no_host';
1.70      www      1519: }
                   1520: 
                   1521: # ------------------------------------- Find the usernames behind a list of IDs
                   1522: 
                   1523: sub idget {
                   1524:     my ($udom,@ids)=@_;
                   1525:     my %returnhash=();
                   1526:     
1.841     albertel 1527:     my %servers = &get_servers($udom,'library');
                   1528:     foreach my $tryserver (keys(%servers)) {
                   1529: 	my $idlist=join('&',@ids);
                   1530: 	$idlist=~tr/A-Z/a-z/; 
                   1531: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1532: 	my @answer=();
                   1533: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1534: 	    @answer=split(/\&/,$reply);
                   1535: 	}                    ;
                   1536: 	my $i;
                   1537: 	for ($i=0;$i<=$#ids;$i++) {
                   1538: 	    if ($answer[$i]) {
                   1539: 		$returnhash{$ids[$i]}=$answer[$i];
                   1540: 	    } 
                   1541: 	}
                   1542:     } 
1.70      www      1543:     return %returnhash;
                   1544: }
                   1545: 
                   1546: # ------------------------------------- Find the IDs behind a list of usernames
                   1547: 
                   1548: sub idrget {
                   1549:     my ($udom,@unames)=@_;
                   1550:     my %returnhash=();
1.800     albertel 1551:     foreach my $uname (@unames) {
                   1552:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1553:     }
1.70      www      1554:     return %returnhash;
                   1555: }
                   1556: 
                   1557: # ------------------------------- Store away a list of names and associated IDs
                   1558: 
                   1559: sub idput {
                   1560:     my ($udom,%ids)=@_;
                   1561:     my %servers=();
1.800     albertel 1562:     foreach my $uname (keys(%ids)) {
                   1563: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1564:         my $uhom=&homeserver($uname,$udom);
1.70      www      1565:         if ($uhom ne 'no_host') {
1.800     albertel 1566:             my $id=&escape($ids{$uname});
1.70      www      1567:             $id=~tr/A-Z/a-z/;
1.800     albertel 1568:             my $esc_unam=&escape($uname);
1.70      www      1569: 	    if ($servers{$uhom}) {
1.800     albertel 1570: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1571:             } else {
1.800     albertel 1572:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1573:             }
                   1574:         }
1.191     harris41 1575:     }
1.800     albertel 1576:     foreach my $server (keys(%servers)) {
                   1577:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1578:     }
1.344     www      1579: }
                   1580: 
1.1231    raeburn  1581: # ---------------------------------------- Delete unwanted IDs from ids.db file 
                   1582: 
                   1583: sub iddel {
                   1584:     my ($udom,$idshashref,$uhome)=@_;
                   1585:     my %result=();
                   1586:     unless (ref($idshashref) eq 'HASH') {
                   1587:         return %result;
                   1588:     }
                   1589:     my %servers=();
                   1590:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1591:         my $uhom;
                   1592:         if ($uhome) {
                   1593:             $uhom = $uhome;
                   1594:         } else {
                   1595:             $uhom=&homeserver($uname,$udom);
                   1596:         }
                   1597:         if ($uhom ne 'no_host') {
                   1598:             if ($servers{$uhom}) {
                   1599:                 $servers{$uhom}.='&'.&escape($id);
                   1600:             } else {
                   1601:                 $servers{$uhom}=&escape($id);
                   1602:             }
                   1603:         }
                   1604:     }
                   1605:     foreach my $server (keys(%servers)) {
                   1606:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1607:     }
                   1608:     return %result;
                   1609: }
                   1610: 
1.1023    raeburn  1611: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1612: sub dump_dom {
1.1165    droeschl 1613:     my ($namespace, $udom, $regexp) = @_;
                   1614: 
                   1615:     $udom ||= $env{'user.domain'};
                   1616: 
                   1617:     return () unless $udom;
                   1618: 
                   1619:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1620: }
                   1621: 
1.1023    raeburn  1622: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1623: 
                   1624: sub get_dom {
1.860     raeburn  1625:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1626:     my $items='';
                   1627:     foreach my $item (@$storearr) {
                   1628:         $items.=&escape($item).'&';
                   1629:     }
                   1630:     $items=~s/\&$//;
1.860     raeburn  1631:     if (!$udom) {
                   1632:         $udom=$env{'user.domain'};
                   1633:         if (defined(&domain($udom,'primary'))) {
                   1634:             $uhome=&domain($udom,'primary');
                   1635:         } else {
1.874     albertel 1636:             undef($uhome);
1.860     raeburn  1637:         }
                   1638:     } else {
                   1639:         if (!$uhome) {
                   1640:             if (defined(&domain($udom,'primary'))) {
                   1641:                 $uhome=&domain($udom,'primary');
                   1642:             }
                   1643:         }
                   1644:     }
                   1645:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1646:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1647:         my %returnhash;
1.875     albertel 1648:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1649:             return %returnhash;
                   1650:         }
1.806     raeburn  1651:         my @pairs=split(/\&/,$rep);
                   1652:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1653:             return @pairs;
                   1654:         }
                   1655:         my $i=0;
                   1656:         foreach my $item (@$storearr) {
                   1657:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1658:             $i++;
                   1659:         }
                   1660:         return %returnhash;
                   1661:     } else {
1.880     banghart 1662:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1663:     }
                   1664: }
                   1665: 
                   1666: # -------------------------------------------- put items in domain db files 
                   1667: 
                   1668: sub put_dom {
1.860     raeburn  1669:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1670:     if (!$udom) {
                   1671:         $udom=$env{'user.domain'};
                   1672:         if (defined(&domain($udom,'primary'))) {
                   1673:             $uhome=&domain($udom,'primary');
                   1674:         } else {
1.874     albertel 1675:             undef($uhome);
1.860     raeburn  1676:         }
                   1677:     } else {
                   1678:         if (!$uhome) {
                   1679:             if (defined(&domain($udom,'primary'))) {
                   1680:                 $uhome=&domain($udom,'primary');
                   1681:             }
                   1682:         }
                   1683:     } 
                   1684:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1685:         my $items='';
                   1686:         foreach my $item (keys(%$storehash)) {
                   1687:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1688:         }
                   1689:         $items=~s/\&$//;
                   1690:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1691:     } else {
1.860     raeburn  1692:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1693:     }
                   1694: }
                   1695: 
1.1023    raeburn  1696: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1697: sub newput_dom {
1.1023    raeburn  1698:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1699:     my $result;
                   1700:     if (!$udom) {
                   1701:         $udom=$env{'user.domain'};
                   1702:     }
1.1023    raeburn  1703:     if ($udom) {
                   1704:         my $uname = &get_domainconfiguser($udom);
                   1705:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1706:     }
                   1707:     return $result;
                   1708: }
                   1709: 
1.1023    raeburn  1710: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1711: sub del_dom {
1.1023    raeburn  1712:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1713:     if (ref($storearr) eq 'ARRAY') {
                   1714:         if (!$udom) {
                   1715:             $udom=$env{'user.domain'};
                   1716:         }
1.1023    raeburn  1717:         if ($udom) {
                   1718:             my $uname = &get_domainconfiguser($udom); 
                   1719:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1720:         }
                   1721:     }
                   1722: }
                   1723: 
1.1023    raeburn  1724: # ----------------------------------construct domainconfig user for a domain 
                   1725: sub get_domainconfiguser {
                   1726:     my ($udom) = @_;
                   1727:     return $udom.'-domainconfig';
                   1728: }
                   1729: 
1.837     raeburn  1730: sub retrieve_inst_usertypes {
                   1731:     my ($udom) = @_;
                   1732:     my (%returnhash,@order);
1.989     raeburn  1733:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1734:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1735:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1736:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1737:         @order = @{$domdefs{'inststatusorder'}};
                   1738:     } else {
                   1739:         if (defined(&domain($udom,'primary'))) {
                   1740:             my $uhome=&domain($udom,'primary');
                   1741:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1742:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1743:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1744:                 return (\%returnhash,\@order);
                   1745:             }
                   1746:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1747:             my @pairs=split(/\&/,$hashitems);
                   1748:             foreach my $item (@pairs) {
                   1749:                 my ($key,$value)=split(/=/,$item,2);
                   1750:                 $key = &unescape($key);
                   1751:                 next if ($key =~ /^error: 2 /);
                   1752:                 $returnhash{$key}=&thaw_unescape($value);
                   1753:             }
                   1754:             my @esc_order = split(/\&/,$orderitems);
                   1755:             foreach my $item (@esc_order) {
                   1756:                 push(@order,&unescape($item));
                   1757:             }
                   1758:         } else {
                   1759:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1760:         }
                   1761:     }
                   1762:     return (\%returnhash,\@order);
                   1763: }
                   1764: 
1.868     raeburn  1765: sub is_domainimage {
                   1766:     my ($url) = @_;
                   1767:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1768:         if (&domain($1) ne '') {
                   1769:             return '1';
                   1770:         }
                   1771:     }
                   1772:     return;
                   1773: }
                   1774: 
1.899     raeburn  1775: sub inst_directory_query {
                   1776:     my ($srch) = @_;
                   1777:     my $udom = $srch->{'srchdomain'};
                   1778:     my %results;
                   1779:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1780:     my $outcome;
1.899     raeburn  1781:     if ($homeserver ne '') {
1.904     albertel 1782: 	my $queryid=&reply("querysend:instdirsearch:".
                   1783: 			   &escape($srch->{'srchby'}).':'.
                   1784: 			   &escape($srch->{'srchterm'}).':'.
                   1785: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1786: 	my $host=&hostname($homeserver);
                   1787: 	if ($queryid !~/^\Q$host\E\_/) {
                   1788: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1789: 	    return;
                   1790: 	}
                   1791: 	my $response = &get_query_reply($queryid);
                   1792: 	my $maxtries = 5;
                   1793: 	my $tries = 1;
                   1794: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1795: 	    $response = &get_query_reply($queryid);
                   1796: 	    $tries ++;
                   1797: 	}
                   1798: 
                   1799:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1800:             if ($response eq 'unavailable') {
                   1801:                 $outcome = $response;
                   1802:             } else {
                   1803:                 $outcome = 'ok';
                   1804:                 my @matches = split(/\n/,$response);
                   1805:                 foreach my $match (@matches) {
                   1806:                     my ($key,$value) = split(/=/,$match);
                   1807:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1808:                 }
1.899     raeburn  1809:             }
                   1810:         }
                   1811:     }
1.909     raeburn  1812:     return ($outcome,%results);
1.899     raeburn  1813: }
                   1814: 
                   1815: sub usersearch {
                   1816:     my ($srch) = @_;
                   1817:     my $dom = $srch->{'srchdomain'};
                   1818:     my %results;
                   1819:     my %libserv = &all_library();
                   1820:     my $query = 'usersearch';
                   1821:     foreach my $tryserver (keys(%libserv)) {
                   1822:         if (&host_domain($tryserver) eq $dom) {
                   1823:             my $host=&hostname($tryserver);
                   1824:             my $queryid=
1.911     raeburn  1825:                 &reply("querysend:".&escape($query).':'.
                   1826:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1827:                        &escape($srch->{'srchtype'}).':'.
                   1828:                        &escape($srch->{'srchterm'}),$tryserver);
                   1829:             if ($queryid !~/^\Q$host\E\_/) {
                   1830:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1831:                 next;
1.899     raeburn  1832:             }
                   1833:             my $reply = &get_query_reply($queryid);
                   1834:             my $maxtries = 1;
                   1835:             my $tries = 1;
                   1836:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1837:                 $reply = &get_query_reply($queryid);
                   1838:                 $tries ++;
                   1839:             }
                   1840:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1841:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1842:             } else {
1.911     raeburn  1843:                 my @matches;
                   1844:                 if ($reply =~ /\n/) {
                   1845:                     @matches = split(/\n/,$reply);
                   1846:                 } else {
                   1847:                     @matches = split(/\&/,$reply);
                   1848:                 }
1.899     raeburn  1849:                 foreach my $match (@matches) {
                   1850:                     my ($uname,$udom,%userhash);
1.911     raeburn  1851:                     foreach my $entry (split(/:/,$match)) {
                   1852:                         my ($key,$value) =
                   1853:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1854:                         $userhash{$key} = $value;
                   1855:                         if ($key eq 'username') {
                   1856:                             $uname = $value;
                   1857:                         } elsif ($key eq 'domain') {
                   1858:                             $udom = $value;
1.911     raeburn  1859:                         }
1.899     raeburn  1860:                     }
                   1861:                     $results{$uname.':'.$udom} = \%userhash;
                   1862:                 }
                   1863:             }
                   1864:         }
                   1865:     }
                   1866:     return %results;
                   1867: }
                   1868: 
1.912     raeburn  1869: sub get_instuser {
                   1870:     my ($udom,$uname,$id) = @_;
                   1871:     my $homeserver = &domain($udom,'primary');
                   1872:     my ($outcome,%results);
                   1873:     if ($homeserver ne '') {
                   1874:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1875:                            &escape($id).':'.&escape($udom),$homeserver);
                   1876:         my $host=&hostname($homeserver);
                   1877:         if ($queryid !~/^\Q$host\E\_/) {
                   1878:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1879:             return;
                   1880:         }
                   1881:         my $response = &get_query_reply($queryid);
                   1882:         my $maxtries = 5;
                   1883:         my $tries = 1;
                   1884:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1885:             $response = &get_query_reply($queryid);
                   1886:             $tries ++;
                   1887:         }
                   1888:         if (!&error($response) && $response ne 'refused') {
                   1889:             if ($response eq 'unavailable') {
                   1890:                 $outcome = $response;
                   1891:             } else {
                   1892:                 $outcome = 'ok';
                   1893:                 my @matches = split(/\n/,$response);
                   1894:                 foreach my $match (@matches) {
                   1895:                     my ($key,$value) = split(/=/,$match);
                   1896:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1897:                 }
                   1898:             }
                   1899:         }
                   1900:     }
                   1901:     my %userinfo;
                   1902:     if (ref($results{$uname}) eq 'HASH') {
                   1903:         %userinfo = %{$results{$uname}};
                   1904:     } 
                   1905:     return ($outcome,%userinfo);
                   1906: }
                   1907: 
                   1908: sub inst_rulecheck {
1.923     raeburn  1909:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1910:     my %returnhash;
                   1911:     if ($udom ne '') {
                   1912:         if (ref($rules) eq 'ARRAY') {
                   1913:             @{$rules} = map {&escape($_);} (@{$rules});
                   1914:             my $rulestr = join(':',@{$rules});
                   1915:             my $homeserver=&domain($udom,'primary');
                   1916:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1917:                 my $response;
                   1918:                 if ($item eq 'username') {                
                   1919:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1920:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1921:                                               $homeserver));
1.923     raeburn  1922:                 } elsif ($item eq 'id') {
                   1923:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1924:                                               ':'.&escape($id).':'.$rulestr,
                   1925:                                               $homeserver));
1.945     raeburn  1926:                 } elsif ($item eq 'selfcreate') {
                   1927:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1928:                                                &escape($udom).':'.&escape($uname).
                   1929:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1930:                 }
1.912     raeburn  1931:                 if ($response ne 'refused') {
                   1932:                     my @pairs=split(/\&/,$response);
                   1933:                     foreach my $item (@pairs) {
                   1934:                         my ($key,$value)=split(/=/,$item,2);
                   1935:                         $key = &unescape($key);
                   1936:                         next if ($key =~ /^error: 2 /);
                   1937:                         $returnhash{$key}=&thaw_unescape($value);
                   1938:                     }
                   1939:                 }
                   1940:             }
                   1941:         }
                   1942:     }
                   1943:     return %returnhash;
                   1944: }
                   1945: 
                   1946: sub inst_userrules {
1.923     raeburn  1947:     my ($udom,$check) = @_;
1.912     raeburn  1948:     my (%ruleshash,@ruleorder);
                   1949:     if ($udom ne '') {
                   1950:         my $homeserver=&domain($udom,'primary');
                   1951:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1952:             my $response;
                   1953:             if ($check eq 'id') {
                   1954:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1955:                                  $homeserver);
1.943     raeburn  1956:             } elsif ($check eq 'email') {
                   1957:                 $response=&reply('instemailrules:'.&escape($udom),
                   1958:                                  $homeserver);
1.923     raeburn  1959:             } else {
                   1960:                 $response=&reply('instuserrules:'.&escape($udom),
                   1961:                                  $homeserver);
                   1962:             }
1.912     raeburn  1963:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1964:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1965:                 ($response ne 'no_such_host')) {
                   1966:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1967:                 my @pairs=split(/\&/,$hashitems);
                   1968:                 foreach my $item (@pairs) {
                   1969:                     my ($key,$value)=split(/=/,$item,2);
                   1970:                     $key = &unescape($key);
                   1971:                     next if ($key =~ /^error: 2 /);
                   1972:                     $ruleshash{$key}=&thaw_unescape($value);
                   1973:                 }
                   1974:                 my @esc_order = split(/\&/,$orderitems);
                   1975:                 foreach my $item (@esc_order) {
                   1976:                     push(@ruleorder,&unescape($item));
                   1977:                 }
                   1978:             }
                   1979:         }
                   1980:     }
                   1981:     return (\%ruleshash,\@ruleorder);
                   1982: }
                   1983: 
1.976     raeburn  1984: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1985: 
                   1986: sub get_domain_defaults {
1.1240  ! raeburn  1987:     my ($domain,$ignore_cache) = @_;
1.943     raeburn  1988:     my $cachetime = 60*60*24;
1.1240  ! raeburn  1989:     unless ($ignore_cache) {
        !          1990:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
        !          1991:         if (defined($cached)) {
        !          1992:             if (ref($result) eq 'HASH') {
        !          1993:                 return %{$result};
        !          1994:             }
1.943     raeburn  1995:         }
                   1996:     }
                   1997:     my %domdefaults;
                   1998:     my %domconfig =
1.989     raeburn  1999:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2000:                                   'requestcourses','inststatus',
1.1183    raeburn  2001:                                   'coursedefaults','usersessions',
                   2002:                                   'requestauthor'],$domain);
1.943     raeburn  2003:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2004:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2005:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2006:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2007:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2008:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2009:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2010:     } else {
                   2011:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2012:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2013:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2014:     }
1.976     raeburn  2015:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2016:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2017:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2018:         } else {
                   2019:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2020:         }
1.1177    raeburn  2021:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2022:         foreach my $item (@usertools) {
                   2023:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2024:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2025:             }
                   2026:         }
1.1229    raeburn  2027:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2028:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2029:         }
1.976     raeburn  2030:     }
1.985     raeburn  2031:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  2032:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  2033:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2034:         }
                   2035:     }
1.1183    raeburn  2036:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2037:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2038:     }
1.989     raeburn  2039:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2040:         foreach my $item ('inststatustypes','inststatusorder') {
                   2041:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2042:         }
                   2043:     }
1.1047    raeburn  2044:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2045:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216    raeburn  2046:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2047:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2048:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
                   2049:         }
1.1230    raeburn  2050:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2051:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
                   2052:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
                   2053:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
                   2054:         }
1.1047    raeburn  2055:     }
1.1073    raeburn  2056:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2057:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2058:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2059:         }
                   2060:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2061:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2062:         }
                   2063:     }
1.1219    raeburn  2064:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2065:     return %domdefaults;
                   2066: }
                   2067: 
1.344     www      2068: # --------------------------------------------------- Assign a key to a student
                   2069: 
                   2070: sub assign_access_key {
1.364     www      2071: #
                   2072: # a valid key looks like uname:udom#comments
                   2073: # comments are being appended
                   2074: #
1.498     www      2075:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2076:     $kdom=
1.620     albertel 2077:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2078:     $knum=
1.620     albertel 2079:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2080:     $cdom=
1.620     albertel 2081:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2082:     $cnum=
1.620     albertel 2083:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2084:     $udom=$env{'user.name'} unless (defined($udom));
                   2085:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2086:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2087:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2088:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2089:                                                   # assigned to this person
                   2090:                                                   # - this should not happen,
1.345     www      2091:                                                   # unless something went wrong
                   2092:                                                   # the first time around
                   2093: # ready to assign
1.364     www      2094:         $logentry=$1.'; '.$logentry;
1.496     www      2095:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2096:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2097: # key now belongs to user
1.346     www      2098: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2099:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2100:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2101:                 return 'ok';
                   2102:             } else {
                   2103:                 return 
                   2104:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2105: 	    }
                   2106:         } else {
                   2107:             return 'error: Could not assign key, try again later.';
                   2108:         }
1.364     www      2109:     } elsif (!$existing{$ckey}) {
1.345     www      2110: # the key does not exist
                   2111: 	return 'error: The key does not exist';
                   2112:     } else {
                   2113: # the key is somebody else's
                   2114: 	return 'error: The key is already in use';
                   2115:     }
1.344     www      2116: }
                   2117: 
1.364     www      2118: # ------------------------------------------ put an additional comment on a key
                   2119: 
                   2120: sub comment_access_key {
                   2121: #
                   2122: # a valid key looks like uname:udom#comments
                   2123: # comments are being appended
                   2124: #
                   2125:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2126:     $cdom=
1.620     albertel 2127:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2128:     $cnum=
1.620     albertel 2129:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2130:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2131:     if ($existing{$ckey}) {
                   2132:         $existing{$ckey}.='; '.$logentry;
                   2133: # ready to assign
1.367     www      2134:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2135:                                                  $cdom,$cnum) eq 'ok') {
                   2136: 	    return 'ok';
                   2137:         } else {
                   2138: 	    return 'error: Count not store comment.';
                   2139:         }
                   2140:     } else {
                   2141: # the key does not exist
                   2142: 	return 'error: The key does not exist';
                   2143:     }
                   2144: }
                   2145: 
1.344     www      2146: # ------------------------------------------------------ Generate a set of keys
                   2147: 
                   2148: sub generate_access_keys {
1.364     www      2149:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2150:     $cdom=
1.620     albertel 2151:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2152:     $cnum=
1.620     albertel 2153:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2154:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2155:     unless (($cdom) && ($cnum)) { return 0; }
                   2156:     if ($number>10000) { return 0; }
                   2157:     sleep(2); # make sure don't get same seed twice
                   2158:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2159:     my $total=0;
                   2160:     for (my $i=1;$i<=$number;$i++) {
                   2161:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2162:                   sprintf("%lx",int(100000*rand)).'-'.
                   2163:                   sprintf("%lx",int(100000*rand));
                   2164:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2165:        $newkey=~s/0/h/g; # and also 0 and O
                   2166:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2167:        if ($existing{$newkey}) {
                   2168:            $i--;
                   2169:        } else {
1.364     www      2170: 	  if (&put('accesskeys',
                   2171:               { $newkey => '# generated '.localtime().
1.620     albertel 2172:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2173:                            '; '.$logentry },
                   2174: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2175:               $total++;
                   2176: 	  }
                   2177:        }
                   2178:     }
1.620     albertel 2179:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2180:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2181:     return $total;
                   2182: }
                   2183: 
                   2184: # ------------------------------------------------------- Validate an accesskey
                   2185: 
                   2186: sub validate_access_key {
                   2187:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2188:     $cdom=
1.620     albertel 2189:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2190:     $cnum=
1.620     albertel 2191:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2192:     $udom=$env{'user.domain'} unless (defined($udom));
                   2193:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2194:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2195:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2196: }
                   2197: 
                   2198: # ------------------------------------- Find the section of student in a course
1.652     albertel 2199: sub devalidate_getsection_cache {
                   2200:     my ($udom,$unam,$courseid)=@_;
                   2201:     my $hashid="$udom:$unam:$courseid";
                   2202:     &devalidate_cache_new('getsection',$hashid);
                   2203: }
1.298     matthew  2204: 
1.815     albertel 2205: sub courseid_to_courseurl {
                   2206:     my ($courseid) = @_;
                   2207:     #already url style courseid
                   2208:     return $courseid if ($courseid =~ m{^/});
                   2209: 
                   2210:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2211: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2212: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2213: 	return "/$cdom/$cnum";
                   2214:     }
                   2215: 
                   2216:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2217:     if (exists($courseinfo{'num'})) {
                   2218: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2219:     }
                   2220: 
                   2221:     return undef;
                   2222: }
                   2223: 
1.298     matthew  2224: sub getsection {
                   2225:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2226:     my $cachetime=1800;
1.551     albertel 2227: 
                   2228:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2229:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2230:     if (defined($cached)) { return $result; }
                   2231: 
1.298     matthew  2232:     my %Pending; 
                   2233:     my %Expired;
                   2234:     #
                   2235:     # Each role can either have not started yet (pending), be active, 
                   2236:     #    or have expired.
                   2237:     #
                   2238:     # If there is an active role, we are done.
                   2239:     #
                   2240:     # If there is more than one role which has not started yet, 
                   2241:     #     choose the one which will start sooner
                   2242:     # If there is one role which has not started yet, return it.
                   2243:     #
                   2244:     # If there is more than one expired role, choose the one which ended last.
                   2245:     # If there is a role which has expired, return it.
                   2246:     #
1.815     albertel 2247:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2248:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2249:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2250:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2251:         my $section=$1;
                   2252:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2253:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2254:         my $now=time;
1.548     albertel 2255:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2256:             $Expired{$end}=$section;
                   2257:             next;
                   2258:         }
1.548     albertel 2259:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2260:             $Pending{$start}=$section;
                   2261:             next;
                   2262:         }
1.599     albertel 2263:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2264:     }
                   2265:     #
                   2266:     # Presumedly there will be few matching roles from the above
                   2267:     # loop and the sorting time will be negligible.
                   2268:     if (scalar(keys(%Pending))) {
                   2269:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2270:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2271:     } 
                   2272:     if (scalar(keys(%Expired))) {
                   2273:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2274:         my $time = pop(@sorted);
1.599     albertel 2275:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2276:     }
1.599     albertel 2277:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2278: }
1.70      www      2279: 
1.599     albertel 2280: sub save_cache {
                   2281:     &purge_remembered();
1.722     albertel 2282:     #&Apache::loncommon::validate_page();
1.620     albertel 2283:     undef(%env);
1.780     albertel 2284:     undef($env_loaded);
1.599     albertel 2285: }
1.452     albertel 2286: 
1.599     albertel 2287: my $to_remember=-1;
                   2288: my %remembered;
                   2289: my %accessed;
                   2290: my $kicks=0;
                   2291: my $hits=0;
1.849     albertel 2292: sub make_key {
                   2293:     my ($name,$id) = @_;
1.872     albertel 2294:     if (length($id) > 65 
                   2295: 	&& length(&escape($id)) > 200) {
                   2296: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2297:     }
1.849     albertel 2298:     return &escape($name.':'.$id);
                   2299: }
                   2300: 
1.599     albertel 2301: sub devalidate_cache_new {
                   2302:     my ($name,$id,$debug) = @_;
                   2303:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2304:     $id=&make_key($name,$id);
1.599     albertel 2305:     $memcache->delete($id);
                   2306:     delete($remembered{$id});
                   2307:     delete($accessed{$id});
                   2308: }
                   2309: 
                   2310: sub is_cached_new {
                   2311:     my ($name,$id,$debug) = @_;
1.849     albertel 2312:     $id=&make_key($name,$id);
1.599     albertel 2313:     if (exists($remembered{$id})) {
1.1133    foxr     2314: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2315: 	$accessed{$id}=[&gettimeofday()];
                   2316: 	$hits++;
                   2317: 	return ($remembered{$id},1);
                   2318:     }
                   2319:     my $value = $memcache->get($id);
                   2320:     if (!(defined($value))) {
                   2321: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2322: 	return (undef,undef);
1.416     albertel 2323:     }
1.599     albertel 2324:     if ($value eq '__undef__') {
                   2325: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2326: 	$value=undef;
                   2327:     }
                   2328:     &make_room($id,$value,$debug);
                   2329:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2330:     return ($value,1);
                   2331: }
                   2332: 
                   2333: sub do_cache_new {
                   2334:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2335:     $id=&make_key($name,$id);
1.599     albertel 2336:     my $setvalue=$value;
                   2337:     if (!defined($setvalue)) {
                   2338: 	$setvalue='__undef__';
                   2339:     }
1.623     albertel 2340:     if (!defined($time) ) {
                   2341: 	$time=600;
                   2342:     }
1.599     albertel 2343:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2344:     my $result = $memcache->set($id,$setvalue,$time);
                   2345:     if (! $result) {
1.872     albertel 2346: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2347: 	$memcache->disconnect_all();
1.872     albertel 2348:     }
1.600     albertel 2349:     # need to make a copy of $value
1.919     albertel 2350:     &make_room($id,$value,$debug);
1.599     albertel 2351:     return $value;
                   2352: }
                   2353: 
                   2354: sub make_room {
                   2355:     my ($id,$value,$debug)=@_;
1.919     albertel 2356: 
                   2357:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2358:                                     : $value;
1.599     albertel 2359:     if ($to_remember<0) { return; }
                   2360:     $accessed{$id}=[&gettimeofday()];
                   2361:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2362:     my $to_kick;
                   2363:     my $max_time=0;
                   2364:     foreach my $other (keys(%accessed)) {
                   2365: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2366: 	    $to_kick=$other;
                   2367: 	    $max_time=&tv_interval($accessed{$other});
                   2368: 	}
                   2369:     }
                   2370:     delete($remembered{$to_kick});
                   2371:     delete($accessed{$to_kick});
                   2372:     $kicks++;
                   2373:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2374:     return;
                   2375: }
                   2376: 
1.599     albertel 2377: sub purge_remembered {
1.604     albertel 2378:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2379:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2380:     undef(%remembered);
                   2381:     undef(%accessed);
1.428     albertel 2382: }
1.70      www      2383: # ------------------------------------- Read an entry from a user's environment
                   2384: 
                   2385: sub userenvironment {
                   2386:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2387:     my $items;
                   2388:     foreach my $item (@what) {
                   2389:         $items.=&escape($item).'&';
                   2390:     }
                   2391:     $items=~s/\&$//;
1.70      www      2392:     my %returnhash=();
1.1009    raeburn  2393:     my $uhome = &homeserver($unam,$udom);
                   2394:     unless ($uhome eq 'no_host') {
                   2395:         my @answer=split(/\&/, 
                   2396:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2397:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2398:             return %returnhash;
                   2399:         }
1.1009    raeburn  2400:         my $i;
                   2401:         for ($i=0;$i<=$#what;$i++) {
                   2402: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2403:         }
1.70      www      2404:     }
                   2405:     return %returnhash;
1.1       albertel 2406: }
                   2407: 
1.617     albertel 2408: # ---------------------------------------------------------- Get a studentphoto
                   2409: sub studentphoto {
                   2410:     my ($udom,$unam,$ext) = @_;
                   2411:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2412:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2413:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2414:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2415:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2416:             } else {
                   2417:                 my ($result,$perm_reqd)=
1.707     albertel 2418: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2419:                 if ($result eq 'ok') {
                   2420:                     if (!($perm_reqd eq 'yes')) {
                   2421:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2422:                     }
                   2423:                 }
                   2424:             }
                   2425:         }
                   2426:     } else {
                   2427:         my ($result,$perm_reqd) = 
1.707     albertel 2428: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2429:         if ($result eq 'ok') {
                   2430:             if (!($perm_reqd eq 'yes')) {
                   2431:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2432:             }
                   2433:         }
                   2434:     }
                   2435:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2436: }
                   2437: 
                   2438: sub retrievestudentphoto {
                   2439:     my ($udom,$unam,$ext,$type) = @_;
                   2440:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2441:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2442:     if ($ret eq 'ok') {
                   2443:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2444:         if ($type eq 'thumbnail') {
                   2445:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2446:         }
                   2447:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2448:         return $tokenurl;
                   2449:     } else {
                   2450:         if ($type eq 'thumbnail') {
                   2451:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2452:         } else { 
                   2453:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2454:         }
1.617     albertel 2455:     }
                   2456: }
                   2457: 
1.263     www      2458: # -------------------------------------------------------------------- New chat
                   2459: 
                   2460: sub chatsend {
1.724     raeburn  2461:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2462:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2463:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2464:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2465:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2466: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2467: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2468: }
                   2469: 
                   2470: # ------------------------------------------ Find current version of a resource
                   2471: 
                   2472: sub getversion {
                   2473:     my $fname=&clutter(shift);
1.1189    raeburn  2474:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2475:     return &currentversion(&filelocation('',$fname));
                   2476: }
                   2477: 
                   2478: sub currentversion {
                   2479:     my $fname=shift;
                   2480:     my $author=$fname;
                   2481:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2482:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2483:     my $home=&homeserver($uname,$udom);
1.292     www      2484:     if ($home eq 'no_host') { 
                   2485:         return -1; 
                   2486:     }
1.1112    www      2487:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2488:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2489: 	return -1;
                   2490:     }
1.1112    www      2491:     return $answer;
1.263     www      2492: }
                   2493: 
1.1111    www      2494: #
                   2495: # Return special version number of resource if set by override, empty otherwise
                   2496: #
                   2497: sub usedversion {
                   2498:     my $fname=shift;
                   2499:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2500:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2501:     if ($urlversion) { return $urlversion; }
                   2502:     return '';
                   2503: }
                   2504: 
1.1       albertel 2505: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2506: 
1.1       albertel 2507: sub subscribe {
                   2508:     my $fname=shift;
1.761     raeburn  2509:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2510:     $fname=~s/[\n\r]//g;
1.1       albertel 2511:     my $author=$fname;
                   2512:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2513:     my ($udom,$uname)=split(/\//,$author);
                   2514:     my $home=homeserver($uname,$udom);
1.335     albertel 2515:     if ($home eq 'no_host') {
                   2516:         return 'not_found';
1.1       albertel 2517:     }
                   2518:     my $answer=reply("sub:$fname",$home);
1.64      www      2519:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2520: 	$answer.=' by '.$home;
                   2521:     }
1.1       albertel 2522:     return $answer;
                   2523: }
                   2524:     
1.8       www      2525: # -------------------------------------------------------------- Replicate file
                   2526: 
                   2527: sub repcopy {
                   2528:     my $filename=shift;
1.23      www      2529:     $filename=~s/\/+/\//g;
1.1142    raeburn  2530:     my $londocroot = $perlvar{'lonDocRoot'};
                   2531:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2532:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2533:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2534: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2535: 	return &repcopy_userfile($filename);
                   2536:     }
1.532     albertel 2537:     $filename=~s/[\n\r]//g;
1.8       www      2538:     my $transname="$filename.in.transfer";
1.828     www      2539: # FIXME: this should flock
1.607     raeburn  2540:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2541:     my $remoteurl=subscribe($filename);
1.64      www      2542:     if ($remoteurl =~ /^con_lost by/) {
                   2543: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2544:            return 'unavailable';
1.8       www      2545:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2546: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2547: 	   return 'not_found';
1.64      www      2548:     } elsif ($remoteurl =~ /^rejected by/) {
                   2549: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2550:            return 'forbidden';
1.20      www      2551:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2552:            return 'ok';
1.8       www      2553:     } else {
1.290     www      2554:         my $author=$filename;
                   2555:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2556:         my ($udom,$uname)=split(/\//,$author);
                   2557:         my $home=homeserver($uname,$udom);
                   2558:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2559:            my @parts=split(/\//,$filename);
                   2560:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2561:            if ($path ne "$londocroot/res") {
1.8       www      2562:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2563: 	       return 'bad_request';
1.8       www      2564:            }
                   2565:            my $count;
                   2566:            for ($count=5;$count<$#parts;$count++) {
                   2567:                $path.="/$parts[$count]";
                   2568:                if ((-e $path)!=1) {
                   2569: 		   mkdir($path,0777);
                   2570:                }
                   2571:            }
                   2572:            my $ua=new LWP::UserAgent;
                   2573:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2574:            my $response=$ua->request($request,$transname);
                   2575:            if ($response->is_error()) {
                   2576: 	       unlink($transname);
                   2577:                my $message=$response->status_line;
1.672     albertel 2578:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2579:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2580:                return 'unavailable';
1.8       www      2581:            } else {
1.16      www      2582: 	       if ($remoteurl!~/\.meta$/) {
                   2583:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2584:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2585:                   if ($mresponse->is_error()) {
                   2586: 		      unlink($filename.'.meta');
                   2587:                       &logthis(
1.672     albertel 2588:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2589:                   }
                   2590: 	       }
1.8       www      2591:                rename($transname,$filename);
1.607     raeburn  2592:                return 'ok';
1.8       www      2593:            }
1.290     www      2594:        }
1.8       www      2595:     }
1.330     www      2596: }
                   2597: 
                   2598: # ------------------------------------------------ Get server side include body
                   2599: sub ssi_body {
1.381     albertel 2600:     my ($filelink,%form)=@_;
1.606     matthew  2601:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2602:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2603:     }
1.953     www      2604:     my $output='';
                   2605:     my $response;
1.980     raeburn  2606:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2607:        ($output,$response)=&externalssi($filelink);
1.953     www      2608:     } else {
1.1004    droeschl 2609:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2610:        $filelink .= 'inhibitmenu=yes';
1.953     www      2611:        ($output,$response)=&ssi($filelink,%form);
                   2612:     }
1.778     albertel 2613:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2614:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2615:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2616:     if (wantarray) {
                   2617:         return ($output, $response);
                   2618:     } else {
                   2619:         return $output;
                   2620:     }
1.8       www      2621: }
                   2622: 
1.15      www      2623: # --------------------------------------------------------- Server Side Include
                   2624: 
1.782     albertel 2625: sub absolute_url {
                   2626:     my ($host_name) = @_;
                   2627:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2628:     if ($host_name eq '') {
                   2629: 	$host_name = $ENV{'SERVER_NAME'};
                   2630:     }
                   2631:     return $protocol.$host_name;
                   2632: }
                   2633: 
1.942     foxr     2634: #
                   2635: #   Server side include.
                   2636: # Parameters:
                   2637: #  fn     Possibly encrypted resource name/id.
                   2638: #  form   Hash that describes how the rendering should be done
                   2639: #         and other things.
1.944     foxr     2640: # Returns:
1.950     raeburn  2641: #   Scalar context: The content of the response.
                   2642: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2643: #     
1.15      www      2644: sub ssi {
                   2645: 
1.944     foxr     2646:     my ($fn,%form)=@_;
1.15      www      2647:     my $ua=new LWP::UserAgent;
1.23      www      2648:     my $request;
1.711     albertel 2649: 
                   2650:     $form{'no_update_last_known'}=1;
1.895     albertel 2651:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2652:     if (%form) {
1.782     albertel 2653:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2654:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2655:     } else {
1.782     albertel 2656:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2657:     }
                   2658: 
1.15      www      2659:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2660:     my $response= $ua->request($request);
1.1182    foxr     2661:     my $content = $response->content;
                   2662: 
                   2663: 
1.944     foxr     2664:     if (wantarray) {
1.1173    foxr     2665: 	return ($content, $response);
1.944     foxr     2666:     } else {
1.1173    foxr     2667: 	return $content;
1.942     foxr     2668:     }
1.324     www      2669: }
                   2670: 
                   2671: sub externalssi {
                   2672:     my ($url)=@_;
                   2673:     my $ua=new LWP::UserAgent;
                   2674:     my $request=new HTTP::Request('GET',$url);
                   2675:     my $response=$ua->request($request);
1.954     raeburn  2676:     if (wantarray) {
                   2677:         return ($response->content, $response);
                   2678:     } else {
                   2679:         return $response->content;
                   2680:     }
1.15      www      2681: }
1.254     www      2682: 
1.492     albertel 2683: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2684: 
                   2685: sub allowuploaded {
                   2686:     my ($srcurl,$url)=@_;
                   2687:     $url=&clutter(&declutter($url));
                   2688:     my $dir=$url;
                   2689:     $dir=~s/\/[^\/]+$//;
                   2690:     my %httpref=();
                   2691:     my $httpurl=&hreflocation('',$url);
                   2692:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2693:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2694: }
1.477     raeburn  2695: 
1.1193    raeburn  2696: #
                   2697: # Determine if the current user should be able to edit a particular resource,
                   2698: # when viewing in course context.
                   2699: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2700: #     Functions.
                   2701: # (b) When displaying folder contents in course editor, used to determine if
                   2702: #     "Edit" link will be displayed alongside resource.
                   2703: #
1.1196    raeburn  2704: #  input: six args -- filename (decluttered), course number, course domain,
                   2705: #                   url, symb (if registered) and group (if this is a group
                   2706: #                   item -- e.g., bulletin board, group page etc.).
                   2707: #  output: array of five scalars -- 
1.1193    raeburn  2708: #          $cfile -- url for file editing if editable on current server
                   2709: #          $home -- homeserver of resource (i.e., for author if published,
                   2710: #                                           or course if uploaded.).
                   2711: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2712: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2713: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2714: #
                   2715: 
                   2716: sub can_edit_resource {
1.1194    raeburn  2717:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2718:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2719: #
                   2720: # For aboutme pages user can only edit his/her own.
                   2721: #
1.1199    raeburn  2722:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2723:         my ($sdom,$sname) = ($1,$2);
                   2724:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2725:             $home = $env{'user.home'};
                   2726:             $cfile = $resurl;
                   2727:             if ($env{'form.forceedit'}) {
                   2728:                 $forceview = 1;
                   2729:             } else {
                   2730:                 $forceedit = 1;
                   2731:             }
                   2732:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2733:         } else {
                   2734:             return;
                   2735:         }
                   2736:     }
                   2737: 
                   2738:     if ($env{'request.course.id'}) {
                   2739:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2740:         if ($group ne '') {
                   2741: # if this is a group homepage or group bulletin board, check group privs
                   2742:             my $allowed = 0;
1.1197    raeburn  2743:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2744:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2745:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2746:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2747:                     $allowed = 1;
                   2748:                 }
1.1197    raeburn  2749:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2750:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2751:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2752:                     $allowed = 1;
                   2753:                 }
                   2754:             }
                   2755:             if ($allowed) {
                   2756:                 $home=&homeserver($cnum,$cdom);
                   2757:                 if ($env{'form.forceedit'}) {
                   2758:                     $forceview = 1;
                   2759:                 } else {
                   2760:                     $forceedit = 1;
                   2761:                 }
                   2762:                 $cfile = $resurl;
                   2763:             } else {
                   2764:                 return;
                   2765:             }
                   2766:         } else {
1.1208    raeburn  2767:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2768:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2769:                     return;
                   2770:                 }
                   2771:             } elsif (!$crsedit) {
1.1194    raeburn  2772: #
                   2773: # No edit allowed where CC has switched to student role.
                   2774: #
                   2775:                 return;
                   2776:             }
                   2777:         }
                   2778:     }
                   2779: 
1.1193    raeburn  2780:     if ($file ne '') {
                   2781:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2782:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2783:                 $uploaded = 1;
                   2784:                 $incourse = 1;
1.1193    raeburn  2785:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2786:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2787:                     if ($env{'form.forceedit'}) {
                   2788:                         $forceview = 1;
                   2789:                     } else {
                   2790:                         $forceedit = 1;
                   2791:                     }
1.1194    raeburn  2792:                 }
                   2793:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2794:                 $incourse = 1;
                   2795:                 if ($env{'form.forceedit'}) {
                   2796:                     $forceview = 1;
                   2797:                 } else {
                   2798:                     $forceedit = 1;
                   2799:                 }
                   2800:                 $cfile = $resurl;
                   2801:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2802:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2803:                     $incourse = 1;
                   2804:                     if ($env{'form.forceedit'}) {
                   2805:                         $forceview = 1;
                   2806:                     } else {
                   2807:                         $forceedit = 1;
                   2808:                     }
                   2809:                     $cfile = $resurl;
1.1199    raeburn  2810:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2811:                     $incourse = 1;
                   2812:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2813:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2814:                     $incourse = 1;
1.1199    raeburn  2815:                     if ($env{'form.forceedit'}) {
                   2816:                         $forceview = 1;
                   2817:                     } else {
                   2818:                         $forceedit = 1;
                   2819:                     }
                   2820:                     $cfile = $resurl;
1.1208    raeburn  2821:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2822:                     $incourse = 1;
                   2823:                     if ($env{'form.forceedit'}) {
                   2824:                         $forceview = 1;
                   2825:                     } else {
                   2826:                         $forceedit = 1;
                   2827:                     }
                   2828:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2829:                 }
                   2830:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2831:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2832:                 if (&is_on_map($template)) { 
                   2833:                     $incourse = 1;
                   2834:                     $forceview = 1;
                   2835:                     $cfile = $template;
1.1193    raeburn  2836:                 }
1.1199    raeburn  2837:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2838:                     $incourse = 1;
                   2839:                     if ($env{'form.forceedit'}) {
                   2840:                         $forceview = 1;
                   2841:                     } else {
                   2842:                         $forceedit = 1;
                   2843:                     }
                   2844:                     $cfile = $resurl;
                   2845:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2846:                 $incourse = 1;
                   2847:                 $forceview = 1;
                   2848:                 if ($symb) {
                   2849:                     my ($map,$id,$res)=&decode_symb($symb);
                   2850:                     $env{'request.symb'} = $symb;
                   2851:                     $cfile = &clutter($res);
                   2852:                 } else {
                   2853:                     $cfile = $env{'form.suppurl'};
                   2854:                     $cfile =~ s{^http://}{};
                   2855:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2856:                 }
1.1234    raeburn  2857:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2858:                 if ($env{'form.forceedit'}) {
                   2859:                     $forceview = 1;
                   2860:                 } else {
                   2861:                     $forceedit = 1;
                   2862:                 }
                   2863:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  2864:             }
                   2865:         }
1.1194    raeburn  2866:         if ($uploaded || $incourse) {
                   2867:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2868:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2869:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2870:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2871:             # Check that the user has permission to edit this resource
                   2872:             my $setpriv = 1;
                   2873:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2874:             if (defined($cfudom)) {
                   2875:                 $home=&homeserver($cfuname,$cfudom);
                   2876:                 $cfile=$file;
                   2877:             }
                   2878:         }
1.1194    raeburn  2879:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2880:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2881:             my @ids=&current_machine_ids();
                   2882:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2883:                 $switchserver=1;
                   2884:             }
                   2885:         }
                   2886:     }
1.1194    raeburn  2887:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2888: }
                   2889: 
                   2890: sub is_course_upload {
                   2891:     my ($file,$cnum,$cdom) = @_;
                   2892:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2893:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2894:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2895:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2896:         return 1;
                   2897:     }
                   2898:     return;
                   2899: }
                   2900: 
1.1194    raeburn  2901: sub in_course {
1.1195    raeburn  2902:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2903:     if ($hideprivileged) {
                   2904:         my $skipuser;
1.1219    raeburn  2905:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2906:         my @possdoms = ($cdom);  
                   2907:         if ($coursehash{'checkforpriv'}) { 
                   2908:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   2909:         }
                   2910:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  2911:             $skipuser = 1;
                   2912:             if ($coursehash{'nothideprivileged'}) {
                   2913:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2914:                     my $user;
                   2915:                     if ($item =~ /:/) {
                   2916:                         $user = $item;
                   2917:                     } else {
                   2918:                         $user = join(':',split(/[\@]/,$item));
                   2919:                     }
                   2920:                     if ($user eq $uname.':'.$udom) {
                   2921:                         undef($skipuser);
                   2922:                         last;
                   2923:                     }
                   2924:                 }
                   2925:             }
                   2926:             if ($skipuser) {
                   2927:                 return 0;
                   2928:             }
                   2929:         }
                   2930:     }
1.1194    raeburn  2931:     $type ||= 'any';
                   2932:     if (!defined($cdom) || !defined($cnum)) {
                   2933:         my $cid  = $env{'request.course.id'};
                   2934:         $cdom = $env{'course.'.$cid.'.domain'};
                   2935:         $cnum = $env{'course.'.$cid.'.num'};
                   2936:     }
                   2937:     my $typesref;
1.1195    raeburn  2938:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  2939:         $typesref = ['active','previous','future'];
                   2940:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2941:         $typesref = [$type];
                   2942:     }
                   2943:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2944:                               $typesref,undef,[$cdom]);
                   2945:     my ($tmp) = keys(%roles);
                   2946:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2947:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2948:     if (@course_roles > 0) {
                   2949:         return 1;
                   2950:     }
                   2951:     return 0;
                   2952: }
                   2953: 
1.478     albertel 2954: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2955: # input: action, courseID, current domain, intended
1.637     raeburn  2956: #        path to file, source of file, instruction to parse file for objects,
                   2957: #        ref to hash for embedded objects,
                   2958: #        ref to hash for codebase of java objects.
1.1095    raeburn  2959: #        reference to scalar to accommodate mime type determined
                   2960: #          from File::MMagic if $parser = parse.
1.637     raeburn  2961: #
1.485     raeburn  2962: # output: url to file (if action was uploaddoc), 
                   2963: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2964: #
1.478     albertel 2965: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2966: # course.
1.477     raeburn  2967: #
1.478     albertel 2968: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2969: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2970: #          course's home server.
1.477     raeburn  2971: #
1.478     albertel 2972: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2973: #          be copied from $source (current location) to 
                   2974: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2975: #         and will then be copied to
                   2976: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2977: #         course's home server.
1.485     raeburn  2978: #
1.481     raeburn  2979: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2980: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2981: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2982: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2983: #         in course's home server.
1.637     raeburn  2984: #
1.477     raeburn  2985: 
                   2986: sub process_coursefile {
1.1095    raeburn  2987:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2988:         $mimetype)=@_;
1.477     raeburn  2989:     my $fetchresult;
1.638     albertel 2990:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2991:     if ($action eq 'propagate') {
1.638     albertel 2992:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2993: 			     $home);
1.481     raeburn  2994:     } else {
1.477     raeburn  2995:         my $fpath = '';
                   2996:         my $fname = $file;
1.478     albertel 2997:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2998:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2999:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3000:         if ($action eq 'copy') {
                   3001:             if ($source eq '') {
                   3002:                 $fetchresult = 'no source file';
                   3003:                 return $fetchresult;
                   3004:             } else {
                   3005:                 my $destination = $filepath.'/'.$fname;
                   3006:                 rename($source,$destination);
                   3007:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3008:                                  $home);
1.481     raeburn  3009:             }
                   3010:         } elsif ($action eq 'uploaddoc') {
                   3011:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3012:             print $fh $env{'form.'.$source};
1.481     raeburn  3013:             close($fh);
1.637     raeburn  3014:             if ($parser eq 'parse') {
1.1024    raeburn  3015:                 my $mm = new File::MMagic;
1.1095    raeburn  3016:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3017:                 if ($type eq 'text/html') {
1.1024    raeburn  3018:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3019:                     unless ($parse_result eq 'ok') {
                   3020:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3021:                     }
1.637     raeburn  3022:                 }
1.1095    raeburn  3023:                 if (ref($mimetype)) {
                   3024:                     $$mimetype = $type;
                   3025:                 } 
1.637     raeburn  3026:             }
1.477     raeburn  3027:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3028:                                  $home);
1.481     raeburn  3029:             if ($fetchresult eq 'ok') {
                   3030:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3031:             } else {
                   3032:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3033:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3034:                 return '/adm/notfound.html';
                   3035:             }
1.477     raeburn  3036:         }
                   3037:     }
1.485     raeburn  3038:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3039:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3040:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3041:     }
                   3042:     return $fetchresult;
                   3043: }
                   3044: 
1.637     raeburn  3045: sub build_filepath {
                   3046:     my ($fpath) = @_;
                   3047:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3048:     unless ($fpath eq '') {
                   3049:         my @parts=split('/',$fpath);
                   3050:         foreach my $part (@parts) {
                   3051:             $filepath.= '/'.$part;
                   3052:             if ((-e $filepath)!=1) {
                   3053:                 mkdir($filepath,0777);
                   3054:             }
                   3055:         }
                   3056:     }
                   3057:     return $filepath;
                   3058: }
                   3059: 
                   3060: sub store_edited_file {
1.638     albertel 3061:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3062:     my $file = $primary_url;
                   3063:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3064:     my $fpath = '';
                   3065:     my $fname = $file;
                   3066:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3067:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3068:     my $filepath = &build_filepath($fpath);
                   3069:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3070:     print $fh $content;
                   3071:     close($fh);
1.638     albertel 3072:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3073:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3074: 			  $home);
1.637     raeburn  3075:     if ($$fetchresult eq 'ok') {
                   3076:         return '/uploaded/'.$fpath.'/'.$fname;
                   3077:     } else {
1.638     albertel 3078:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3079: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3080:         return '/adm/notfound.html';
                   3081:     }
                   3082: }
                   3083: 
1.531     albertel 3084: sub clean_filename {
1.831     albertel 3085:     my ($fname,$args)=@_;
1.315     www      3086: # Replace Windows backslashes by forward slashes
1.257     www      3087:     $fname=~s/\\/\//g;
1.831     albertel 3088:     if (!$args->{'keep_path'}) {
                   3089:         # Get rid of everything but the actual filename
                   3090: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3091:     }
1.315     www      3092: # Replace spaces by underscores
                   3093:     $fname=~s/\s+/\_/g;
                   3094: # Replace all other weird characters by nothing
1.831     albertel 3095:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3096: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3097: # numbers
                   3098:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3099:     return $fname;
                   3100: }
1.1051    raeburn  3101: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3102: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3103: # image with the same aspect ratio as the original, but with dimensions which do 
                   3104: # not exceed $resizewidth and $resizeheight.
                   3105:  
1.984     neumanie 3106: sub resizeImage {
1.1051    raeburn  3107:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3108:     my $ima = Image::Magick->new;
                   3109:     my $resized;
                   3110:     if (-e $img_path) {
                   3111:         $ima->Read($img_path);
                   3112:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3113:             my $width = $ima->Get('width');
                   3114:             my $height = $ima->Get('height');
                   3115:             if ($width > $resizewidth) {
                   3116: 	        my $factor = $width/$resizewidth;
                   3117:                 my $newheight = $height/$factor;
                   3118:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3119:                 $resized = 1;
                   3120:             }
                   3121:         }
                   3122:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3123:             my $width = $ima->Get('width');
                   3124:             my $height = $ima->Get('height');
                   3125:             if ($height > $resizeheight) {
                   3126:                 my $factor = $height/$resizeheight;
                   3127:                 my $newwidth = $width/$factor;
                   3128:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3129:                 $resized = 1;
                   3130:             }
                   3131:         }
                   3132:         if ($resized) {
                   3133:             $ima->Write($img_path);
                   3134:         }
                   3135:     }
                   3136:     return;
1.977     amueller 3137: }
                   3138: 
1.608     albertel 3139: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3140: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3141: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3142: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3143: #                                    canceloverwrite, or ''. 
                   3144: #                   if 'coursedoc': upload to the current course
                   3145: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3146: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3147: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3148: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3149: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3150: #        $allfiles - reference to hash for embedded objects
                   3151: #        $codebase - reference to hash for codebase of java objects
                   3152: #        $desuname - username for permanent storage of uploaded file
                   3153: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3154: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3155: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3156: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3157: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3158: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3159: #                    from File::MMagic.
1.858     raeburn  3160: # 
1.686     albertel 3161: # output: url of file in userspace, or error: <message> 
                   3162: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3163: 
1.531     albertel 3164: sub userfileupload {
1.1090    raeburn  3165:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3166:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3167:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3168:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3169:     $fname=&clean_filename($fname);
1.1090    raeburn  3170:     # See if there is anything left
1.257     www      3171:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3172:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3173:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3174:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3175:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3176:         my $now = time;
1.1090    raeburn  3177:         my $filepath;
1.1095    raeburn  3178:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3179:              $filepath = 'tmp/helprequests/'.$now;
                   3180:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3181:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3182:                          '_'.$env{'user.domain'}.'/pending';
                   3183:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3184:             my ($docuname,$docudom);
                   3185:             if ($destudom) {
                   3186:                 $docudom = $destudom;
                   3187:             } else {
                   3188:                 $docudom = $env{'user.domain'};
                   3189:             }
                   3190:             if ($destuname) {
                   3191:                 $docuname = $destuname;
                   3192:             } else {
                   3193:                 $docuname = $env{'user.name'};
                   3194:             }
                   3195:             if (exists($env{'form.group'})) {
                   3196:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3197:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3198:             }
                   3199:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3200:             if ($context eq 'canceloverwrite') {
                   3201:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3202:                 if (-e  $tempfile) {
                   3203:                     my @info = stat($tempfile);
                   3204:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3205:                         unlink($tempfile);
                   3206:                     }
                   3207:                 }
                   3208:                 return;
1.523     raeburn  3209:             }
                   3210:         }
1.1090    raeburn  3211:         # Create the directory if not present
1.741     raeburn  3212:         my @parts=split(/\//,$filepath);
                   3213:         my $fullpath = $perlvar{'lonDaemons'};
                   3214:         for (my $i=0;$i<@parts;$i++) {
                   3215:             $fullpath .= '/'.$parts[$i];
                   3216:             if ((-e $fullpath)!=1) {
                   3217:                 mkdir($fullpath,0777);
                   3218:             }
                   3219:         }
                   3220:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3221:         print $fh $env{'form.'.$formname};
                   3222:         close($fh);
1.1090    raeburn  3223:         if ($context eq 'existingfile') {
                   3224:             my @info = stat($fullpath.'/'.$fname);
                   3225:             return ($fullpath.'/'.$fname,$info[9]);
                   3226:         } else {
                   3227:             return $fullpath.'/'.$fname;
                   3228:         }
1.523     raeburn  3229:     }
1.995     raeburn  3230:     if ($subdir eq 'scantron') {
                   3231:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3232:     } else {
1.995     raeburn  3233:         $fname="$subdir/$fname";
                   3234:     }
1.1090    raeburn  3235:     if ($context eq 'coursedoc') {
1.638     albertel 3236: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3237: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3238:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3239:             return &finishuserfileupload($docuname,$docudom,
                   3240: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3241: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3242:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3243:         } else {
1.1218    raeburn  3244:             if ($env{'form.folder'}) {
                   3245:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3246:             }
1.638     albertel 3247:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3248: 				       $fname,$formname,$parser,
1.1095    raeburn  3249: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3250:         }
1.719     banghart 3251:     } elsif (defined($destuname)) {
                   3252:         my $docuname=$destuname;
                   3253:         my $docudom=$destudom;
1.860     raeburn  3254: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3255: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3256:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3257:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3258:     } else {
1.638     albertel 3259:         my $docuname=$env{'user.name'};
                   3260:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3261:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3262:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3263:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3264:         }
1.860     raeburn  3265: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3266: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3267:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3268:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3269:     }
1.271     www      3270: }
                   3271: 
                   3272: sub finishuserfileupload {
1.860     raeburn  3273:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3274:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3275:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3276:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3277:   
1.860     raeburn  3278:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3279:     $file=$fname;
                   3280:     if ($fname=~m|/|) {
                   3281:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3282: 	$path.=$fnamepath.'/';
                   3283:     }
1.259     www      3284:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3285:     my $count;
                   3286:     for ($count=4;$count<=$#parts;$count++) {
                   3287:         $filepath.="/$parts[$count]";
                   3288:         if ((-e $filepath)!=1) {
                   3289: 	    mkdir($filepath,0777);
                   3290:         }
                   3291:     }
1.984     neumanie 3292: 
1.258     www      3293: # Save the file
                   3294:     {
1.701     albertel 3295: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3296: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3297: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3298: 	    return '/adm/notfound.html';
                   3299: 	}
1.1090    raeburn  3300:         if ($context eq 'overwrite') {
1.1117    foxr     3301:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3302:             my $target = $filepath.'/'.$file;
                   3303:             if (-e $source) {
                   3304:                 my @info = stat($source);
                   3305:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3306:                     unless (&File::Copy::move($source,$target)) {
                   3307:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3308:                         return "Moving from $source failed";
                   3309:                     }
                   3310:                 } else {
                   3311:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3312:                 }
                   3313:             } else {
                   3314:                 return "Temporary file: $source missing";
                   3315:             }
                   3316:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3317: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3318: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3319: 	    return '/adm/notfound.html';
                   3320: 	}
1.570     albertel 3321: 	close(FH);
1.1051    raeburn  3322:         if ($resizewidth && $resizeheight) {
                   3323:             my $mm = new File::MMagic;
                   3324:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3325:             if ($mime_type =~ m{^image/}) {
                   3326: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3327:             }  
1.977     amueller 3328: 	}
1.258     www      3329:     }
1.1152    raeburn  3330:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3331:         if (ref($mimetype)) {
                   3332:             if ($$mimetype eq '') {
                   3333:                 my $mm = new File::MMagic;
                   3334:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3335:                 $$mimetype = $type;
                   3336:             }
                   3337:         }
                   3338:     }
1.637     raeburn  3339:     if ($parser eq 'parse') {
1.1152    raeburn  3340:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3341:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3342:                                                        $allfiles,$codebase);
                   3343:             unless ($parse_result eq 'ok') {
                   3344:                 &logthis('Failed to parse '.$filepath.$file.
                   3345: 	   	         ' for embedded media: '.$parse_result); 
                   3346:             }
1.637     raeburn  3347:         }
                   3348:     }
1.860     raeburn  3349:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3350:         my $input = $filepath.'/'.$file;
                   3351:         my $output = $filepath.'/'.'tn-'.$file;
                   3352:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3353:         system("convert -sample $thumbsize $input $output");
                   3354:         if (-e $filepath.'/'.'tn-'.$file) {
                   3355:             $fetchthumb  = 1; 
                   3356:         }
                   3357:     }
1.858     raeburn  3358:  
1.259     www      3359: # Notify homeserver to grep it
                   3360: #
1.984     neumanie 3361:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3362:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3363:     if ($fetchresult eq 'ok') {
1.860     raeburn  3364:         if ($fetchthumb) {
                   3365:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3366:             if ($thumbresult ne 'ok') {
                   3367:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3368:                          $docuhome.': '.$thumbresult);
                   3369:             }
                   3370:         }
1.259     www      3371: #
1.258     www      3372: # Return the URL to it
1.494     albertel 3373:         return '/uploaded/'.$path.$file;
1.263     www      3374:     } else {
1.494     albertel 3375:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3376: 		 ': '.$fetchresult);
1.263     www      3377:         return '/adm/notfound.html';
1.858     raeburn  3378:     }
1.493     albertel 3379: }
                   3380: 
1.637     raeburn  3381: sub extract_embedded_items {
1.961     raeburn  3382:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3383:     my @state = ();
1.1164    raeburn  3384:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3385:     my %javafiles = (
                   3386:                       codebase => '',
                   3387:                       code => '',
                   3388:                       archive => ''
                   3389:                     );
                   3390:     my %mediafiles = (
                   3391:                       src => '',
                   3392:                       movie => '',
                   3393:                      );
1.648     raeburn  3394:     my $p;
                   3395:     if ($content) {
                   3396:         $p = HTML::LCParser->new($content);
                   3397:     } else {
1.961     raeburn  3398:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3399:     }
1.641     albertel 3400:     while (my $t=$p->get_token()) {
1.640     albertel 3401: 	if ($t->[0] eq 'S') {
                   3402: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3403: 	    push(@state, $tagname);
1.648     raeburn  3404:             if (lc($tagname) eq 'allow') {
                   3405:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3406:             }
1.640     albertel 3407: 	    if (lc($tagname) eq 'img') {
                   3408: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3409: 	    }
1.886     albertel 3410: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3411:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3412:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3413:                 }
1.886     albertel 3414: 	    }
1.645     raeburn  3415:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3416:                 my $src;
1.645     raeburn  3417:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3418:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3419:                 } else {
1.1164    raeburn  3420:                     if ($attr->{'src'} ne '') {
                   3421:                         $src = $attr->{'src'};
                   3422:                         &add_filetype($allfiles,$src,'src');
                   3423:                     }
                   3424:                 }
                   3425:                 my $text = $p->get_trimmed_text();
                   3426:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3427:                     my @swfargs = split(/,/,$1);
                   3428:                     foreach my $item (@swfargs) {
                   3429:                         $item =~ s/["']//g;
                   3430:                         $item =~ s/^\s+//;
                   3431:                         $item =~ s/\s+$//;
                   3432:                     }
                   3433:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3434:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3435:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3436:                         } else {
                   3437:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3438:                         }
                   3439:                     }
1.645     raeburn  3440:                 }
                   3441:             }
                   3442:             if (lc($tagname) eq 'link') {
                   3443:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3444:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3445:                 }
                   3446:             }
1.640     albertel 3447: 	    if (lc($tagname) eq 'object' ||
                   3448: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3449: 		foreach my $item (keys(%javafiles)) {
                   3450: 		    $javafiles{$item} = '';
                   3451: 		}
1.1164    raeburn  3452:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3453:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3454:                 }
1.640     albertel 3455: 	    }
                   3456: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3457: 		my $name = lc($attr->{'name'});
                   3458: 		foreach my $item (keys(%javafiles)) {
                   3459: 		    if ($name eq $item) {
                   3460: 			$javafiles{$item} = $attr->{'value'};
                   3461: 			last;
                   3462: 		    }
                   3463: 		}
1.1164    raeburn  3464:                 my $pathfrom;
1.640     albertel 3465: 		foreach my $item (keys(%mediafiles)) {
                   3466: 		    if ($name eq $item) {
1.1164    raeburn  3467:                         $pathfrom = $attr->{'value'};
                   3468:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3469: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3470: 			last;
                   3471: 		    }
                   3472: 		}
1.1164    raeburn  3473:                 if ($name eq 'flashvars') {
                   3474:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3475:                 }
                   3476:                 if ($pathfrom ne '') {
                   3477:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3478:                                          $pathfrom);
                   3479:                 }
1.640     albertel 3480: 	    }
                   3481: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3482: 		foreach my $item (keys(%javafiles)) {
                   3483: 		    if ($attr->{$item}) {
                   3484: 			$javafiles{$item} = $attr->{$item};
                   3485: 			last;
                   3486: 		    }
                   3487: 		}
                   3488: 		foreach my $item (keys(%mediafiles)) {
                   3489: 		    if ($attr->{$item}) {
                   3490: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3491: 			last;
                   3492: 		    }
                   3493: 		}
1.1164    raeburn  3494:                 if (lc($tagname) eq 'embed') {
                   3495:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3496:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3497:                                              $attr->{'src'});
                   3498:                     }
                   3499:                 }
1.640     albertel 3500: 	    }
1.1164    raeburn  3501:             if ($t->[4] =~ m{/>$}) {
                   3502:                 pop(@state);  
                   3503:             }
1.640     albertel 3504: 	} elsif ($t->[0] eq 'E') {
                   3505: 	    my ($tagname) = ($t->[1]);
                   3506: 	    if ($javafiles{'codebase'} ne '') {
                   3507: 		$javafiles{'codebase'} .= '/';
                   3508: 	    }  
                   3509: 	    if (lc($tagname) eq 'applet' ||
                   3510: 		lc($tagname) eq 'object' ||
                   3511: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3512: 		) {
                   3513: 		foreach my $item (keys(%javafiles)) {
                   3514: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3515: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3516: 			&add_filetype($allfiles,$file,$item);
                   3517: 		    }
                   3518: 		}
                   3519: 	    } 
                   3520: 	    pop @state;
                   3521: 	}
                   3522:     }
1.1164    raeburn  3523:     foreach my $id (sort(keys(%flashvars))) {
                   3524:         if ($shockwave{$id} ne '') {
                   3525:             my @pairs = split(/\&/,$flashvars{$id});
                   3526:             foreach my $pair (@pairs) {
                   3527:                 my ($key,$value) = split(/\=/,$pair);
                   3528:                 if ($key eq 'thumb') {
                   3529:                     &add_filetype($allfiles,$value,$key);
                   3530:                 } elsif ($key eq 'content') {
                   3531:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3532:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3533:                     if ($ext ne '') {
                   3534:                         &add_filetype($allfiles,$path.$value,$ext);
                   3535:                     }
                   3536:                 }
                   3537:             }
                   3538:         }
                   3539:     }
1.637     raeburn  3540:     return 'ok';
                   3541: }
                   3542: 
1.639     albertel 3543: sub add_filetype {
                   3544:     my ($allfiles,$file,$type)=@_;
                   3545:     if (exists($allfiles->{$file})) {
                   3546: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3547: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3548: 	}
                   3549:     } else {
                   3550: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3551:     }
                   3552: }
                   3553: 
1.1164    raeburn  3554: sub embedded_dependency {
                   3555:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3556:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3557:         if (($identifier ne '') &&
                   3558:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3559:             ($pathfrom ne '')) {
                   3560:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3561:             foreach my $dep (@{$related->{$identifier}}) {
                   3562:                 &add_filetype($allfiles,$path.$dep,'object');
                   3563:             }
                   3564:         }
                   3565:     }
                   3566:     return;
                   3567: }
                   3568: 
1.493     albertel 3569: sub removeuploadedurl {
1.984     neumanie 3570:     my ($url)=@_;	
                   3571:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3572:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3573: }
                   3574: 
                   3575: sub removeuserfile {
                   3576:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3577:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3578:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3579:     if ($result eq 'ok') {	
1.798     raeburn  3580:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3581:             my $metafile = $fname.'.meta';
                   3582:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3583: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3584:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3585:             my $sqlresult = 
1.823     albertel 3586:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3587:                                         'portfolio_metadata',$group,
                   3588:                                         'delete');
1.798     raeburn  3589:         }
                   3590:     }
                   3591:     return $result;
1.257     www      3592: }
1.15      www      3593: 
1.530     albertel 3594: sub mkdiruserfile {
                   3595:     my ($docuname,$docudom,$dir)=@_;
                   3596:     my $home=&homeserver($docuname,$docudom);
                   3597:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3598: }
                   3599: 
1.531     albertel 3600: sub renameuserfile {
                   3601:     my ($docuname,$docudom,$old,$new)=@_;
                   3602:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3603:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3604:                         &escape("$old").':'.&escape("$new"),$home);
                   3605:     if ($result eq 'ok') {
                   3606:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3607:             my $oldmeta = $old.'.meta';
                   3608:             my $newmeta = $new.'.meta';
                   3609:             my $metaresult = 
                   3610:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3611: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3612:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3613:             my $sqlresult = 
1.823     albertel 3614:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3615:                                         'portfolio_metadata',$group,
                   3616:                                         'delete');
1.798     raeburn  3617:         }
                   3618:     }
                   3619:     return $result;
1.531     albertel 3620: }
                   3621: 
1.14      www      3622: # ------------------------------------------------------------------------- Log
                   3623: 
                   3624: sub log {
                   3625:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3626:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3627: }
                   3628: 
                   3629: # ------------------------------------------------------------------ Course Log
1.352     www      3630: #
                   3631: # This routine flushes several buffers of non-mission-critical nature
                   3632: #
1.157     www      3633: 
                   3634: sub flushcourselogs {
1.352     www      3635:     &logthis('Flushing log buffers');
                   3636: #
                   3637: # course logs
                   3638: # This is a log of all transactions in a course, which can be used
                   3639: # for data mining purposes
                   3640: #
                   3641: # It also collects the courseid database, which lists last transaction
                   3642: # times and course titles for all courseids
                   3643: #
                   3644:     my %courseidbuffer=();
1.921     raeburn  3645:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3646:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3647: 		          &escape($courselogs{$crsid}),
                   3648: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3649: 	    delete $courselogs{$crsid};
                   3650:         } else {
                   3651:             &logthis('Failed to flush log buffer for '.$crsid);
                   3652:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3653:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3654:                         " exceeded maximum size, deleting.</font>");
                   3655:                delete $courselogs{$crsid};
                   3656:             }
1.352     www      3657:         }
1.920     raeburn  3658:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3659:             'description' => $coursedescrbuf{$crsid},
                   3660:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3661:             'type'        => $coursetypebuf{$crsid},
                   3662:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3663:         };
1.191     harris41 3664:     }
1.352     www      3665: #
                   3666: # Write course id database (reverse lookup) to homeserver of courses 
                   3667: # Is used in pickcourse
                   3668: #
1.840     albertel 3669:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3670:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3671:                                     $courseidbuffer{$crs_home},
                   3672:                                     $crs_home,'timeonly');
1.352     www      3673:     }
                   3674: #
                   3675: # File accesses
                   3676: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3677: #
1.449     matthew  3678:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3679:         if ($entry =~ /___count$/) {
                   3680:             my ($dom,$name);
1.807     albertel 3681:             ($dom,$name,undef)=
1.811     albertel 3682: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3683:             if (! defined($dom) || $dom eq '' || 
                   3684:                 ! defined($name) || $name eq '') {
1.620     albertel 3685:                 my $cid = $env{'request.course.id'};
                   3686:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3687:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3688:             }
1.450     matthew  3689:             my $value = $accesshash{$entry};
                   3690:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3691:             my %temphash=($url => $value);
1.449     matthew  3692:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3693:             if ($result eq 'ok') {
                   3694:                 delete $accesshash{$entry};
                   3695:             }
                   3696:         } else {
1.811     albertel 3697:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3698:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3699:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3700:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3701:                 delete $accesshash{$entry};
                   3702:             }
1.185     www      3703:         }
1.191     harris41 3704:     }
1.352     www      3705: #
                   3706: # Roles
                   3707: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3708: #
1.800     albertel 3709:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3710:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3711: 	    split(/\:/,$entry);
                   3712:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3713:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3714:                 $rudom,$runame) eq 'ok') {
                   3715: 	    delete $userrolehash{$entry};
                   3716:         }
                   3717:     }
1.662     raeburn  3718: #
                   3719: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3720: #
                   3721:     my %domrolebuffer = ();
1.1000    raeburn  3722:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3723:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3724:         if ($domrolebuffer{$rudom}) {
                   3725:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3726:                       '='.&escape($domainrolehash{$entry});
                   3727:         } else {
                   3728:             $domrolebuffer{$rudom}.=&escape($entry).
                   3729:                       '='.&escape($domainrolehash{$entry});
                   3730:         }
                   3731:         delete $domainrolehash{$entry};
                   3732:     }
                   3733:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3734: 	my %servers = &get_servers($dom,'library');
                   3735: 	foreach my $tryserver (keys(%servers)) {
                   3736: 	    unless (&reply('domroleput:'.$dom.':'.
                   3737: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3738: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3739: 	    }
1.662     raeburn  3740:         }
                   3741:     }
1.186     www      3742:     $dumpcount++;
1.157     www      3743: }
                   3744: 
                   3745: sub courselog {
                   3746:     my $what=shift;
1.158     www      3747:     $what=time.':'.$what;
1.620     albertel 3748:     unless ($env{'request.course.id'}) { return ''; }
                   3749:     $coursedombuf{$env{'request.course.id'}}=
                   3750:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3751:     $coursenumbuf{$env{'request.course.id'}}=
                   3752:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3753:     $coursehombuf{$env{'request.course.id'}}=
                   3754:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3755:     $coursedescrbuf{$env{'request.course.id'}}=
                   3756:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3757:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3758:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3759:     $courseownerbuf{$env{'request.course.id'}}=
                   3760:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3761:     $coursetypebuf{$env{'request.course.id'}}=
                   3762:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3763:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3764: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3765:     } else {
1.620     albertel 3766: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3767:     }
1.620     albertel 3768:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3769: 	&flushcourselogs();
                   3770:     }
1.158     www      3771: }
                   3772: 
                   3773: sub courseacclog {
                   3774:     my $fnsymb=shift;
1.620     albertel 3775:     unless ($env{'request.course.id'}) { return ''; }
                   3776:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3777:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3778:         $what.=':POST';
1.583     matthew  3779:         # FIXME: Probably ought to escape things....
1.800     albertel 3780: 	foreach my $key (keys(%env)) {
                   3781:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3782:                 my $formitem = $1;
                   3783:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3784:                     $what.=':'.$formitem.'='.$env{$key};
                   3785:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3786:                     $what.=':'.$formitem.'='.$env{$key};
                   3787:                 }
1.158     www      3788:             }
1.191     harris41 3789:         }
1.583     matthew  3790:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3791:         # FIXME: We should not be depending on a form parameter that someone
                   3792:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3793:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3794:             $what.= ':POST';
                   3795:             # FIXME: Probably ought to escape things....
                   3796:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3797:                                  'crsdiscuss') {
1.620     albertel 3798:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3799:             }
                   3800:         }
1.158     www      3801:     }
                   3802:     &courselog($what);
1.149     www      3803: }
                   3804: 
1.185     www      3805: sub countacc {
                   3806:     my $url=&declutter(shift);
1.458     matthew  3807:     return if (! defined($url) || $url eq '');
1.620     albertel 3808:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3809: #
                   3810: # Mark that this url was used in this course
                   3811: #
1.620     albertel 3812:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3813: #
                   3814: # Increase the access count for this resource in this child process
                   3815: #
1.281     www      3816:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3817:     $accesshash{$key}++;
1.185     www      3818: }
1.349     www      3819: 
1.361     www      3820: sub linklog {
                   3821:     my ($from,$to)=@_;
                   3822:     $from=&declutter($from);
                   3823:     $to=&declutter($to);
                   3824:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3825:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3826: }
1.1160    www      3827: 
                   3828: sub statslog {
                   3829:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3830:     if ($users<2) { return; }
                   3831:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3832:             'course'       => $env{'request.course.id'},
                   3833:             'sections'     => '"all"',
                   3834:             'num_students' => $users,
                   3835:             'part'         => $part,
                   3836:             'symb'         => $symb,
                   3837:             'mean_tries'   => $av_attempts,
                   3838:             'deg_of_diff'  => $degdiff});
                   3839:     foreach my $key (keys(%dynstore)) {
                   3840:         $accesshash{$key}=$dynstore{$key};
                   3841:     }
                   3842: }
1.361     www      3843:   
1.349     www      3844: sub userrolelog {
                   3845:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3846:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3847:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3848:        $userrolehash
                   3849:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3850:                     =$tend.':'.$tstart;
1.662     raeburn  3851:     }
1.1169    droeschl 3852:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3853:        $userrolehash
                   3854:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3855:                     =$tend.':'.$tstart;
                   3856:     }
1.1169    droeschl 3857:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3858:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3859:        $domainrolehash
                   3860:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3861:                     = $tend.':'.$tstart;
                   3862:     }
1.351     www      3863: }
                   3864: 
1.957     raeburn  3865: sub courserolelog {
                   3866:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3867:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3868:         my $cdom = $1;
                   3869:         my $cnum = $2;
                   3870:         my $sec = $3;
                   3871:         my $namespace = 'rolelog';
                   3872:         my %storehash = (
                   3873:                            role    => $trole,
                   3874:                            start   => $tstart,
                   3875:                            end     => $tend,
                   3876:                            selfenroll => $selfenroll,
                   3877:                            context    => $context,
                   3878:                         );
                   3879:         if ($trole eq 'gr') {
                   3880:             $namespace = 'groupslog';
                   3881:             $storehash{'group'} = $sec;
                   3882:         } else {
                   3883:             $storehash{'section'} = $sec;
                   3884:         }
1.1188    raeburn  3885:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3886:                    $domain,$cnum,$cdom);
1.1184    raeburn  3887:         if (($trole ne 'st') || ($sec ne '')) {
                   3888:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3889:         }
                   3890:     }
                   3891:     return;
                   3892: }
                   3893: 
1.1184    raeburn  3894: sub domainrolelog {
                   3895:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3896:     if ($area =~ m{^/($match_domain)/$}) {
                   3897:         my $cdom = $1;
                   3898:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3899:         my $namespace = 'rolelog';
                   3900:         my %storehash = (
                   3901:                            role    => $trole,
                   3902:                            start   => $tstart,
                   3903:                            end     => $tend,
                   3904:                            context => $context,
                   3905:                         );
1.1188    raeburn  3906:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3907:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3908:     }
                   3909:     return;
                   3910: 
                   3911: }
                   3912: 
                   3913: sub coauthorrolelog {
                   3914:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3915:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3916:         my $audom = $1;
                   3917:         my $auname = $2;
                   3918:         my $namespace = 'rolelog';
                   3919:         my %storehash = (
                   3920:                            role    => $trole,
                   3921:                            start   => $tstart,
                   3922:                            end     => $tend,
                   3923:                            context => $context,
                   3924:                         );
1.1188    raeburn  3925:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3926:                    $domain,$auname,$audom);
1.1184    raeburn  3927:     }
                   3928:     return;
                   3929: }
                   3930: 
1.351     www      3931: sub get_course_adv_roles {
1.948     raeburn  3932:     my ($cid,$codes) = @_;
1.620     albertel 3933:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3934:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3935:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3936:     my %nothide=();
1.800     albertel 3937:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3938:         if ($user !~ /:/) {
                   3939: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3940:         } else {
                   3941:             $nothide{$user}=1;
                   3942:         }
1.470     www      3943:     }
1.1219    raeburn  3944:     my @possdoms = ($coursehash{'domain'});
                   3945:     if ($coursehash{'checkforpriv'}) {
                   3946:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3947:     }
1.351     www      3948:     my %returnhash=();
                   3949:     my %dumphash=
                   3950:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3951:     my $now=time;
1.997     raeburn  3952:     my %privileged;
1.1000    raeburn  3953:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3954: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3955:         if (($tstart) && ($tstart<0)) { next; }
                   3956:         if (($tend) && ($tend<$now)) { next; }
                   3957:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3958:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3959: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  3960:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3961:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3962: 	if ($role eq 'cr') { next; }
1.948     raeburn  3963:         if ($codes) {
                   3964:             if ($section) { $role .= ':'.$section; }
                   3965:             if ($returnhash{$role}) {
                   3966:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3967:             } else {
                   3968:                 $returnhash{$role}=$username.':'.$domain;
                   3969:             }
1.351     www      3970:         } else {
1.988     raeburn  3971:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3972:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3973:             if ($returnhash{$key}) {
                   3974: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3975:             } else {
                   3976:                 $returnhash{$key}=$username.':'.$domain;
                   3977:             }
1.351     www      3978:         }
1.948     raeburn  3979:     }
1.400     www      3980:     return %returnhash;
                   3981: }
                   3982: 
                   3983: sub get_my_roles {
1.937     raeburn  3984:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3985:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3986:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3987:     my (%dumphash,%nothide);
1.1086    raeburn  3988:     if ($context eq 'userroles') {
1.1166    raeburn  3989:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3990:     } else {
1.1219    raeburn  3991:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3992:         if ($hidepriv) {
                   3993:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3994:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3995:                 if ($user !~ /:/) {
                   3996:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3997:                 } else {
                   3998:                     $nothide{$user} = 1;
                   3999:                 }
                   4000:             }
                   4001:         }
1.858     raeburn  4002:     }
1.400     www      4003:     my %returnhash=();
                   4004:     my $now=time;
1.999     raeburn  4005:     my %privileged;
1.800     albertel 4006:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4007:         my ($role,$tend,$tstart);
                   4008:         if ($context eq 'userroles') {
1.1149    raeburn  4009:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4010: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4011:         } else {
                   4012:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4013:         }
1.400     www      4014:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4015:         my $status = 'active';
1.939     raeburn  4016:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4017:             $status = 'previous';
                   4018:         } 
                   4019:         if (($tstart) && ($now<$tstart)) {
                   4020:             $status = 'future';
                   4021:         }
                   4022:         if (ref($types) eq 'ARRAY') {
                   4023:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4024:                 next;
                   4025:             } 
                   4026:         } else {
                   4027:             if ($status ne 'active') {
                   4028:                 next;
                   4029:             }
                   4030:         }
1.867     raeburn  4031:         my ($rolecode,$username,$domain,$section,$area);
                   4032:         if ($context eq 'userroles') {
1.1186    raeburn  4033:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4034:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4035:         } else {
                   4036:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4037:         }
1.832     raeburn  4038:         if (ref($roledoms) eq 'ARRAY') {
                   4039:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4040:                 next;
                   4041:             }
                   4042:         }
                   4043:         if (ref($roles) eq 'ARRAY') {
                   4044:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4045:                 if ($role =~ /^cr\//) {
                   4046:                     if (!grep(/^cr$/,@{$roles})) {
                   4047:                         next;
                   4048:                     }
1.1104    raeburn  4049:                 } elsif ($role =~ /^gr\//) {
                   4050:                     if (!grep(/^gr$/,@{$roles})) {
                   4051:                         next;
                   4052:                     }
1.922     raeburn  4053:                 } else {
                   4054:                     next;
                   4055:                 }
1.832     raeburn  4056:             }
1.867     raeburn  4057:         }
1.937     raeburn  4058:         if ($hidepriv) {
1.1219    raeburn  4059:             my @privroles = ('dc','su');
1.999     raeburn  4060:             if ($context eq 'userroles') {
1.1219    raeburn  4061:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4062:             } else {
1.1219    raeburn  4063:                 my $possdoms = [$domain];
                   4064:                 if (ref($roledoms) eq 'ARRAY') {
                   4065:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4066:                 }
1.1219    raeburn  4067:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4068:                     if (!$nothide{$username.':'.$domain}) {
                   4069:                         next;
                   4070:                     }
                   4071:                 }
1.937     raeburn  4072:             }
                   4073:         }
1.933     raeburn  4074:         if ($withsec) {
                   4075:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4076:                 $tstart.':'.$tend;
                   4077:         } else {
                   4078:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4079:         }
1.832     raeburn  4080:     }
1.373     www      4081:     return %returnhash;
1.399     www      4082: }
                   4083: 
                   4084: # ----------------------------------------------------- Frontpage Announcements
                   4085: #
                   4086: #
                   4087: 
                   4088: sub postannounce {
                   4089:     my ($server,$text)=@_;
1.844     albertel 4090:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4091:     unless ($text=~/\w/) { $text=''; }
                   4092:     return &reply('setannounce:'.&escape($text),$server);
                   4093: }
                   4094: 
                   4095: sub getannounce {
1.448     albertel 4096: 
                   4097:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4098: 	my $announcement='';
1.800     albertel 4099: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4100: 	close($fh);
1.399     www      4101: 	if ($announcement=~/\w/) { 
                   4102: 	    return 
                   4103:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4104:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4105: 	} else {
                   4106: 	    return '';
                   4107: 	}
                   4108:     } else {
                   4109: 	return '';
                   4110:     }
1.351     www      4111: }
1.353     www      4112: 
                   4113: # ---------------------------------------------------------- Course ID routines
                   4114: # Deal with domain's nohist_courseid.db files
                   4115: #
                   4116: 
                   4117: sub courseidput {
1.921     raeburn  4118:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4119:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4120:     my $outcome;
                   4121:     if ($caller eq 'timeonly') {
                   4122:         my $cids = '';
                   4123:         foreach my $item (keys(%$storehash)) {
                   4124:             $cids.=&escape($item).'&';
                   4125:         }
                   4126:         $cids=~s/\&$//;
                   4127:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4128:                           $coursehome);       
                   4129:     } else {
                   4130:         my $items = '';
                   4131:         foreach my $item (keys(%$storehash)) {
                   4132:             $items.= &escape($item).'='.
                   4133:                      &freeze_escape($$storehash{$item}).'&';
                   4134:         }
                   4135:         $items=~s/\&$//;
                   4136:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4137:                           $coursehome);
1.918     raeburn  4138:     }
                   4139:     if ($outcome eq 'unknown_cmd') {
                   4140:         my $what;
                   4141:         foreach my $cid (keys(%$storehash)) {
                   4142:             $what .= &escape($cid).'=';
1.921     raeburn  4143:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4144:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4145:             }
                   4146:             $what =~ s/\:$/&/;
                   4147:         }
                   4148:         $what =~ s/\&$//;  
                   4149:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4150:     } else {
                   4151:         return $outcome;
                   4152:     }
1.353     www      4153: }
                   4154: 
                   4155: sub courseiddump {
1.921     raeburn  4156:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4157:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4158:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4159:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4160:     my $as_hash = 1;
                   4161:     my %returnhash;
                   4162:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4163:     my %libserv = &all_library();
                   4164:     foreach my $tryserver (keys(%libserv)) {
                   4165:         if ( (  $hostidflag == 1 
                   4166: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4167: 	     || (!defined($hostidflag)) ) {
                   4168: 
1.918     raeburn  4169: 	    if (($domfilter eq '') ||
                   4170: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4171:                 my $rep;
                   4172:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4173:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4174:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4175:                                 &escape($descfilter), &escape($instcodefilter), 
                   4176:                                 &escape($ownerfilter), &escape($coursefilter),
                   4177:                                 &escape($typefilter), &escape($regexp_ok), 
                   4178:                                 $as_hash, &escape($selfenrollonly), 
                   4179:                                 &escape($catfilter), $showhidden, $caller, 
                   4180:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4181:                                 &escape($createdbefore), &escape($createdafter), 
                   4182:                                 &escape($creationcontext), $domcloner)));
                   4183:                 } else {
                   4184:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4185:                              $sincefilter.':'.&escape($descfilter).':'.
                   4186:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4187:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4188:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4189:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4190:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4191:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4192:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4193:                              &escape($creationcontext).':'.$domcloner,
                   4194:                              $tryserver);
                   4195:                 }
                   4196:                      
1.918     raeburn  4197:                 my @pairs=split(/\&/,$rep);
                   4198:                 foreach my $item (@pairs) {
                   4199:                     my ($key,$value)=split(/\=/,$item,2);
                   4200:                     $key = &unescape($key);
                   4201:                     next if ($key =~ /^error: 2 /);
                   4202:                     my $result = &thaw_unescape($value);
                   4203:                     if (ref($result) eq 'HASH') {
                   4204:                         $returnhash{$key}=$result;
                   4205:                     } else {
1.921     raeburn  4206:                         my @responses = split(/:/,$value);
                   4207:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4208:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4209:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4210:                         }
1.1008    raeburn  4211:                     }
1.353     www      4212:                 }
                   4213:             }
                   4214:         }
                   4215:     }
                   4216:     return %returnhash;
                   4217: }
                   4218: 
1.1055    raeburn  4219: sub courselastaccess {
                   4220:     my ($cdom,$cnum,$hostidref) = @_;
                   4221:     my %returnhash;
                   4222:     if ($cdom && $cnum) {
                   4223:         my $chome = &homeserver($cnum,$cdom);
                   4224:         if ($chome ne 'no_host') {
                   4225:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4226:             &extract_lastaccess(\%returnhash,$rep);
                   4227:         }
                   4228:     } else {
                   4229:         if (!$cdom) { $cdom=''; }
                   4230:         my %libserv = &all_library();
                   4231:         foreach my $tryserver (keys(%libserv)) {
                   4232:             if (ref($hostidref) eq 'ARRAY') {
                   4233:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4234:             } 
                   4235:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4236:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4237:                 &extract_lastaccess(\%returnhash,$rep);
                   4238:             }
                   4239:         }
                   4240:     }
                   4241:     return %returnhash;
                   4242: }
                   4243: 
                   4244: sub extract_lastaccess {
                   4245:     my ($returnhash,$rep) = @_;
                   4246:     if (ref($returnhash) eq 'HASH') {
                   4247:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4248:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4249:                  $rep eq '') {
                   4250:             my @pairs=split(/\&/,$rep);
                   4251:             foreach my $item (@pairs) {
                   4252:                 my ($key,$value)=split(/\=/,$item,2);
                   4253:                 $key = &unescape($key);
                   4254:                 next if ($key =~ /^error: 2 /);
                   4255:                 $returnhash->{$key} = &thaw_unescape($value);
                   4256:             }
                   4257:         }
                   4258:     }
                   4259:     return;
                   4260: }
                   4261: 
1.658     raeburn  4262: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4263: 
                   4264: sub dcmailput {
1.685     raeburn  4265:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4266:     my $status = &Apache::lonnet::critical(
1.740     www      4267:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4268:        &escape($message),$server);
1.662     raeburn  4269:     return $status;
                   4270: }
                   4271: 
1.658     raeburn  4272: sub dcmaildump {
                   4273:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4274:     my %returnhash=();
1.846     albertel 4275: 
                   4276:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4277:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4278:                                                          &escape($enddate).':';
                   4279: 	my @esc_senders=map { &escape($_)} @$senders;
                   4280: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4281: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4282:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4283:             if (($key) && ($value)) {
                   4284:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4285:             }
                   4286:         }
                   4287:     }
                   4288:     return %returnhash;
                   4289: }
1.662     raeburn  4290: # ---------------------------------------------------------- Domain roles
                   4291: 
                   4292: sub get_domain_roles {
                   4293:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4294:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4295:         $startdate = '.';
                   4296:     }
1.1018    raeburn  4297:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4298:         $enddate = '.';
                   4299:     }
1.922     raeburn  4300:     my $rolelist;
                   4301:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4302:         $rolelist = join('&',@{$roles});
1.922     raeburn  4303:     }
1.662     raeburn  4304:     my %personnel = ();
1.841     albertel 4305: 
                   4306:     my %servers = &get_servers($dom,'library');
                   4307:     foreach my $tryserver (keys(%servers)) {
                   4308: 	%{$personnel{$tryserver}}=();
                   4309: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4310: 					    &escape($startdate).':'.
                   4311: 					    &escape($enddate).':'.
                   4312: 					    &escape($rolelist), $tryserver))) {
                   4313: 	    my ($key,$value) = split(/\=/,$line,2);
                   4314: 	    if (($key) && ($value)) {
                   4315: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4316: 	    }
                   4317: 	}
1.662     raeburn  4318:     }
                   4319:     return %personnel;
                   4320: }
1.658     raeburn  4321: 
1.1057    www      4322: # ----------------------------------------------------------- Interval timing 
1.149     www      4323: 
1.1153    www      4324: {
                   4325: # Caches needed for speedup of navmaps
                   4326: # We don't want to cache this for very long at all (5 seconds at most)
                   4327: # 
                   4328: # The user for whom we cache
                   4329: my $cachedkey='';
                   4330: # The cached times for this user
                   4331: my %cachedtimes=();
                   4332: # When this was last done
                   4333: my $cachedtime=();
                   4334: 
                   4335: sub load_all_first_access {
1.1154    raeburn  4336:     my ($uname,$udom)=@_;
1.1156    www      4337:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4338:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4339:         return;
                   4340:     }
                   4341:     $cachedtime=time;
                   4342:     $cachedkey=$uname.':'.$udom;
                   4343:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4344: }
                   4345: 
1.504     albertel 4346: sub get_first_access {
1.1162    raeburn  4347:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4348:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4349:     if ($argsymb) { $symb=$argsymb; }
                   4350:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4351:     if ($argmap) { $map = $argmap; }
1.926     albertel 4352:     if ($type eq 'course') {
                   4353: 	$res='course';
                   4354:     } elsif ($type eq 'map') {
1.588     albertel 4355: 	$res=&symbread($map);
                   4356:     } else {
                   4357: 	$res=$symb;
                   4358:     }
1.1153    www      4359:     &load_all_first_access($uname,$udom);
                   4360:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4361: }
                   4362: 
                   4363: sub set_first_access {
1.1162    raeburn  4364:     my ($type,$interval)=@_;
1.790     albertel 4365:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4366:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4367:     if ($type eq 'course') {
                   4368: 	$res='course';
                   4369:     } elsif ($type eq 'map') {
1.588     albertel 4370: 	$res=&symbread($map);
                   4371:     } else {
                   4372: 	$res=$symb;
                   4373:     }
1.1153    www      4374:     $cachedkey='';
1.1162    raeburn  4375:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4376:     if (!$firstaccess) {
1.1162    raeburn  4377:         my $start = time;
                   4378: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4379:                           $udom,$uname);
                   4380:         if ($putres eq 'ok') {
                   4381:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4382:                  $udom,$uname); 
                   4383:             &appenv(
                   4384:                      {
                   4385:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4386:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4387:                      }
                   4388:                   );
                   4389:         }
                   4390:         return $putres;
1.505     albertel 4391:     }
                   4392:     return 'already_set';
1.504     albertel 4393: }
1.1153    www      4394: }
1.110     www      4395: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4396: 
                   4397: sub expirespread {
                   4398:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4399:     my $cid=$env{'request.course.id'}; 
1.110     www      4400:     if ($cid) {
                   4401:        my $now=time;
                   4402:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4403:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4404:                             $env{'course.'.$cid.'.num'}.
1.110     www      4405: 	        	    ':nohist_expirationdates:'.
                   4406:                             &escape($key).'='.$now,
1.620     albertel 4407:                             $env{'course.'.$cid.'.home'})
1.110     www      4408:     }
                   4409:     return 'ok';
1.14      www      4410: }
                   4411: 
1.109     www      4412: # ----------------------------------------------------- Devalidate Spreadsheets
                   4413: 
                   4414: sub devalidate {
1.325     www      4415:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4416:     my $cid=$env{'request.course.id'}; 
1.109     www      4417:     if ($cid) {
1.391     matthew  4418:         # delete the stored spreadsheets for
                   4419:         # - the student level sheet of this user in course's homespace
                   4420:         # - the assessment level sheet for this resource 
                   4421:         #   for this user in user's homespace
1.553     albertel 4422: 	# - current conditional state info
1.325     www      4423: 	my $key=$uname.':'.$udom.':';
1.109     www      4424:         my $status=
1.299     matthew  4425: 	    &del('nohist_calculatedsheets',
1.391     matthew  4426: 		 [$key.'studentcalc:'],
1.620     albertel 4427: 		 $env{'course.'.$cid.'.domain'},
                   4428: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4429: 		.' '.
                   4430: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4431: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4432:         unless ($status eq 'ok ok') {
                   4433:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4434:                     $uname.' at '.$udom.' for '.
1.109     www      4435: 		    $symb.': '.$status);
1.133     albertel 4436:         }
1.553     albertel 4437: 	&delenv('user.state.'.$cid);
1.109     www      4438:     }
                   4439: }
                   4440: 
1.265     albertel 4441: sub get_scalar {
                   4442:     my ($string,$end) = @_;
                   4443:     my $value;
                   4444:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4445: 	$value = $1;
                   4446:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4447: 	$value = $1;
                   4448:     }
                   4449:     return &unescape($value);
                   4450: }
                   4451: 
                   4452: sub array2str {
                   4453:   my (@array) = @_;
                   4454:   my $result=&arrayref2str(\@array);
                   4455:   $result=~s/^__ARRAY_REF__//;
                   4456:   $result=~s/__END_ARRAY_REF__$//;
                   4457:   return $result;
                   4458: }
                   4459: 
1.204     albertel 4460: sub arrayref2str {
                   4461:   my ($arrayref) = @_;
1.265     albertel 4462:   my $result='__ARRAY_REF__';
1.204     albertel 4463:   foreach my $elem (@$arrayref) {
1.265     albertel 4464:     if(ref($elem) eq 'ARRAY') {
                   4465:       $result.=&arrayref2str($elem).'&';
                   4466:     } elsif(ref($elem) eq 'HASH') {
                   4467:       $result.=&hashref2str($elem).'&';
                   4468:     } elsif(ref($elem)) {
                   4469:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4470:     } else {
                   4471:       $result.=&escape($elem).'&';
                   4472:     }
                   4473:   }
                   4474:   $result=~s/\&$//;
1.265     albertel 4475:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4476:   return $result;
                   4477: }
                   4478: 
1.168     albertel 4479: sub hash2str {
1.204     albertel 4480:   my (%hash) = @_;
                   4481:   my $result=&hashref2str(\%hash);
1.265     albertel 4482:   $result=~s/^__HASH_REF__//;
                   4483:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4484:   return $result;
                   4485: }
                   4486: 
                   4487: sub hashref2str {
                   4488:   my ($hashref)=@_;
1.265     albertel 4489:   my $result='__HASH_REF__';
1.800     albertel 4490:   foreach my $key (sort(keys(%$hashref))) {
                   4491:     if (ref($key) eq 'ARRAY') {
                   4492:       $result.=&arrayref2str($key).'=';
                   4493:     } elsif (ref($key) eq 'HASH') {
                   4494:       $result.=&hashref2str($key).'=';
                   4495:     } elsif (ref($key)) {
1.265     albertel 4496:       $result.='=';
1.800     albertel 4497:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4498:     } else {
1.1132    raeburn  4499: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4500:     }
                   4501: 
1.800     albertel 4502:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4503:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4504:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4505:       $result.=&hashref2str($hashref->{$key}).'&';
                   4506:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4507:        $result.='&';
1.800     albertel 4508:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4509:     } else {
1.800     albertel 4510:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4511:     }
                   4512:   }
1.168     albertel 4513:   $result=~s/\&$//;
1.265     albertel 4514:   $result .= '__END_HASH_REF__';
1.168     albertel 4515:   return $result;
                   4516: }
                   4517: 
                   4518: sub str2hash {
1.265     albertel 4519:     my ($string)=@_;
                   4520:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4521:     return %$hash;
                   4522: }
                   4523: 
                   4524: sub str2hashref {
1.168     albertel 4525:   my ($string) = @_;
1.265     albertel 4526: 
                   4527:   my %hash;
                   4528: 
                   4529:   if($string !~ /^__HASH_REF__/) {
                   4530:       if (! ($string eq '' || !defined($string))) {
                   4531: 	  $hash{'error'}='Not hash reference';
                   4532:       }
                   4533:       return (\%hash, $string);
                   4534:   }
                   4535: 
                   4536:   $string =~ s/^__HASH_REF__//;
                   4537: 
                   4538:   while($string !~ /^__END_HASH_REF__/) {
                   4539:       #key
                   4540:       my $key='';
                   4541:       if($string =~ /^__HASH_REF__/) {
                   4542:           ($key, $string)=&str2hashref($string);
                   4543:           if(defined($key->{'error'})) {
                   4544:               $hash{'error'}='Bad data';
                   4545:               return (\%hash, $string);
                   4546:           }
                   4547:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4548:           ($key, $string)=&str2arrayref($string);
                   4549:           if($key->[0] eq 'Array reference error') {
                   4550:               $hash{'error'}='Bad data';
                   4551:               return (\%hash, $string);
                   4552:           }
                   4553:       } else {
                   4554:           $string =~ s/^(.*?)=//;
1.267     albertel 4555: 	  $key=&unescape($1);
1.265     albertel 4556:       }
                   4557:       $string =~ s/^=//;
                   4558: 
                   4559:       #value
                   4560:       my $value='';
                   4561:       if($string =~ /^__HASH_REF__/) {
                   4562:           ($value, $string)=&str2hashref($string);
                   4563:           if(defined($value->{'error'})) {
                   4564:               $hash{'error'}='Bad data';
                   4565:               return (\%hash, $string);
                   4566:           }
                   4567:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4568:           ($value, $string)=&str2arrayref($string);
                   4569:           if($value->[0] eq 'Array reference error') {
                   4570:               $hash{'error'}='Bad data';
                   4571:               return (\%hash, $string);
                   4572:           }
                   4573:       } else {
                   4574: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4575:       }
                   4576:       $string =~ s/^&//;
                   4577: 
                   4578:       $hash{$key}=$value;
1.204     albertel 4579:   }
1.265     albertel 4580: 
                   4581:   $string =~ s/^__END_HASH_REF__//;
                   4582: 
                   4583:   return (\%hash, $string);
1.204     albertel 4584: }
                   4585: 
                   4586: sub str2array {
1.265     albertel 4587:     my ($string)=@_;
                   4588:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4589:     return @$array;
                   4590: }
                   4591: 
                   4592: sub str2arrayref {
1.204     albertel 4593:   my ($string) = @_;
1.265     albertel 4594:   my @array;
                   4595: 
                   4596:   if($string !~ /^__ARRAY_REF__/) {
                   4597:       if (! ($string eq '' || !defined($string))) {
                   4598: 	  $array[0]='Array reference error';
                   4599:       }
                   4600:       return (\@array, $string);
                   4601:   }
                   4602: 
                   4603:   $string =~ s/^__ARRAY_REF__//;
                   4604: 
                   4605:   while($string !~ /^__END_ARRAY_REF__/) {
                   4606:       my $value='';
                   4607:       if($string =~ /^__HASH_REF__/) {
                   4608:           ($value, $string)=&str2hashref($string);
                   4609:           if(defined($value->{'error'})) {
                   4610:               $array[0] ='Array reference error';
                   4611:               return (\@array, $string);
                   4612:           }
                   4613:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4614:           ($value, $string)=&str2arrayref($string);
                   4615:           if($value->[0] eq 'Array reference error') {
                   4616:               $array[0] ='Array reference error';
                   4617:               return (\@array, $string);
                   4618:           }
                   4619:       } else {
                   4620: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4621:       }
                   4622:       $string =~ s/^&//;
                   4623: 
                   4624:       push(@array, $value);
1.191     harris41 4625:   }
1.265     albertel 4626: 
                   4627:   $string =~ s/^__END_ARRAY_REF__//;
                   4628: 
                   4629:   return (\@array, $string);
1.168     albertel 4630: }
                   4631: 
1.167     albertel 4632: # -------------------------------------------------------------------Temp Store
                   4633: 
1.168     albertel 4634: sub tmpreset {
                   4635:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4636:   if (!$symb) {
                   4637:     $symb=&symbread();
1.620     albertel 4638:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4639:   }
                   4640:   $symb=escape($symb);
                   4641: 
1.620     albertel 4642:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4643:   $namespace=~s/\//\_/g;
                   4644:   $namespace=~s/\W//g;
                   4645: 
1.620     albertel 4646:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4647:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4648:   if ($domain eq 'public' && $stuname eq 'public') {
                   4649:       $stuname=$ENV{'REMOTE_ADDR'};
                   4650:   }
1.1117    foxr     4651:   my $path=LONCAPA::tempdir();
1.168     albertel 4652:   my %hash;
                   4653:   if (tie(%hash,'GDBM_File',
                   4654: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4655: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4656:     foreach my $key (keys(%hash)) {
1.180     albertel 4657:       if ($key=~ /:$symb/) {
1.168     albertel 4658: 	delete($hash{$key});
                   4659:       }
                   4660:     }
                   4661:   }
                   4662: }
                   4663: 
1.167     albertel 4664: sub tmpstore {
1.168     albertel 4665:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4666: 
                   4667:   if (!$symb) {
                   4668:     $symb=&symbread();
1.620     albertel 4669:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4670:   }
                   4671:   $symb=escape($symb);
                   4672: 
                   4673:   if (!$namespace) {
                   4674:     # I don't think we would ever want to store this for a course.
                   4675:     # it seems this will only be used if we don't have a course.
1.620     albertel 4676:     #$namespace=$env{'request.course.id'};
1.168     albertel 4677:     #if (!$namespace) {
1.620     albertel 4678:       $namespace=$env{'request.state'};
1.168     albertel 4679:     #}
                   4680:   }
                   4681:   $namespace=~s/\//\_/g;
                   4682:   $namespace=~s/\W//g;
1.620     albertel 4683:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4684:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4685:   if ($domain eq 'public' && $stuname eq 'public') {
                   4686:       $stuname=$ENV{'REMOTE_ADDR'};
                   4687:   }
1.168     albertel 4688:   my $now=time;
                   4689:   my %hash;
1.1117    foxr     4690:   my $path=LONCAPA::tempdir();
1.168     albertel 4691:   if (tie(%hash,'GDBM_File',
                   4692: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4693: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4694:     $hash{"version:$symb"}++;
                   4695:     my $version=$hash{"version:$symb"};
                   4696:     my $allkeys=''; 
                   4697:     foreach my $key (keys(%$storehash)) {
                   4698:       $allkeys.=$key.':';
1.591     albertel 4699:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4700:     }
                   4701:     $hash{"$version:$symb:timestamp"}=$now;
                   4702:     $allkeys.='timestamp';
                   4703:     $hash{"$version:keys:$symb"}=$allkeys;
                   4704:     if (untie(%hash)) {
                   4705:       return 'ok';
                   4706:     } else {
                   4707:       return "error:$!";
                   4708:     }
                   4709:   } else {
                   4710:     return "error:$!";
                   4711:   }
                   4712: }
1.167     albertel 4713: 
1.168     albertel 4714: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4715: 
1.168     albertel 4716: sub tmprestore {
                   4717:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4718: 
1.168     albertel 4719:   if (!$symb) {
                   4720:     $symb=&symbread();
1.620     albertel 4721:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4722:   }
                   4723:   $symb=escape($symb);
                   4724: 
1.620     albertel 4725:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4726: 
1.620     albertel 4727:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4728:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4729:   if ($domain eq 'public' && $stuname eq 'public') {
                   4730:       $stuname=$ENV{'REMOTE_ADDR'};
                   4731:   }
1.168     albertel 4732:   my %returnhash;
                   4733:   $namespace=~s/\//\_/g;
                   4734:   $namespace=~s/\W//g;
                   4735:   my %hash;
1.1117    foxr     4736:   my $path=LONCAPA::tempdir();
1.168     albertel 4737:   if (tie(%hash,'GDBM_File',
                   4738: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4739: 	  &GDBM_READER(),0640)) {
1.168     albertel 4740:     my $version=$hash{"version:$symb"};
                   4741:     $returnhash{'version'}=$version;
                   4742:     my $scope;
                   4743:     for ($scope=1;$scope<=$version;$scope++) {
                   4744:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4745:       my @keys=split(/:/,$vkeys);
                   4746:       my $key;
                   4747:       $returnhash{"$scope:keys"}=$vkeys;
                   4748:       foreach $key (@keys) {
1.591     albertel 4749: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4750: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4751:       }
                   4752:     }
1.168     albertel 4753:     if (!(untie(%hash))) {
                   4754:       return "error:$!";
                   4755:     }
                   4756:   } else {
                   4757:     return "error:$!";
                   4758:   }
                   4759:   return %returnhash;
1.167     albertel 4760: }
                   4761: 
1.9       www      4762: # ----------------------------------------------------------------------- Store
                   4763: 
                   4764: sub store {
1.124     www      4765:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4766:     my $home='';
                   4767: 
1.168     albertel 4768:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4769: 
1.213     www      4770:     $symb=&symbclean($symb);
1.122     albertel 4771:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4772: 
1.620     albertel 4773:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4774:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4775: 
                   4776:     &devalidate($symb,$stuname,$domain);
1.109     www      4777: 
                   4778:     $symb=escape($symb);
1.187     www      4779:     if (!$namespace) { 
1.620     albertel 4780:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4781:           return ''; 
                   4782:        } 
                   4783:     }
1.620     albertel 4784:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4785: 
                   4786:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4787:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4788: 
1.12      www      4789:     my $namevalue='';
1.800     albertel 4790:     foreach my $key (keys(%$storehash)) {
                   4791:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4792:     }
1.12      www      4793:     $namevalue=~s/\&$//;
1.187     www      4794:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4795:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4796: }
                   4797: 
1.47      www      4798: # -------------------------------------------------------------- Critical Store
                   4799: 
                   4800: sub cstore {
1.124     www      4801:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4802:     my $home='';
                   4803: 
1.168     albertel 4804:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4805: 
1.213     www      4806:     $symb=&symbclean($symb);
1.122     albertel 4807:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4808: 
1.620     albertel 4809:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4810:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4811: 
                   4812:     &devalidate($symb,$stuname,$domain);
1.109     www      4813: 
                   4814:     $symb=escape($symb);
1.187     www      4815:     if (!$namespace) { 
1.620     albertel 4816:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4817:           return ''; 
                   4818:        } 
                   4819:     }
1.620     albertel 4820:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4821: 
                   4822:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4823:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4824: 
1.47      www      4825:     my $namevalue='';
1.800     albertel 4826:     foreach my $key (keys(%$storehash)) {
                   4827:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4828:     }
1.47      www      4829:     $namevalue=~s/\&$//;
1.187     www      4830:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4831:     return critical
                   4832:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4833: }
                   4834: 
1.9       www      4835: # --------------------------------------------------------------------- Restore
                   4836: 
                   4837: sub restore {
1.124     www      4838:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4839:     my $home='';
                   4840: 
1.168     albertel 4841:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4842: 
1.122     albertel 4843:     if (!$symb) {
1.1224    raeburn  4844:         return if ($namespace eq 'courserequests');
                   4845:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4846:     } else {
1.1224    raeburn  4847:         unless ($namespace eq 'courserequests') {
                   4848:             $symb=&escape(&symbclean($symb));
                   4849:         }
1.122     albertel 4850:     }
1.188     www      4851:     if (!$namespace) { 
1.620     albertel 4852:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4853:           return ''; 
                   4854:        } 
                   4855:     }
1.620     albertel 4856:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4857:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4858:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4859:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4860: 
1.12      www      4861:     my %returnhash=();
1.800     albertel 4862:     foreach my $line (split(/\&/,$answer)) {
                   4863: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4864:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4865:     }
1.75      www      4866:     my $version;
                   4867:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4868:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4869:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4870:        }
1.75      www      4871:     }
1.13      www      4872:     return %returnhash;
1.34      www      4873: }
                   4874: 
                   4875: # ---------------------------------------------------------- Course Description
1.1118    foxr     4876: #
                   4877: #  
1.34      www      4878: 
                   4879: sub coursedescription {
1.731     albertel 4880:     my ($courseid,$args)=@_;
1.34      www      4881:     $courseid=~s/^\///;
1.49      www      4882:     $courseid=~s/\_/\//g;
1.34      www      4883:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4884:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4885:     my $normalid=$cdomain.'_'.$cnum;
                   4886:     # need to always cache even if we get errors otherwise we keep 
                   4887:     # trying and trying and trying to get the course description.
                   4888:     my %envhash=();
                   4889:     my %returnhash=();
1.731     albertel 4890:     
                   4891:     my $expiretime=600;
                   4892:     if ($env{'request.course.id'} eq $normalid) {
                   4893: 	$expiretime=120;
                   4894:     }
                   4895: 
                   4896:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4897:     if (!$args->{'freshen_cache'}
                   4898: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4899: 	foreach my $key (keys(%env)) {
                   4900: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4901: 	    my ($setting) = $1;
                   4902: 	    $returnhash{$setting} = $env{$key};
                   4903: 	}
                   4904: 	return %returnhash;
                   4905:     }
                   4906: 
1.1118    foxr     4907:     # get the data again
                   4908: 
1.731     albertel 4909:     if (!$args->{'one_time'}) {
                   4910: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4911:     }
1.811     albertel 4912: 
1.34      www      4913:     if ($chome ne 'no_host') {
1.302     albertel 4914:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4915:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4916: 	   my $username = $env{'user.name'}; # Defult username
                   4917: 	   if(defined $args->{'user'}) {
                   4918: 	       $username = $args->{'user'};
                   4919: 	   }
1.129     albertel 4920:            $returnhash{'home'}= $chome;
                   4921: 	   $returnhash{'domain'} = $cdomain;
                   4922: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4923:            if (!defined($returnhash{'type'})) {
                   4924:                $returnhash{'type'} = 'Course';
                   4925:            }
1.130     albertel 4926:            while (my ($name,$value) = each %returnhash) {
1.53      www      4927:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4928:            }
1.270     www      4929:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4930:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4931: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4932:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4933:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4934:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4935:        }
                   4936:     }
1.731     albertel 4937:     if (!$args->{'one_time'}) {
1.949     raeburn  4938: 	&appenv(\%envhash);
1.731     albertel 4939:     }
1.302     albertel 4940:     return %returnhash;
1.461     www      4941: }
                   4942: 
1.1080    raeburn  4943: sub update_released_required {
                   4944:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4945:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4946:         $cid = $env{'request.course.id'};
                   4947:         $cdom = $env{'course.'.$cid.'.domain'};
                   4948:         $cnum = $env{'course.'.$cid.'.num'};
                   4949:         $chome = $env{'course.'.$cid.'.home'};
                   4950:     }
                   4951:     if ($needsrelease) {
                   4952:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4953:         my $needsupdate;
                   4954:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4955:             $needsupdate = 1;
                   4956:         } else {
                   4957:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4958:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4959:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4960:                 $needsupdate = 1;
                   4961:             }
                   4962:         }
                   4963:         if ($needsupdate) {
                   4964:             my %needshash = (
                   4965:                              'internal.releaserequired' => $needsrelease,
                   4966:                             );
                   4967:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4968:             if ($putresult eq 'ok') {
                   4969:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4970:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4971:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4972:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4973:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4974:                 }
                   4975:             }
                   4976:         }
                   4977:     }
                   4978:     return;
                   4979: }
                   4980: 
1.461     www      4981: # -------------------------------------------------See if a user is privileged
                   4982: 
                   4983: sub privileged {
1.1219    raeburn  4984:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 4985:     my $now = time;
1.1219    raeburn  4986:     my $roles;
                   4987:     if (ref($possroles) eq 'ARRAY') {
                   4988:         $roles = $possroles; 
                   4989:     } else {
                   4990:         $roles = ['dc','su'];
                   4991:     }
                   4992:     if (ref($possdomains) eq 'ARRAY') {
                   4993:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   4994:         foreach my $dom (@{$possdomains}) {
                   4995:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   4996:                 (ref($privileged{$dom}) eq 'HASH')) {
                   4997:                 foreach my $role (@{$roles}) {
                   4998:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   4999:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5000:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5001:                             return 1 unless (($end && $end < $now) ||
                   5002:                                              ($start && $start > $now));
                   5003:                         }
                   5004:                     }
                   5005:                 }
                   5006:             }
                   5007:         }
                   5008:     } else {
                   5009:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5010:         my $now = time;
1.1170    droeschl 5011: 
1.1219    raeburn  5012:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5013:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5014:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5015:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5016:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5017:             }
1.1219    raeburn  5018:         }
                   5019:     }
                   5020:     return 0;
                   5021: }
1.1170    droeschl 5022: 
1.1219    raeburn  5023: sub privileged_by_domain {
                   5024:     my ($domains,$roles) = @_;
                   5025:     my %privileged = ();
                   5026:     my $cachetime = 60*60*24;
                   5027:     my $now = time;
                   5028:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5029:         return %privileged;
                   5030:     }
                   5031:     foreach my $dom (@{$domains}) {
                   5032:         next if (ref($privileged{$dom}) eq 'HASH');
                   5033:         my $needroles;
                   5034:         foreach my $role (@{$roles}) {
                   5035:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5036:             if (defined($cached)) {
                   5037:                 if (ref($result) eq 'HASH') {
                   5038:                     $privileged{$dom}{$role} = $result;
                   5039:                 }
                   5040:             } else {
                   5041:                 $needroles = 1;
                   5042:             }
                   5043:         }
                   5044:         if ($needroles) {
                   5045:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5046:             $privileged{$dom} = {};
                   5047:             foreach my $server (keys(%dompersonnel)) {
                   5048:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5049:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5050:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5051:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5052:                         next if ($end && $end < $now);
                   5053:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5054:                             $dompersonnel{$server}{$item};
                   5055:                     }
                   5056:                 }
                   5057:             }
                   5058:             if (ref($privileged{$dom}) eq 'HASH') {
                   5059:                 foreach my $role (@{$roles}) {
                   5060:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5061:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5062:                     } else {
                   5063:                         my %hash = ();
                   5064:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5065:                     }
                   5066:                 }
                   5067:             }
                   5068:         }
                   5069:     }
                   5070:     return %privileged;
1.9       www      5071: }
1.1       albertel 5072: 
1.103     harris41 5073: # -------------------------------------------------------- Get user privileges
1.11      www      5074: 
                   5075: sub rolesinit {
1.1169    droeschl 5076:     my ($domain, $username) = @_;
                   5077:     my %userroles = ('user.login.time' => time);
                   5078:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5079: 
                   5080:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5081:     # also, blocking can be triggered by an activating timer
                   5082:     # it's saved in the user's %env.
                   5083:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5084:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5085:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5086:         %timerintchk, %timerintenv);
                   5087: 
1.1162    raeburn  5088:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5089:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5090:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5091:     }
1.1169    droeschl 5092: 
1.1162    raeburn  5093:     foreach my $key (keys(%timerinterval)) {
                   5094:         my ($cid,$rest) = split(/\0/,$key);
                   5095:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5096:     }
1.1169    droeschl 5097: 
1.11      www      5098:     my %allroles=();
1.1162    raeburn  5099:     my %allgroups=();
1.11      www      5100: 
1.1169    droeschl 5101:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5102:         my $role = $rolesdump{$area};
                   5103:         $area =~ s/\_\w\w$//;
                   5104: 
                   5105:         my ($trole, $tend, $tstart, $group_privs);
                   5106: 
                   5107:         if ($role =~ /^cr/) {
                   5108:         # Custom role, defined by a user 
                   5109:         # e.g., user.role.cr/msu/smith/mynewrole
                   5110:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5111:                 $trole = $1;
                   5112:                 ($tend, $tstart) = split('_', $2);
                   5113:             } else {
                   5114:                 $trole = $role;
                   5115:             }
                   5116:         } elsif ($role =~ m|^gr/|) {
                   5117:         # Role of member in a group, defined within a course/community
                   5118:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5119:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5120:             next if $tstart eq '-1';
                   5121:             ($trole, $group_privs) = split(/\//, $trole);
                   5122:             $group_privs = &unescape($group_privs);
                   5123:         } else {
                   5124:         # Just a normal role, defined in roles.tab
                   5125:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5126:         }
                   5127: 
                   5128:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5129:                  $username);
                   5130:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5131: 
                   5132:         # role expired or not available yet?
                   5133:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5134:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5135: 
                   5136:         next if $area eq '' or $trole eq '';
                   5137: 
                   5138:         my $spec = "$trole.$area";
                   5139:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5140: 
                   5141:         if ($trole =~ /^cr\//) {
                   5142:         # Custom role, defined by a user
                   5143:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5144:         } elsif ($trole eq 'gr') {
                   5145:         # Role of a member in a group, defined within a course/community
                   5146:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5147:             next;
                   5148:         } else {
                   5149:         # Normal role, defined in roles.tab
                   5150:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5151:         }
                   5152: 
                   5153:         my $cid = $tdomain.'_'.$trest;
                   5154:         unless ($firstaccchk{$cid}) {
                   5155:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5156:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5157:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5158:                         $coursetimerstarts{$cid}{$item}; 
                   5159:                 }
                   5160:             }
                   5161:             $firstaccchk{$cid} = 1;
                   5162:         }
                   5163:         unless ($timerintchk{$cid}) {
                   5164:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5165:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5166:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5167:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5168:                 }
1.12      www      5169:             }
1.1169    droeschl 5170:             $timerintchk{$cid} = 1;
1.191     harris41 5171:         }
1.11      www      5172:     }
1.1169    droeschl 5173: 
                   5174:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5175:         \%allroles, \%allgroups);
                   5176:     $env{'user.adv'} = $userroles{'user.adv'};
                   5177: 
1.1162    raeburn  5178:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5179: }
                   5180: 
1.567     raeburn  5181: sub set_arearole {
1.1215    raeburn  5182:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5183:     unless ($nolog) {
1.567     raeburn  5184: # log the associated role with the area
1.1215    raeburn  5185:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5186:     }
1.743     albertel 5187:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5188: }
                   5189: 
                   5190: sub custom_roleprivs {
                   5191:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5192:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5193:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5194:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5195:         my ($rdummy,$roledef)=
                   5196:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5197:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5198:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5199:             if (defined($syspriv)) {
1.1043    raeburn  5200:                 if ($trest =~ /^$match_community$/) {
                   5201:                     $syspriv =~ s/bre\&S//; 
                   5202:                 }
1.567     raeburn  5203:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5204:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5205:             }
                   5206:             if ($tdomain ne '') {
                   5207:                 if (defined($dompriv)) {
                   5208:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5209:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5210:                 }
                   5211:                 if (($trest ne '') && (defined($coursepriv))) {
                   5212:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5213:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5214:                 }
                   5215:             }
                   5216:         }
                   5217:     }
                   5218: }
                   5219: 
1.678     raeburn  5220: sub group_roleprivs {
                   5221:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5222:     my $access = 1;
                   5223:     my $now = time;
                   5224:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5225:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5226:     if ($access) {
1.811     albertel 5227:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5228:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5229:     }
                   5230: }
1.567     raeburn  5231: 
                   5232: sub standard_roleprivs {
                   5233:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5234:     if (defined($pr{$trole.':s'})) {
                   5235:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5236:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5237:     }
                   5238:     if ($tdomain ne '') {
                   5239:         if (defined($pr{$trole.':d'})) {
                   5240:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5241:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5242:         }
                   5243:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5244:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5245:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5246:         }
                   5247:     }
                   5248: }
                   5249: 
                   5250: sub set_userprivs {
1.1064    raeburn  5251:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5252:     my $author=0;
                   5253:     my $adv=0;
1.678     raeburn  5254:     my %grouproles = ();
                   5255:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5256:         my @groupkeys; 
1.1000    raeburn  5257:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5258:             push(@groupkeys,$role);
                   5259:         }
                   5260:         if (ref($groups_roles) eq 'HASH') {
                   5261:             foreach my $key (keys(%{$groups_roles})) {
                   5262:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5263:                     push(@groupkeys,$key);
                   5264:                 }
                   5265:             }
                   5266:         }
                   5267:         if (@groupkeys > 0) {
                   5268:             foreach my $role (@groupkeys) {
                   5269:                 my ($trole,$area,$sec,$extendedarea);
                   5270:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5271:                     $trole = $1;
                   5272:                     $area = $2;
                   5273:                     $sec = $3;
                   5274:                     $extendedarea = $area.$sec;
                   5275:                     if (exists($$allgroups{$area})) {
                   5276:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5277:                             my $spec = $trole.'.'.$extendedarea;
                   5278:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5279:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5280:                         }
1.678     raeburn  5281:                     }
                   5282:                 }
                   5283:             }
                   5284:         }
                   5285:     }
1.800     albertel 5286:     foreach my $group (keys(%grouproles)) {
                   5287:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5288:     }
1.800     albertel 5289:     foreach my $role (keys(%{$allroles})) {
                   5290:         my %thesepriv;
1.941     raeburn  5291:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5292:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5293:             if ($item ne '') {
                   5294:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5295:                 if ($restrictions eq '') {
                   5296:                     $thesepriv{$privilege}='F';
                   5297:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5298:                     $thesepriv{$privilege}.=$restrictions;
                   5299:                 }
                   5300:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5301:             }
                   5302:         }
                   5303:         my $thesestr='';
1.1104    raeburn  5304:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5305: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5306: 	}
                   5307:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5308:     }
                   5309:     return ($author,$adv);
                   5310: }
                   5311: 
1.994     raeburn  5312: sub role_status {
1.1104    raeburn  5313:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5314:     my @pwhere = ();
                   5315:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5316:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5317:         unless (!defined($$role) || $$role eq '') {
                   5318:             $$where=join('.',@pwhere);
                   5319:             $$trolecode=$$role.'.'.$$where;
                   5320:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5321:             $$tstatus='is';
1.1104    raeburn  5322:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5323:                 $$tstatus='future';
1.1034    raeburn  5324:                 if ($$tstart<$now) {
                   5325:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5326:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5327:                             my (%allroles,%allgroups,$group_privs,
                   5328:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5329:                             my %userroles = (
                   5330:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5331:                             );
1.1064    raeburn  5332:                             @rolecodes = ('cm'); 
1.1002    raeburn  5333:                             my $spec=$$role.'.'.$$where;
                   5334:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5335:                             if ($$role =~ /^cr\//) {
                   5336:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5337:                                 push(@rolecodes,'cr');
1.1002    raeburn  5338:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5339:                                 push(@rolecodes,$$role);
1.1002    raeburn  5340:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5341:                                                     $env{'user.name'});
1.1064    raeburn  5342:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5343:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5344:                                 $group_privs = &unescape($group_privs);
                   5345:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5346:                                 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  5347:                                 &get_groups_roles($tdomain,$trest,
                   5348:                                                   \%course_roles,\@rolecodes,
                   5349:                                                   \%groups_roles);
1.1002    raeburn  5350:                             } else {
1.1064    raeburn  5351:                                 push(@rolecodes,$$role);
1.1002    raeburn  5352:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5353:                             }
1.1064    raeburn  5354:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5355:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5356:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5357:                         }
                   5358:                     }
1.1034    raeburn  5359:                     $$tstatus = 'is';
1.1002    raeburn  5360:                 }
1.994     raeburn  5361:             }
                   5362:             if ($$tend) {
1.1104    raeburn  5363:                 if ($$tend<$update) {
1.994     raeburn  5364:                     $$tstatus='expired';
                   5365:                 } elsif ($$tend<$now) {
                   5366:                     $$tstatus='will_not';
                   5367:                 }
                   5368:             }
                   5369:         }
                   5370:     }
                   5371: }
                   5372: 
1.1104    raeburn  5373: sub get_groups_roles {
                   5374:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5375:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5376:                   (ref($rolecodes) eq 'ARRAY') && 
                   5377:                   (ref($groups_roles) eq 'HASH')); 
                   5378:     if (keys(%{$cdom_courseroles}) > 0) {
                   5379:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5380:         if ($cdom ne '' && $cnum ne '') {
                   5381:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5382:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5383:                     my $crsrole = $1;
                   5384:                     my $crssec = $2;
                   5385:                     if ($crsrole =~ /^cr/) {
                   5386:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5387:                             push(@{$rolecodes},'cr');
                   5388:                         }
                   5389:                     } else {
                   5390:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5391:                             push(@{$rolecodes},$crsrole);
                   5392:                         }
                   5393:                     }
                   5394:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5395:                     if ($crssec ne '') {
                   5396:                         $rolekey .= "/$crssec";
                   5397:                     }
                   5398:                     $rolekey .= './';
                   5399:                     $groups_roles->{$rolekey} = $rolecodes;
                   5400:                 }
                   5401:             }
                   5402:         }
                   5403:     }
                   5404:     return;
                   5405: }
                   5406: 
                   5407: sub delete_env_groupprivs {
                   5408:     my ($where,$courseroles,$possroles) = @_;
                   5409:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5410:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5411:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5412:         %{$courseroles->{$udom}} =
                   5413:             &get_my_roles('','','userroles',['active'],
                   5414:                           $possroles,[$udom],1);
                   5415:     }
                   5416:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5417:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5418:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5419:             my $area = '/'.$cdom.'/'.$cnum;
                   5420:             my $privkey = "user.priv.$crsrole.$area";
                   5421:             if ($crssec ne '') {
                   5422:                 $privkey .= '/'.$crssec;
                   5423:             }
                   5424:             $privkey .= ".$area/$group";
                   5425:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5426:         }
                   5427:     }
                   5428:     return;
                   5429: }
                   5430: 
1.994     raeburn  5431: sub check_adhoc_privs {
1.1104    raeburn  5432:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5433:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5434:     my $setprivs;
1.994     raeburn  5435:     if ($env{$cckey}) {
                   5436:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5437:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5438:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5439:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5440:             $setprivs = 1;
1.994     raeburn  5441:         }
                   5442:     } else {
1.1088    raeburn  5443:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5444:         $setprivs = 1;
1.994     raeburn  5445:     }
1.1185    raeburn  5446:     return $setprivs;
1.994     raeburn  5447: }
                   5448: 
                   5449: sub set_adhoc_privileges {
                   5450: # role can be cc or ca
1.1088    raeburn  5451:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5452:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5453:     my $spec = $role.'.'.$area;
                   5454:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5455:                                   $env{'user.name'},1);
1.994     raeburn  5456:     my %ccrole = ();
                   5457:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5458:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5459:     &appenv(\%userroles,[$role,'cm']);
                   5460:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5461:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5462:         &appenv( {'request.role'        => $spec,
                   5463:                   'request.role.domain' => $dcdom,
                   5464:                   'request.course.sec'  => ''
                   5465:                  }
                   5466:                );
                   5467:         my $tadv=0;
                   5468:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5469:         &appenv({'request.role.adv'    => $tadv});
                   5470:     }
1.994     raeburn  5471: }
                   5472: 
1.12      www      5473: # --------------------------------------------------------------- get interface
                   5474: 
                   5475: sub get {
1.131     albertel 5476:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5477:    my $items='';
1.800     albertel 5478:    foreach my $item (@$storearr) {
                   5479:        $items.=&escape($item).'&';
1.191     harris41 5480:    }
1.12      www      5481:    $items=~s/\&$//;
1.620     albertel 5482:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5483:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5484:    my $uhome=&homeserver($uname,$udomain);
                   5485: 
1.133     albertel 5486:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5487:    my @pairs=split(/\&/,$rep);
1.273     albertel 5488:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5489:      return @pairs;
                   5490:    }
1.15      www      5491:    my %returnhash=();
1.42      www      5492:    my $i=0;
1.800     albertel 5493:    foreach my $item (@$storearr) {
                   5494:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5495:       $i++;
1.191     harris41 5496:    }
1.15      www      5497:    return %returnhash;
1.27      www      5498: }
                   5499: 
                   5500: # --------------------------------------------------------------- del interface
                   5501: 
                   5502: sub del {
1.133     albertel 5503:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5504:    my $items='';
1.800     albertel 5505:    foreach my $item (@$storearr) {
                   5506:        $items.=&escape($item).'&';
1.191     harris41 5507:    }
1.984     neumanie 5508: 
1.27      www      5509:    $items=~s/\&$//;
1.620     albertel 5510:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5511:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5512:    my $uhome=&homeserver($uname,$udomain);
                   5513:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5514: }
                   5515: 
                   5516: # -------------------------------------------------------------- dump interface
                   5517: 
1.1180    droeschl 5518: sub unserialize {
                   5519:     my ($rep, $escapedkeys) = @_;
                   5520: 
                   5521:     return {} if $rep =~ /^error/;
                   5522: 
                   5523:     my %returnhash=();
                   5524: 	foreach my $item (split /\&/, $rep) {
                   5525: 	    my ($key, $value) = split(/=/, $item, 2);
                   5526: 	    $key = unescape($key) unless $escapedkeys;
                   5527: 	    next if $key =~ /^error: 2 /;
                   5528: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5529: 	}
                   5530:     #return %returnhash;
                   5531:     return \%returnhash;
                   5532: }        
                   5533: 
                   5534: # see Lond::dump_with_regexp
                   5535: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5536: sub dump {
1.1180    droeschl 5537:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5538:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5539:     if (!$uname) { $uname=$env{'user.name'}; }
                   5540:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5541: 
1.1180    droeschl 5542:     my $reply;
                   5543:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5544:         # user is hosted on this machine
                   5545:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5546:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5547:         return %{unserialize($reply, $escapedkeys)};
                   5548:     }
1.755     albertel 5549:     if ($regexp) {
                   5550: 	$regexp=&escape($regexp);
                   5551:     } else {
                   5552: 	$regexp='.';
                   5553:     }
1.1166    raeburn  5554:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5555:     my @pairs=split(/\&/,$rep);
                   5556:     my %returnhash=();
1.1098    foxr     5557:     if (!($rep =~ /^error/ )) {
                   5558: 	foreach my $item (@pairs) {
                   5559: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5560:         $key = unescape($key) unless $escapedkeys;
                   5561:         #$key = &unescape($key);
1.1098    foxr     5562: 	    next if ($key =~ /^error: 2 /);
                   5563: 	    $returnhash{$key}=&thaw_unescape($value);
                   5564: 	}
1.755     albertel 5565:     }
                   5566:     return %returnhash;
1.407     www      5567: }
                   5568: 
1.1098    foxr     5569: 
1.717     albertel 5570: # --------------------------------------------------------- dumpstore interface
                   5571: 
                   5572: sub dumpstore {
                   5573:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5574:    # same as dump but keys must be escaped. They may contain colon separated
                   5575:    # lists of values that may themself contain colons (e.g. symbs).
                   5576:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5577: }
                   5578: 
1.407     www      5579: # -------------------------------------------------------------- keys interface
                   5580: 
                   5581: sub getkeys {
                   5582:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5583:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5584:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5585:    my $uhome=&homeserver($uname,$udomain);
                   5586:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5587:    my @keyarray=();
1.800     albertel 5588:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5589:       next if ($key =~ /^error: 2 /);
1.800     albertel 5590:       push(@keyarray,&unescape($key));
1.407     www      5591:    }
                   5592:    return @keyarray;
1.318     matthew  5593: }
                   5594: 
1.319     matthew  5595: # --------------------------------------------------------------- currentdump
                   5596: sub currentdump {
1.328     matthew  5597:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5598:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5599:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5600:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5601:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5602:    my $rep;
                   5603: 
                   5604:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5605:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5606:                    $courseid)));
                   5607:    } else {
                   5608:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5609:    }
                   5610: 
1.318     matthew  5611:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5612:    #
1.318     matthew  5613:    my %returnhash=();
1.319     matthew  5614:    #
                   5615:    if ($rep eq "unknown_cmd") { 
                   5616:        # an old lond will not know currentdump
                   5617:        # Do a dump and make it look like a currentdump
1.822     albertel 5618:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5619:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5620:        my %hash = @tmp;
                   5621:        @tmp=();
1.424     matthew  5622:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5623:    } else {
                   5624:        my @pairs=split(/\&/,$rep);
1.800     albertel 5625:        foreach my $pair (@pairs) {
                   5626:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5627:            my ($symb,$param) = split(/:/,$key);
                   5628:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5629:                                                         &thaw_unescape($value);
1.319     matthew  5630:        }
1.191     harris41 5631:    }
1.12      www      5632:    return %returnhash;
1.424     matthew  5633: }
                   5634: 
                   5635: sub convert_dump_to_currentdump{
                   5636:     my %hash = %{shift()};
                   5637:     my %returnhash;
                   5638:     # Code ripped from lond, essentially.  The only difference
                   5639:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5640:     # we might run in to problems with parameter names =~ /^v\./
                   5641:     while (my ($key,$value) = each(%hash)) {
                   5642:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5643: 	$symb  = &unescape($symb);
                   5644: 	$param = &unescape($param);
1.424     matthew  5645:         next if ($v eq 'version' || $symb eq 'keys');
                   5646:         next if (exists($returnhash{$symb}) &&
                   5647:                  exists($returnhash{$symb}->{$param}) &&
                   5648:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5649:         $returnhash{$symb}->{$param}=$value;
                   5650:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5651:     }
                   5652:     #
                   5653:     # Remove all of the keys in the hashes which keep track of
                   5654:     # the version of the parameter.
                   5655:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5656:         # use a foreach because we are going to delete from the hash.
                   5657:         foreach my $key (keys(%$param_hash)) {
                   5658:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5659:         }
                   5660:     }
                   5661:     return \%returnhash;
1.12      www      5662: }
                   5663: 
1.627     albertel 5664: # ------------------------------------------------------ critical inc interface
                   5665: 
                   5666: sub cinc {
                   5667:     return &inc(@_,'critical');
                   5668: }
                   5669: 
1.449     matthew  5670: # --------------------------------------------------------------- inc interface
                   5671: 
                   5672: sub inc {
1.627     albertel 5673:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5674:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5675:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5676:     my $uhome=&homeserver($uname,$udomain);
                   5677:     my $items='';
                   5678:     if (! ref($store)) {
                   5679:         # got a single value, so use that instead
                   5680:         $items = &escape($store).'=&';
                   5681:     } elsif (ref($store) eq 'SCALAR') {
                   5682:         $items = &escape($$store).'=&';        
                   5683:     } elsif (ref($store) eq 'ARRAY') {
                   5684:         $items = join('=&',map {&escape($_);} @{$store});
                   5685:     } elsif (ref($store) eq 'HASH') {
                   5686:         while (my($key,$value) = each(%{$store})) {
                   5687:             $items.= &escape($key).'='.&escape($value).'&';
                   5688:         }
                   5689:     }
                   5690:     $items=~s/\&$//;
1.627     albertel 5691:     if ($critical) {
                   5692: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5693:     } else {
                   5694: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5695:     }
1.449     matthew  5696: }
                   5697: 
1.12      www      5698: # --------------------------------------------------------------- put interface
                   5699: 
                   5700: sub put {
1.134     albertel 5701:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5702:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5703:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5704:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5705:    my $items='';
1.800     albertel 5706:    foreach my $item (keys(%$storehash)) {
                   5707:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5708:    }
1.12      www      5709:    $items=~s/\&$//;
1.134     albertel 5710:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5711: }
                   5712: 
1.631     albertel 5713: # ------------------------------------------------------------ newput interface
                   5714: 
                   5715: sub newput {
                   5716:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5717:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5718:    if (!$uname) { $uname=$env{'user.name'}; }
                   5719:    my $uhome=&homeserver($uname,$udomain);
                   5720:    my $items='';
                   5721:    foreach my $key (keys(%$storehash)) {
                   5722:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5723:    }
                   5724:    $items=~s/\&$//;
                   5725:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5726: }
                   5727: 
                   5728: # ---------------------------------------------------------  putstore interface
                   5729: 
1.524     raeburn  5730: sub putstore {
1.715     albertel 5731:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5732:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5733:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5734:    my $uhome=&homeserver($uname,$udomain);
                   5735:    my $items='';
1.715     albertel 5736:    foreach my $key (keys(%$storehash)) {
                   5737:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5738:    }
1.715     albertel 5739:    $items=~s/\&$//;
1.716     albertel 5740:    my $esc_symb=&escape($symb);
                   5741:    my $esc_v=&escape($version);
1.715     albertel 5742:    my $reply =
1.716     albertel 5743:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5744: 	      $uhome);
                   5745:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5746:        # gfall back to way things use to be done
1.715     albertel 5747:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5748: 			    $uname);
1.524     raeburn  5749:    }
1.715     albertel 5750:    return $reply;
                   5751: }
                   5752: 
                   5753: sub old_putstore {
1.716     albertel 5754:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5755:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5756:     if (!$uname) { $uname=$env{'user.name'}; }
                   5757:     my $uhome=&homeserver($uname,$udomain);
                   5758:     my %newstorehash;
1.800     albertel 5759:     foreach my $item (keys(%$storehash)) {
                   5760: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5761: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5762:     }
                   5763:     my $items='';
                   5764:     my %allitems = ();
1.800     albertel 5765:     foreach my $item (keys(%newstorehash)) {
                   5766: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5767: 	    my $key = $1.':keys:'.$2;
                   5768: 	    $allitems{$key} .= $3.':';
                   5769: 	}
1.800     albertel 5770: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5771:     }
1.800     albertel 5772:     foreach my $item (keys(%allitems)) {
                   5773: 	$allitems{$item} =~ s/\:$//;
                   5774: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5775:     }
                   5776:     $items=~s/\&$//;
                   5777:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5778: }
                   5779: 
1.47      www      5780: # ------------------------------------------------------ critical put interface
                   5781: 
                   5782: sub cput {
1.134     albertel 5783:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5784:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5785:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5786:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5787:    my $items='';
1.800     albertel 5788:    foreach my $item (keys(%$storehash)) {
                   5789:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5790:    }
1.47      www      5791:    $items=~s/\&$//;
1.134     albertel 5792:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5793: }
                   5794: 
                   5795: # -------------------------------------------------------------- eget interface
                   5796: 
                   5797: sub eget {
1.133     albertel 5798:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5799:    my $items='';
1.800     albertel 5800:    foreach my $item (@$storearr) {
                   5801:        $items.=&escape($item).'&';
1.191     harris41 5802:    }
1.12      www      5803:    $items=~s/\&$//;
1.620     albertel 5804:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5805:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5806:    my $uhome=&homeserver($uname,$udomain);
                   5807:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5808:    my @pairs=split(/\&/,$rep);
                   5809:    my %returnhash=();
1.42      www      5810:    my $i=0;
1.800     albertel 5811:    foreach my $item (@$storearr) {
                   5812:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5813:       $i++;
1.191     harris41 5814:    }
1.12      www      5815:    return %returnhash;
                   5816: }
                   5817: 
1.667     albertel 5818: # ------------------------------------------------------------ tmpput interface
                   5819: sub tmpput {
1.802     raeburn  5820:     my ($storehash,$server,$context)=@_;
1.667     albertel 5821:     my $items='';
1.800     albertel 5822:     foreach my $item (keys(%$storehash)) {
                   5823: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5824:     }
                   5825:     $items=~s/\&$//;
1.802     raeburn  5826:     if (defined($context)) {
                   5827:         $items .= ':'.&escape($context);
                   5828:     }
1.667     albertel 5829:     return &reply("tmpput:$items",$server);
                   5830: }
                   5831: 
                   5832: # ------------------------------------------------------------ tmpget interface
                   5833: sub tmpget {
1.688     albertel 5834:     my ($token,$server)=@_;
                   5835:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5836:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5837:     my %returnhash;
                   5838:     foreach my $item (split(/\&/,$rep)) {
                   5839: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5840:         next if ($key =~ /^error: 2 /);
1.667     albertel 5841: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5842:     }
                   5843:     return %returnhash;
                   5844: }
                   5845: 
1.1113    raeburn  5846: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5847: sub tmpdel {
                   5848:     my ($token,$server)=@_;
                   5849:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5850:     return &reply("tmpdel:$token",$server);
                   5851: }
                   5852: 
1.1198    raeburn  5853: # ------------------------------------------------------------ get_timebased_id 
                   5854: 
                   5855: sub get_timebased_id {
                   5856:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5857:         $maxtries) = @_;
                   5858:     my ($newid,$error,$dellock);
                   5859:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5860:         return ('','ok','invalid call to get suffix');
                   5861:     }
                   5862: 
                   5863: # set defaults for any optional args for which values were not supplied
                   5864:     if ($who eq '') {
                   5865:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5866:     }
                   5867:     if (!$locktries) {
                   5868:         $locktries = 3;
                   5869:     }
                   5870:     if (!$maxtries) {
                   5871:         $maxtries = 10;
                   5872:     }
                   5873:     
                   5874:     if (($cdom eq '') || ($cnum eq '')) {
                   5875:         if ($env{'request.course.id'}) {
                   5876:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5877:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5878:         }
                   5879:         if (($cdom eq '') || ($cnum eq '')) {
                   5880:             return ('','ok','call to get suffix not in course context');
                   5881:         }
                   5882:     }
                   5883: 
                   5884: # construct locking item
                   5885:     my $lockhash = {
                   5886:                       $prefix."\0".'locked_'.$keyid => $who,
                   5887:                    };
                   5888:     my $tries = 0;
                   5889: 
                   5890: # attempt to get lock on nohist_$namespace file
                   5891:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5892:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5893:         $tries ++;
                   5894:         sleep 1;
                   5895:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5896:     }
                   5897: 
                   5898: # attempt to get unique identifier, based on current timestamp
                   5899:     if ($gotlock eq 'ok') {
                   5900:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5901:         my $id = time;
                   5902:         $newid = $id;
                   5903:         my $idtries = 0;
                   5904:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5905:             if ($idtype eq 'concat') {
                   5906:                 $newid = $id.$idtries;
                   5907:             } else {
                   5908:                 $newid ++;
                   5909:             }
                   5910:             $idtries ++;
                   5911:         }
                   5912:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5913:             my %new_item =  (
                   5914:                               $prefix."\0".$newid => $who,
                   5915:                             );
                   5916:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5917:                                                  $cdom,$cnum);
                   5918:             if ($putresult ne 'ok') {
                   5919:                 undef($newid);
                   5920:                 $error = 'error saving new item: '.$putresult;
                   5921:             }
                   5922:         } else {
                   5923:              $error = ('error: no unique suffix available for the new item ');
                   5924:         }
                   5925: #  remove lock
                   5926:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5927:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5928:     } else {
                   5929:         $error = "error: could not obtain lockfile\n";
                   5930:         $dellock = 'ok';
                   5931:     }
                   5932:     return ($newid,$dellock,$error);
                   5933: }
                   5934: 
1.765     albertel 5935: # -------------------------------------------------- portfolio access checking
                   5936: 
                   5937: sub portfolio_access {
1.766     albertel 5938:     my ($requrl) = @_;
1.765     albertel 5939:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5940:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5941:     if ($result) {
                   5942:         my %setters;
                   5943:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5944:             my ($startblock,$endblock) =
                   5945:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5946:             if ($startblock && $endblock) {
                   5947:                 return 'B';
                   5948:             }
                   5949:         } else {
                   5950:             my ($startblock,$endblock) =
                   5951:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5952:             if ($startblock && $endblock) {
                   5953:                 return 'B';
                   5954:             }
                   5955:         }
                   5956:     }
1.765     albertel 5957:     if ($result eq 'ok') {
1.766     albertel 5958:        return 'F';
1.765     albertel 5959:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5960:        return 'A';
1.765     albertel 5961:     }
1.766     albertel 5962:     return '';
1.765     albertel 5963: }
                   5964: 
                   5965: sub get_portfolio_access {
1.767     albertel 5966:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5967: 
                   5968:     if (!ref($access_hash)) {
                   5969: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5970: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5971: 						   $file_name);
                   5972: 	$access_hash = $access_controls{$file_name};
                   5973:     }
                   5974: 
1.765     albertel 5975:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5976:     my $now = time;
                   5977:     if (ref($access_hash) eq 'HASH') {
                   5978:         foreach my $key (keys(%{$access_hash})) {
                   5979:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5980:             if ($start > $now) {
                   5981:                 next;
                   5982:             }
                   5983:             if ($end && $end<$now) {
                   5984:                 next;
                   5985:             }
                   5986:             if ($scope eq 'public') {
                   5987:                 $public = $key;
                   5988:                 last;
                   5989:             } elsif ($scope eq 'guest') {
                   5990:                 $guest = $key;
                   5991:             } elsif ($scope eq 'domains') {
                   5992:                 push(@domains,$key);
                   5993:             } elsif ($scope eq 'users') {
                   5994:                 push(@users,$key);
                   5995:             } elsif ($scope eq 'course') {
                   5996:                 push(@courses,$key);
                   5997:             } elsif ($scope eq 'group') {
                   5998:                 push(@groups,$key);
                   5999:             }
                   6000:         }
                   6001:         if ($public) {
                   6002:             return 'ok';
                   6003:         }
                   6004:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6005:             if ($guest) {
                   6006:                 return $guest;
                   6007:             }
                   6008:         } else {
                   6009:             if (@domains > 0) {
                   6010:                 foreach my $domkey (@domains) {
                   6011:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6012:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6013:                             return 'ok';
                   6014:                         }
                   6015:                     }
                   6016:                 }
                   6017:             }
                   6018:             if (@users > 0) {
                   6019:                 foreach my $userkey (@users) {
1.865     raeburn  6020:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6021:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6022:                             if (ref($item) eq 'HASH') {
                   6023:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6024:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6025:                                     return 'ok';
                   6026:                                 }
                   6027:                             }
                   6028:                         }
                   6029:                     } 
1.765     albertel 6030:                 }
                   6031:             }
                   6032:             my %roleshash;
                   6033:             my @courses_and_groups = @courses;
                   6034:             push(@courses_and_groups,@groups); 
                   6035:             if (@courses_and_groups > 0) {
                   6036:                 my (%allgroups,%allroles); 
                   6037:                 my ($start,$end,$role,$sec,$group);
                   6038:                 foreach my $envkey (%env) {
1.1060    raeburn  6039:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6040:                         my $cid = $2.'_'.$3; 
                   6041:                         if ($1 eq 'gr') {
                   6042:                             $group = $4;
                   6043:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6044:                         } else {
                   6045:                             if ($4 eq '') {
                   6046:                                 $sec = 'none';
                   6047:                             } else {
                   6048:                                 $sec = $4;
                   6049:                             }
                   6050:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6051:                         }
1.811     albertel 6052:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6053:                         my $cid = $2.'_'.$3;
                   6054:                         if ($4 eq '') {
                   6055:                             $sec = 'none';
                   6056:                         } else {
                   6057:                             $sec = $4;
                   6058:                         }
                   6059:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6060:                     }
                   6061:                 }
                   6062:                 if (keys(%allroles) == 0) {
                   6063:                     return;
                   6064:                 }
                   6065:                 foreach my $key (@courses_and_groups) {
                   6066:                     my %content = %{$$access_hash{$key}};
                   6067:                     my $cnum = $content{'number'};
                   6068:                     my $cdom = $content{'domain'};
                   6069:                     my $cid = $cdom.'_'.$cnum;
                   6070:                     if (!exists($allroles{$cid})) {
                   6071:                         next;
                   6072:                     }    
                   6073:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6074:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6075:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6076:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6077:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6078:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6079:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6080:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6081:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6082:                                         if (grep/^all$/,@sections) {
                   6083:                                             return 'ok';
                   6084:                                         } else {
                   6085:                                             if (grep/^$sec$/,@sections) {
                   6086:                                                 return 'ok';
                   6087:                                             }
                   6088:                                         }
                   6089:                                     }
                   6090:                                 }
                   6091:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6092:                                     if (grep/^none$/,@groups) {
                   6093:                                         return 'ok';
                   6094:                                     }
                   6095:                                 } else {
                   6096:                                     if (grep/^all$/,@groups) {
                   6097:                                         return 'ok';
                   6098:                                     } 
                   6099:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6100:                                         if (grep/^$group$/,@groups) {
                   6101:                                             return 'ok';
                   6102:                                         }
                   6103:                                     }
                   6104:                                 } 
                   6105:                             }
                   6106:                         }
                   6107:                     }
                   6108:                 }
                   6109:             }
                   6110:             if ($guest) {
                   6111:                 return $guest;
                   6112:             }
                   6113:         }
                   6114:     }
                   6115:     return;
                   6116: }
                   6117: 
                   6118: sub course_group_datechecker {
                   6119:     my ($dates,$now,$status) = @_;
                   6120:     my ($start,$end) = split(/\./,$dates);
                   6121:     if (!$start && !$end) {
                   6122:         return 'ok';
                   6123:     }
                   6124:     if (grep/^active$/,@{$status}) {
                   6125:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6126:             return 'ok';
                   6127:         }
                   6128:     }
                   6129:     if (grep/^previous$/,@{$status}) {
                   6130:         if ($end > $now ) {
                   6131:             return 'ok';
                   6132:         }
                   6133:     }
                   6134:     if (grep/^future$/,@{$status}) {
                   6135:         if ($start > $now) {
                   6136:             return 'ok';
                   6137:         }
                   6138:     }
                   6139:     return; 
                   6140: }
                   6141: 
                   6142: sub parse_portfolio_url {
                   6143:     my ($url) = @_;
                   6144: 
                   6145:     my ($type,$udom,$unum,$group,$file_name);
                   6146:     
1.823     albertel 6147:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6148: 	$type = 1;
                   6149:         $udom = $1;
                   6150:         $unum = $2;
                   6151:         $file_name = $3;
1.823     albertel 6152:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6153: 	$type = 2;
                   6154:         $udom = $1;
                   6155:         $unum = $2;
                   6156:         $group = $3;
                   6157:         $file_name = $3.'/'.$4;
                   6158:     }
                   6159:     if (wantarray) {
                   6160: 	return ($type,$udom,$unum,$file_name,$group);
                   6161:     }
                   6162:     return $type;
                   6163: }
                   6164: 
                   6165: sub is_portfolio_url {
                   6166:     my ($url) = @_;
                   6167:     return scalar(&parse_portfolio_url($url));
                   6168: }
                   6169: 
1.798     raeburn  6170: sub is_portfolio_file {
                   6171:     my ($file) = @_;
1.820     raeburn  6172:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6173:         return 1;
                   6174:     }
                   6175:     return;
                   6176: }
                   6177: 
1.976     raeburn  6178: sub usertools_access {
1.1084    raeburn  6179:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6180:     my ($access,%tools);
                   6181:     if ($context eq '') {
                   6182:         $context = 'tools';
                   6183:     }
                   6184:     if ($context eq 'requestcourses') {
                   6185:         %tools = (
                   6186:                       official   => 1,
                   6187:                       unofficial => 1,
1.1006    raeburn  6188:                       community  => 1,
1.985     raeburn  6189:                  );
1.1183    raeburn  6190:     } elsif ($context eq 'requestauthor') {
                   6191:         %tools = (
                   6192:                       requestauthor => 1,
                   6193:                  );
1.985     raeburn  6194:     } else {
                   6195:         %tools = (
                   6196:                       aboutme   => 1,
                   6197:                       blog      => 1,
1.1177    raeburn  6198:                       webdav    => 1,
1.985     raeburn  6199:                       portfolio => 1,
                   6200:                  );
                   6201:     }
1.976     raeburn  6202:     return if (!defined($tools{$tool}));
                   6203: 
                   6204:     if ((!defined($udom)) || (!defined($uname))) {
                   6205:         $udom = $env{'user.domain'};
                   6206:         $uname = $env{'user.name'};
                   6207:     }
                   6208: 
1.978     raeburn  6209:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6210:         if ($action ne 'reload') {
1.985     raeburn  6211:             if ($context eq 'requestcourses') {
                   6212:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6213:             } elsif ($context eq 'requestauthor') {
                   6214:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6215:             } else {
                   6216:                 return $env{'environment.availabletools.'.$tool};
                   6217:             }
                   6218:         }
1.976     raeburn  6219:     }
                   6220: 
1.1183    raeburn  6221:     my ($toolstatus,$inststatus,$envkey);
                   6222:     if ($context eq 'requestauthor') {
                   6223:         $envkey = $context; 
                   6224:     } else {
                   6225:         $envkey = $context.'.'.$tool;
                   6226:     }
1.976     raeburn  6227: 
1.985     raeburn  6228:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6229:          ($action ne 'reload')) {
1.1183    raeburn  6230:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6231:         $inststatus = $env{'environment.inststatus'};
                   6232:     } else {
1.1084    raeburn  6233:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6234:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6235:             $inststatus = $userenvref->{'inststatus'};
                   6236:         } else {
1.1183    raeburn  6237:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6238:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6239:             $inststatus = $userenv{'inststatus'};
                   6240:         }
1.976     raeburn  6241:     }
                   6242: 
                   6243:     if ($toolstatus ne '') {
                   6244:         if ($toolstatus) {
                   6245:             $access = 1;
                   6246:         } else {
                   6247:             $access = 0;
                   6248:         }
                   6249:         return $access;
                   6250:     }
                   6251: 
1.1084    raeburn  6252:     my ($is_adv,%domdef);
                   6253:     if (ref($is_advref) eq 'HASH') {
                   6254:         $is_adv = $is_advref->{'is_adv'};
                   6255:     } else {
                   6256:         $is_adv = &is_advanced_user($udom,$uname);
                   6257:     }
                   6258:     if (ref($domdefref) eq 'HASH') {
                   6259:         %domdef = %{$domdefref};
                   6260:     } else {
                   6261:         %domdef = &get_domain_defaults($udom);
                   6262:     }
1.976     raeburn  6263:     if (ref($domdef{$tool}) eq 'HASH') {
                   6264:         if ($is_adv) {
                   6265:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6266:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6267:                     $access = 1;
                   6268:                 } else {
                   6269:                     $access = 0;
                   6270:                 }
                   6271:                 return $access;
                   6272:             }
                   6273:         }
                   6274:         if ($inststatus ne '') {
                   6275:             my ($hasaccess,$hasnoaccess);
                   6276:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6277:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6278:                     if ($domdef{$tool}{$affiliation}) {
                   6279:                         $hasaccess = 1;
                   6280:                     } else {
                   6281:                         $hasnoaccess = 1;
                   6282:                     }
                   6283:                 }
                   6284:             }
                   6285:             if ($hasaccess || $hasnoaccess) {
                   6286:                 if ($hasaccess) {
                   6287:                     $access = 1;
                   6288:                 } elsif ($hasnoaccess) {
                   6289:                     $access = 0; 
                   6290:                 }
                   6291:                 return $access;
                   6292:             }
                   6293:         } else {
                   6294:             if ($domdef{$tool}{'default'} ne '') {
                   6295:                 if ($domdef{$tool}{'default'}) {
                   6296:                     $access = 1;
                   6297:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6298:                     $access = 0;
                   6299:                 }
                   6300:                 return $access;
                   6301:             }
                   6302:         }
                   6303:     } else {
1.1177    raeburn  6304:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6305:             $access = 1;
                   6306:         } else {
                   6307:             $access = 0;
                   6308:         }
1.976     raeburn  6309:         return $access;
                   6310:     }
                   6311: }
                   6312: 
1.1050    raeburn  6313: sub is_course_owner {
                   6314:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6315:     if (($udom eq '') || ($uname eq '')) {
                   6316:         $udom = $env{'user.domain'};
                   6317:         $uname = $env{'user.name'};
                   6318:     }
                   6319:     unless (($udom eq '') || ($uname eq '')) {
                   6320:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6321:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6322:                 return 1;
                   6323:             } else {
                   6324:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6325:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6326:                     return 1;
                   6327:                 }
                   6328:             }
                   6329:         }
                   6330:     }
                   6331:     return;
                   6332: }
                   6333: 
1.976     raeburn  6334: sub is_advanced_user {
                   6335:     my ($udom,$uname) = @_;
1.1085    raeburn  6336:     if ($udom ne '' && $uname ne '') {
                   6337:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6338:             if (wantarray) {
                   6339:                 return ($env{'user.adv'},$env{'user.author'});
                   6340:             } else {
                   6341:                 return $env{'user.adv'};
                   6342:             }
1.1085    raeburn  6343:         }
                   6344:     }
1.976     raeburn  6345:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6346:     my %allroles;
1.1128    raeburn  6347:     my ($is_adv,$is_author);
1.976     raeburn  6348:     foreach my $role (keys(%roleshash)) {
                   6349:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6350:         my $area = '/'.$tdomain.'/'.$trest;
                   6351:         if ($sec ne '') {
                   6352:             $area .= '/'.$sec;
                   6353:         }
                   6354:         if (($area ne '') && ($trole ne '')) {
                   6355:             my $spec=$trole.'.'.$area;
                   6356:             if ($trole =~ /^cr\//) {
                   6357:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6358:             } elsif ($trole ne 'gr') {
                   6359:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6360:             }
1.1128    raeburn  6361:             if ($trole eq 'au') {
                   6362:                 $is_author = 1;
                   6363:             }
1.976     raeburn  6364:         }
                   6365:     }
                   6366:     foreach my $role (keys(%allroles)) {
                   6367:         last if ($is_adv);
                   6368:         foreach my $item (split(/:/,$allroles{$role})) {
                   6369:             if ($item ne '') {
                   6370:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6371:                 if ($privilege eq 'adv') {
                   6372:                     $is_adv = 1;
                   6373:                     last;
                   6374:                 }
                   6375:             }
                   6376:         }
                   6377:     }
1.1128    raeburn  6378:     if (wantarray) {
                   6379:         return ($is_adv,$is_author);
                   6380:     }
1.976     raeburn  6381:     return $is_adv;
                   6382: }
1.798     raeburn  6383: 
1.1035    raeburn  6384: sub check_can_request {
1.1036    raeburn  6385:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6386:     my $canreq = 0;
                   6387:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6388:     my @options = ('approval','validate','autolimit');
                   6389:     my $optregex = join('|',@options);
                   6390:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6391:         foreach my $type (@{$types}) {
                   6392:             if (&usertools_access($env{'user.name'},
                   6393:                                   $env{'user.domain'},
                   6394:                                   $type,undef,'requestcourses')) {
                   6395:                 $canreq ++;
1.1036    raeburn  6396:                 if (ref($request_domains) eq 'HASH') {
                   6397:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6398:                 }
1.1035    raeburn  6399:                 if ($dom eq $env{'user.domain'}) {
                   6400:                     $can_request->{$type} = 1;
                   6401:                 }
                   6402:             }
                   6403:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6404:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6405:                 if (@curr > 0) {
1.1036    raeburn  6406:                     foreach my $item (@curr) {
                   6407:                         if (ref($request_domains) eq 'HASH') {
                   6408:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6409:                             if ($otherdom ne '') {
                   6410:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6411:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6412:                                         push(@{$request_domains->{$type}},$otherdom);
                   6413:                                     }
                   6414:                                 } else {
                   6415:                                     push(@{$request_domains->{$type}},$otherdom);
                   6416:                                 }
                   6417:                             }
                   6418:                         }
                   6419:                     }
                   6420:                     unless($dom eq $env{'user.domain'}) {
                   6421:                         $canreq ++;
1.1035    raeburn  6422:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6423:                             $can_request->{$type} = 1;
                   6424:                         }
                   6425:                     }
                   6426:                 }
                   6427:             }
                   6428:         }
                   6429:     }
                   6430:     return $canreq;
                   6431: }
                   6432: 
1.341     www      6433: # ---------------------------------------------- Custom access rule evaluation
                   6434: 
                   6435: sub customaccess {
                   6436:     my ($priv,$uri)=@_;
1.807     albertel 6437:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6438:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6439:     $udom = &LONCAPA::clean_domain($udom);
                   6440:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6441:     my $access=0;
1.800     albertel 6442:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6443: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6444: 	if ($type eq 'user') {
                   6445: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6446: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6447: 		if ($tdom) {
                   6448: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6449: 		}
1.896     albertel 6450: 		if ($tuname) {
                   6451: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6452: 		}
                   6453: 		$access=($effect eq 'allow');
                   6454: 		last;
                   6455: 	    }
                   6456: 	} else {
                   6457: 	    if ($role) {
                   6458: 		if ($role ne $urole) { next; }
                   6459: 	    }
                   6460: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6461: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6462: 		if ($tdom) {
                   6463: 		    if ($tdom ne $udom) { next; }
                   6464: 		}
                   6465: 		if ($tcrs) {
                   6466: 		    if ($tcrs ne $ucrs) { next; }
                   6467: 		}
                   6468: 		if ($tsec) {
                   6469: 		    if ($tsec ne $usec) { next; }
                   6470: 		}
                   6471: 		$access=($effect eq 'allow');
                   6472: 		last;
                   6473: 	    }
                   6474: 	    if ($realm eq '' && $role eq '') {
                   6475: 		$access=($effect eq 'allow');
                   6476: 	    }
1.402     bowersj2 6477: 	}
1.341     www      6478:     }
                   6479:     return $access;
                   6480: }
                   6481: 
1.103     harris41 6482: # ------------------------------------------------- Check for a user privilege
1.12      www      6483: 
                   6484: sub allowed {
1.810     raeburn  6485:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6486:     my $ver_orguri=$uri;
1.439     www      6487:     $uri=&deversion($uri);
1.152     www      6488:     my $orguri=$uri;
1.52      www      6489:     $uri=&declutter($uri);
1.809     raeburn  6490: 
1.810     raeburn  6491:     if ($priv eq 'evb') {
                   6492: # Evade communication block restrictions for specified role in a course
                   6493:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6494:             return $1;
                   6495:         } else {
                   6496:             return;
                   6497:         }
                   6498:     }
                   6499: 
1.620     albertel 6500:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6501: # Free bre access to adm and meta resources
1.775     albertel 6502:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6503: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6504: 	&& ($priv eq 'bre')) {
1.14      www      6505: 	return 'F';
1.159     www      6506:     }
                   6507: 
1.545     banghart 6508: # Free bre access to user's own portfolio contents
1.714     raeburn  6509:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6510:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6511: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6512:         my %setters;
                   6513:         my ($startblock,$endblock) = 
                   6514:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6515:         if ($startblock && $endblock) {
                   6516:             return 'B';
                   6517:         } else {
                   6518:             return 'F';
                   6519:         }
1.545     banghart 6520:     }
                   6521: 
1.762     raeburn  6522: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6523:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6524:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6525:         if (exists($env{'request.course.id'})) {
                   6526:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6527:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6528:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6529:                 my $courseprivid=$env{'request.course.id'};
                   6530:                 $courseprivid=~s/\_/\//;
                   6531:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6532:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6533:                     return $1; 
1.762     raeburn  6534:                 } else {
                   6535:                     if ($env{'request.course.sec'}) {
                   6536:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6537:                     }
                   6538:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6539:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6540:                         return $2;
                   6541:                     }
1.714     raeburn  6542:                 }
                   6543:             }
                   6544:         }
                   6545:     }
                   6546: 
1.159     www      6547: # Free bre to public access
                   6548: 
                   6549:     if ($priv eq 'bre') {
1.238     www      6550:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6551: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6552:            return 'F'; 
                   6553:         }
1.238     www      6554:         if ($copyright eq 'priv') {
                   6555:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6556: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6557: 		return '';
                   6558:             }
                   6559:         }
                   6560:         if ($copyright eq 'domain') {
                   6561:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6562: 	    unless (($env{'user.domain'} eq $1) ||
                   6563:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6564: 		return '';
                   6565:             }
1.262     matthew  6566:         }
1.620     albertel 6567:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6568:             # Library role, so allow browsing of resources in this domain.
                   6569:             return 'F';
1.238     www      6570:         }
1.341     www      6571:         if ($copyright eq 'custom') {
                   6572: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6573:         }
1.14      www      6574:     }
1.264     matthew  6575:     # Domain coordinator is trying to create a course
1.620     albertel 6576:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6577:         # uri is the requested domain in this case.
                   6578:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6579:         # a role of dc for the domain in question.
1.620     albertel 6580:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6581:     }
1.29      www      6582: 
1.52      www      6583:     my $thisallowed='';
                   6584:     my $statecond=0;
                   6585:     my $courseprivid='';
                   6586: 
1.1039    raeburn  6587:     my $ownaccess;
1.1043    raeburn  6588:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6589:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6590:         if ($uri eq '') {
                   6591:             $ownaccess = 1;
                   6592:         } else {
                   6593:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6594:                 my $udom = $env{'user.domain'};
                   6595:                 my $uname = $env{'user.name'};
                   6596:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6597:                     $ownaccess = 1;
1.1040    raeburn  6598:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6599:                     unless ($uri =~ m{\.\./}) {
                   6600:                         $ownaccess = 1;
                   6601:                     }
                   6602:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6603:                     my $now = time;
                   6604:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6605:                         my $adom = $1;
                   6606:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6607:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6608:                                 my ($start,$end) = split('.',$env{$key});
                   6609:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6610:                                     $ownaccess = 1;
                   6611:                                     last;
                   6612:                                 }
                   6613:                             }
                   6614:                         }
                   6615:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6616:                         my $adom = $1;
                   6617:                         my $aname = $2;
1.1042    raeburn  6618:                         foreach my $role ('ca','aa') { 
                   6619:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6620:                                 my ($start,$end) =
                   6621:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6622:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6623:                                     $ownaccess = 1;
                   6624:                                     last;
                   6625:                                 }
1.1039    raeburn  6626:                             }
                   6627:                         }
                   6628:                     }
                   6629:                 }
                   6630:             }
                   6631:         }
                   6632:     }
                   6633: 
1.52      www      6634: # Course
                   6635: 
1.620     albertel 6636:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6637:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6638:             $thisallowed.=$1;
                   6639:         }
1.52      www      6640:     }
1.29      www      6641: 
1.52      www      6642: # Domain
                   6643: 
1.620     albertel 6644:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6645:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6646:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6647:             $thisallowed.=$1;
                   6648:         }
1.12      www      6649:     }
1.52      www      6650: 
1.1141    raeburn  6651: # User who is not author or co-author might still be able to edit
                   6652: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6653:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6654:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6655:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6656:             $thisallowed.=$1;
                   6657:         }
                   6658:     }
                   6659: 
1.52      www      6660: # Course: uri itself is a course
1.66      www      6661:     my $courseuri=$uri;
                   6662:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6663:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6664: 
1.620     albertel 6665:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6666:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6667:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6668:             $thisallowed.=$1;
                   6669:         }
1.12      www      6670:     }
1.29      www      6671: 
1.665     albertel 6672: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6673: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6674:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6675: 	$thisallowed='';
1.671     raeburn  6676:         my ($match)=&is_on_map($uri);
                   6677:         if ($match) {
                   6678:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6679:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6680:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6681:                 if (@blockers > 0) {
                   6682:                     $thisallowed = 'B';
                   6683:                 } else {
                   6684:                     $thisallowed.=$1;
                   6685:                 }
1.671     raeburn  6686:             }
                   6687:         } else {
1.705     albertel 6688:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6689:             if ($refuri) {
                   6690:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6691:                     $thisallowed='F';
1.671     raeburn  6692:                 } else {
                   6693:                     $refuri=&declutter($refuri);
                   6694:                     my ($match) = &is_on_map($refuri);
                   6695:                     if ($match) {
1.1162    raeburn  6696:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6697:                         if (@blockers > 0) {
                   6698:                             $thisallowed = 'B';
                   6699:                         } else {
                   6700:                             $thisallowed='F';
                   6701:                         }
1.671     raeburn  6702:                     }
1.669     raeburn  6703:                 }
1.671     raeburn  6704:             }
                   6705:         }
1.314     www      6706:     }
1.492     albertel 6707: 
1.766     albertel 6708:     if ($priv eq 'bre'
                   6709: 	&& $thisallowed ne 'F' 
                   6710: 	&& $thisallowed ne '2'
                   6711: 	&& &is_portfolio_url($uri)) {
                   6712: 	$thisallowed = &portfolio_access($uri);
                   6713:     }
                   6714:     
1.52      www      6715: # Full access at system, domain or course-wide level? Exit.
1.29      www      6716:     if ($thisallowed=~/F/) {
                   6717: 	return 'F';
                   6718:     }
                   6719: 
1.52      www      6720: # If this is generating or modifying users, exit with special codes
1.29      www      6721: 
1.643     www      6722:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6723: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6724: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6725: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6726: 	    unless ($auname) { return $thisallowed; }
                   6727: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6728: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6729: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6730: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6731: 	}
1.52      www      6732: 	return $thisallowed;
                   6733:     }
                   6734: #
1.103     harris41 6735: # Gathered so far: system, domain and course wide privileges
1.52      www      6736: #
                   6737: # Course: See if uri or referer is an individual resource that is part of 
                   6738: # the course
                   6739: 
1.620     albertel 6740:     if ($env{'request.course.id'}) {
1.232     www      6741: 
1.620     albertel 6742:        $courseprivid=$env{'request.course.id'};
                   6743:        if ($env{'request.course.sec'}) {
                   6744:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6745:        }
                   6746:        $courseprivid=~s/\_/\//;
                   6747:        my $checkreferer=1;
1.232     www      6748:        my ($match,$cond)=&is_on_map($uri);
                   6749:        if ($match) {
                   6750:            $statecond=$cond;
1.620     albertel 6751:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6752:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6753:                my $value = $1;
                   6754:                if ($priv eq 'bre') {
                   6755:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6756:                    if (@blockers > 0) {
                   6757:                        $thisallowed = 'B';
                   6758:                    } else {
                   6759:                        $thisallowed.=$value;
                   6760:                    }
                   6761:                } else {
                   6762:                    $thisallowed.=$value;
                   6763:                }
1.52      www      6764:                $checkreferer=0;
                   6765:            }
1.29      www      6766:        }
1.83      www      6767:        
1.148     www      6768:        if ($checkreferer) {
1.620     albertel 6769: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6770:             unless ($refuri) {
1.800     albertel 6771:                 foreach my $key (keys(%env)) {
                   6772: 		    if ($key=~/^httpref\..*\*/) {
                   6773: 			my $pattern=$key;
1.156     www      6774:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6775:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6776:                         $pattern=~s/\//\\\//g;
1.152     www      6777:                         if ($orguri=~/$pattern/) {
1.800     albertel 6778: 			    $refuri=$env{$key};
1.148     www      6779:                         }
                   6780:                     }
1.191     harris41 6781:                 }
1.148     www      6782:             }
1.232     www      6783: 
1.148     www      6784:          if ($refuri) { 
1.152     www      6785: 	  $refuri=&declutter($refuri);
1.232     www      6786:           my ($match,$cond)=&is_on_map($refuri);
                   6787:             if ($match) {
                   6788:               my $refstatecond=$cond;
1.620     albertel 6789:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6790:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6791:                   my $value = $1;
                   6792:                   if ($priv eq 'bre') {
                   6793:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6794:                       if (@blockers > 0) {
                   6795:                           $thisallowed = 'B';
                   6796:                       } else {
                   6797:                           $thisallowed.=$value;
                   6798:                       }
                   6799:                   } else {
                   6800:                       $thisallowed.=$value;
                   6801:                   }
1.53      www      6802:                   $uri=$refuri;
                   6803:                   $statecond=$refstatecond;
1.52      www      6804:               }
                   6805:           }
1.148     www      6806:         }
1.29      www      6807:        }
1.52      www      6808:    }
1.29      www      6809: 
1.52      www      6810: #
1.103     harris41 6811: # Gathered now: all privileges that could apply, and condition number
1.52      www      6812: # 
                   6813: #
                   6814: # Full or no access?
                   6815: #
1.29      www      6816: 
1.52      www      6817:     if ($thisallowed=~/F/) {
                   6818: 	return 'F';
                   6819:     }
1.29      www      6820: 
1.52      www      6821:     unless ($thisallowed) {
                   6822:         return '';
                   6823:     }
1.29      www      6824: 
1.52      www      6825: # Restrictions exist, deal with them
                   6826: #
                   6827: #   C:according to course preferences
                   6828: #   R:according to resource settings
                   6829: #   L:unless locked
                   6830: #   X:according to user session state
                   6831: #
                   6832: 
                   6833: # Possibly locked functionality, check all courses
1.54      www      6834: # Locks might take effect only after 10 minutes cache expiration for other
                   6835: # courses, and 2 minutes for current course
1.52      www      6836: 
                   6837:     my $envkey;
                   6838:     if ($thisallowed=~/L/) {
1.1000    raeburn  6839:         foreach $envkey (keys(%env)) {
1.54      www      6840:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6841:                my $courseid=$2;
                   6842:                my $roleid=$1.'.'.$2;
1.92      www      6843:                $courseid=~s/^\///;
1.54      www      6844:                my $expiretime=600;
1.620     albertel 6845:                if ($env{'request.role'} eq $roleid) {
1.54      www      6846: 		  $expiretime=120;
                   6847:                }
                   6848: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6849:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6850:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6851: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6852:                }
1.620     albertel 6853:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6854:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6855: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6856:                        &log($env{'user.domain'},$env{'user.name'},
                   6857:                             $env{'user.home'},
1.57      www      6858:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6859:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6860:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6861: 		       return '';
                   6862:                    }
                   6863:                }
1.620     albertel 6864:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6865:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6866: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6867:                        &log($env{'user.domain'},$env{'user.name'},
                   6868:                             $env{'user.home'},
1.57      www      6869:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6870:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6871:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6872: 		       return '';
                   6873:                    }
                   6874:                }
                   6875: 	   }
1.29      www      6876:        }
1.52      www      6877:     }
                   6878:    
                   6879: #
                   6880: # Rest of the restrictions depend on selected course
                   6881: #
                   6882: 
1.620     albertel 6883:     unless ($env{'request.course.id'}) {
1.766     albertel 6884: 	if ($thisallowed eq 'A') {
                   6885: 	    return 'A';
1.814     raeburn  6886:         } elsif ($thisallowed eq 'B') {
                   6887:             return 'B';
1.766     albertel 6888: 	} else {
                   6889: 	    return '1';
                   6890: 	}
1.52      www      6891:     }
1.29      www      6892: 
1.52      www      6893: #
                   6894: # Now user is definitely in a course
                   6895: #
1.53      www      6896: 
                   6897: 
                   6898: # Course preferences
                   6899: 
                   6900:    if ($thisallowed=~/C/) {
1.620     albertel 6901:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6902:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6903:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6904: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6905: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6906: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6907: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6908: 			$env{'request.course.id'});
                   6909: 	   }
1.237     www      6910:            return '';
                   6911:        }
                   6912: 
1.620     albertel 6913:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6914: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6915: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6916: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6917: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6918: 			$env{'request.course.id'});
                   6919: 	   }
1.54      www      6920:            return '';
                   6921:        }
1.53      www      6922:    }
                   6923: 
                   6924: # Resource preferences
                   6925: 
                   6926:    if ($thisallowed=~/R/) {
1.620     albertel 6927:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6928:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6929: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6930: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6931: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6932: 	   }
                   6933: 	   return '';
1.54      www      6934:        }
1.53      www      6935:    }
1.30      www      6936: 
1.246     www      6937: # Restricted by state or randomout?
1.30      www      6938: 
1.52      www      6939:    if ($thisallowed=~/X/) {
1.620     albertel 6940:       if ($env{'acc.randomout'}) {
1.579     albertel 6941: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6942:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6943:             return ''; 
                   6944:          }
1.247     www      6945:       }
                   6946:       if (&condval($statecond)) {
1.52      www      6947: 	 return '2';
                   6948:       } else {
                   6949:          return '';
                   6950:       }
                   6951:    }
1.30      www      6952: 
1.766     albertel 6953:     if ($thisallowed eq 'A') {
                   6954: 	return 'A';
1.814     raeburn  6955:     } elsif ($thisallowed eq 'B') {
                   6956:         return 'B';
1.766     albertel 6957:     }
1.52      www      6958:    return 'F';
1.232     www      6959: }
1.1162    raeburn  6960: 
1.1192    raeburn  6961: # ------------------------------------------- Check construction space access
                   6962: 
                   6963: sub constructaccess {
                   6964:     my ($url,$setpriv)=@_;
                   6965: 
                   6966: # We do not allow editing of previous versions of files
                   6967:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6968: 
                   6969: # Get username and domain from URL
                   6970:     my ($ownername,$ownerdomain,$ownerhome);
                   6971: 
                   6972:     ($ownerdomain,$ownername) =
                   6973:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6974: 
                   6975: # The URL does not really point to any authorspace, forget it
                   6976:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6977: 
                   6978: # Now we need to see if the user has access to the authorspace of
                   6979: # $ownername at $ownerdomain
                   6980: 
                   6981:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6982: # Real author for this?
                   6983:        $ownerhome = $env{'user.home'};
                   6984:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6985:           return ($ownername,$ownerdomain,$ownerhome);
                   6986:        }
                   6987:     } else {
                   6988: # Co-author for this?
                   6989:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6990:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6991:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6992:             return ($ownername,$ownerdomain,$ownerhome);
                   6993:         }
                   6994:     }
                   6995: 
                   6996: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6997: # we might as well leave
                   6998:    unless ($setpriv) { return ''; }
                   6999: 
                   7000: # Backdoor access?
                   7001:     my $allowed=&allowed('eco',$ownerdomain);
                   7002: # Nope
                   7003:     unless ($allowed) { return ''; }
                   7004: # Looks like we may have access, but could be locked by the owner of the construction space
                   7005:     if ($allowed eq 'U') {
                   7006:         my %blocked=&get('environment',['domcoord.author'],
                   7007:                          $ownerdomain,$ownername);
                   7008: # Is blocked by owner
                   7009:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7010:     }
                   7011:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7012: # Grant temporary access
                   7013:         my $then=$env{'user.login.time'};
1.1209    raeburn  7014:         my $update=$env{'user.update.time'};
1.1192    raeburn  7015:         if (!$update) { $update = $then; }
                   7016:         my $refresh=$env{'user.refresh.time'};
                   7017:         if (!$refresh) { $refresh = $update; }
                   7018:         my $now = time;
                   7019:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7020:                            $now,'ca','constructaccess');
                   7021:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7022:         return($ownername,$ownerdomain,$ownerhome);
                   7023:     }
                   7024: # No business here
                   7025:     return '';
                   7026: }
                   7027: 
1.1162    raeburn  7028: sub get_comm_blocks {
                   7029:     my ($cdom,$cnum) = @_;
                   7030:     if ($cdom eq '' || $cnum eq '') {
                   7031:         return unless ($env{'request.course.id'});
                   7032:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7033:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7034:     }
                   7035:     my %commblocks;
                   7036:     my $hashid=$cdom.'_'.$cnum;
                   7037:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7038:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7039:         %commblocks = %{$blocksref};
                   7040:     } else {
                   7041:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7042:         my $cachetime = 600;
                   7043:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7044:     }
                   7045:     return %commblocks;
                   7046: }
                   7047: 
                   7048: sub has_comm_blocking {
                   7049:     my ($priv,$symb,$uri,$blocks) = @_;
                   7050:     return unless ($env{'request.course.id'});
                   7051:     return unless ($priv eq 'bre');
                   7052:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7053:     my %commblocks;
                   7054:     if (ref($blocks) eq 'HASH') {
                   7055:         %commblocks = %{$blocks};
                   7056:     } else {
                   7057:         %commblocks = &get_comm_blocks();
                   7058:     }
                   7059:     return unless (keys(%commblocks) > 0);
                   7060:     if (!$symb) { $symb=&symbread($uri,1); }
                   7061:     my ($map,$resid,undef)=&decode_symb($symb);
                   7062:     my %tocheck = (
                   7063:                     maps      => $map,
                   7064:                     resources => $symb,
                   7065:                   );
                   7066:     my @blockers;
                   7067:     my $now = time;
1.1163    raeburn  7068:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7069:     foreach my $block (keys(%commblocks)) {
                   7070:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7071:             my ($start,$end) = ($1,$2);
                   7072:             if ($start <= $now && $end >= $now) {
                   7073:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7074:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7075:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7076:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7077:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7078:                                     push(@blockers,$block);
                   7079:                                 }
                   7080:                             }
                   7081:                         }
                   7082:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7083:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7084:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7085:                                     push(@blockers,$block);
                   7086:                                 }
                   7087:                             }
                   7088:                         }
                   7089:                     }
                   7090:                 }
                   7091:             }
                   7092:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7093:             my $item = $1;
1.1163    raeburn  7094:             my @to_test;
1.1162    raeburn  7095:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7096:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7097:                     my $check_interval;
                   7098:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7099:                         my @interval;
                   7100:                         my $type = 'map';
                   7101:                         if ($item eq 'course') {
                   7102:                             $type = 'course';
                   7103:                             @interval=&EXT("resource.0.interval");
                   7104:                         } else {
                   7105:                             if ($item =~ /___\d+___/) {
                   7106:                                 $type = 'resource';
                   7107:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7108:                                 if (ref($navmap)) {                        
                   7109:                                     my $res = $navmap->getBySymb($item); 
                   7110:                                     push(@to_test,$res);
                   7111:                                 }
1.1162    raeburn  7112:                             } else {
                   7113:                                 my $mapsymb = &symbread($item,1);
                   7114:                                 if ($mapsymb) {
                   7115:                                     if (ref($navmap)) {
                   7116:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7117:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7118:                                         foreach my $res (@to_test) {
1.1162    raeburn  7119:                                             my $symb = $res->symb();
                   7120:                                             next if ($symb eq $mapsymb);
                   7121:                                             if ($symb ne '') {
                   7122:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7123:                                                 last;
                   7124:                                             }
                   7125:                                         }
                   7126:                                     }
                   7127:                                 }
                   7128:                             }
                   7129:                         }
                   7130:                         if ($interval[0] =~ /\d+/) {
                   7131:                             my $first_access;
                   7132:                             if ($type eq 'resource') {
                   7133:                                 $first_access=&get_first_access($interval[1],$item);
                   7134:                             } elsif ($type eq 'map') {
                   7135:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7136:                             } else {
                   7137:                                 $first_access=&get_first_access($interval[1]);
                   7138:                             }
                   7139:                             if ($first_access) {
                   7140:                                 my $timesup = $first_access+$interval[0];
                   7141:                                 if ($timesup > $now) {
1.1163    raeburn  7142:                                     foreach my $res (@to_test) {
                   7143:                                         if ($res->is_problem()) {
                   7144:                                             if ($res->completable()) {
                   7145:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7146:                                                     push(@blockers,$block);
                   7147:                                                 }
                   7148:                                                 last;
                   7149:                                             }
                   7150:                                         }
1.1162    raeburn  7151:                                     }
                   7152:                                 }
                   7153:                             }
                   7154:                         }
                   7155:                     }
                   7156:                 }
                   7157:             }
                   7158:         }
                   7159:     }
                   7160:     return @blockers;
                   7161: }
                   7162: 
                   7163: sub check_docs_block {
                   7164:     my ($docsblock,$tocheck) =@_;
                   7165:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7166:         return;
                   7167:     }
                   7168:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7169:         if ($tocheck->{'maps'}) {
                   7170:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7171:                 return 1;
                   7172:             }
                   7173:         }
                   7174:     }
                   7175:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7176:         if ($tocheck->{'resources'}) {
                   7177:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7178:                 return 1;
                   7179:             }
                   7180:         }
                   7181:     }
                   7182:     return;
                   7183: }
                   7184: 
1.1133    foxr     7185: #
                   7186: #   Removes the versino from a URI and
                   7187: #   splits it in to its filename and path to the filename.
                   7188: #   Seems like File::Basename could have done this more clearly.
                   7189: #   Parameters:
                   7190: #      $uri   - input URI
                   7191: #   Returns:
                   7192: #     Two element list consisting of 
                   7193: #     $pathname  - the URI up to and excluding the trailing /
                   7194: #     $filename  - The part of the URI following the last /
                   7195: #  NOTE:
                   7196: #    Another realization of this is simply:
                   7197: #    use File::Basename;
                   7198: #    ...
                   7199: #    $uri = shift;
                   7200: #    $filename = basename($uri);
                   7201: #    $path     = dirname($uri);
                   7202: #    return ($filename, $path);
                   7203: #
                   7204: #     The implementation below is probably faster however.
                   7205: #
1.710     albertel 7206: sub split_uri_for_cond {
                   7207:     my $uri=&deversion(&declutter(shift));
                   7208:     my @uriparts=split(/\//,$uri);
                   7209:     my $filename=pop(@uriparts);
                   7210:     my $pathname=join('/',@uriparts);
                   7211:     return ($pathname,$filename);
                   7212: }
1.232     www      7213: # --------------------------------------------------- Is a resource on the map?
                   7214: 
                   7215: sub is_on_map {
1.710     albertel 7216:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7217:     #Trying to find the conditional for the file
1.620     albertel 7218:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7219: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7220:     if ($match) {
1.289     bowersj2 7221: 	return (1,$1);
                   7222:     } else {
1.434     www      7223: 	return (0,0);
1.289     bowersj2 7224:     }
1.12      www      7225: }
                   7226: 
1.427     www      7227: # --------------------------------------------------------- Get symb from alias
                   7228: 
                   7229: sub get_symb_from_alias {
                   7230:     my $symb=shift;
                   7231:     my ($map,$resid,$url)=&decode_symb($symb);
                   7232: # Already is a symb
                   7233:     if ($url) { return $symb; }
                   7234: # Must be an alias
                   7235:     my $aliassymb='';
                   7236:     my %bighash;
1.620     albertel 7237:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7238:                             &GDBM_READER(),0640)) {
                   7239:         my $rid=$bighash{'mapalias_'.$symb};
                   7240: 	if ($rid) {
                   7241: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7242: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7243: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7244: 	}
                   7245:         untie %bighash;
                   7246:     }
                   7247:     return $aliassymb;
                   7248: }
                   7249: 
1.12      www      7250: # ----------------------------------------------------------------- Define Role
                   7251: 
                   7252: sub definerole {
                   7253:   if (allowed('mcr','/')) {
                   7254:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7255:     foreach my $role (split(':',$sysrole)) {
                   7256: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7257:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7258:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7259: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7260:                return "refused:s:$crole&$cqual"; 
                   7261:             }
                   7262:         }
1.191     harris41 7263:     }
1.800     albertel 7264:     foreach my $role (split(':',$domrole)) {
                   7265: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7266:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7267:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7268: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7269:                return "refused:d:$crole&$cqual"; 
                   7270:             }
                   7271:         }
1.191     harris41 7272:     }
1.800     albertel 7273:     foreach my $role (split(':',$courole)) {
                   7274: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7275:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7276:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7277: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7278:                return "refused:c:$crole&$cqual"; 
                   7279:             }
                   7280:         }
1.191     harris41 7281:     }
1.620     albertel 7282:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7283:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7284: 	        "rolesdef_$rolename=".
                   7285:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7286:     return reply($command,$env{'user.home'});
1.12      www      7287:   } else {
                   7288:     return 'refused';
                   7289:   }
1.105     harris41 7290: }
                   7291: 
                   7292: # ---------------- Make a metadata query against the network of library servers
                   7293: 
                   7294: sub metadata_query {
1.1237    raeburn  7295:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7296:     my %rhash;
1.845     albertel 7297:     my %libserv = &all_library();
1.244     matthew  7298:     my @server_list = (defined($server_array) ? @$server_array
                   7299:                                               : keys(%libserv) );
                   7300:     for my $server (@server_list) {
1.1237    raeburn  7301:         my $domains = ''; 
                   7302:         if (ref($domains_hash) eq 'HASH') {
                   7303:             $domains = $domains_hash->{$server}; 
                   7304:         }
1.118     harris41 7305: 	unless ($custom or $customshow) {
1.1237    raeburn  7306: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7307: 	    $rhash{$server}=$reply;
                   7308: 	}
                   7309: 	else {
                   7310: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7311: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7312: 			     $server);
                   7313: 	    $rhash{$server}=$reply;
                   7314: 	}
1.112     harris41 7315:     }
1.118     harris41 7316:     return \%rhash;
1.240     www      7317: }
                   7318: 
                   7319: # ----------------------------------------- Send log queries and wait for reply
                   7320: 
                   7321: sub log_query {
                   7322:     my ($uname,$udom,$query,%filters)=@_;
                   7323:     my $uhome=&homeserver($uname,$udom);
                   7324:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7325:     my $uhost=&hostname($uhome);
1.800     albertel 7326:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7327:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7328:                        $uhome);
1.479     albertel 7329:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7330:     return get_query_reply($queryid);
                   7331: }
                   7332: 
1.818     raeburn  7333: # -------------------------- Update MySQL table for portfolio file
                   7334: 
                   7335: sub update_portfolio_table {
1.821     raeburn  7336:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7337:     if ($group ne '') {
                   7338:         $file_name =~s /^\Q$group\E//;
                   7339:     }
1.818     raeburn  7340:     my $homeserver = &homeserver($uname,$udom);
                   7341:     my $queryid=
1.821     raeburn  7342:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7343:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7344:     my $reply = &get_query_reply($queryid);
                   7345:     return $reply;
                   7346: }
                   7347: 
1.899     raeburn  7348: # -------------------------- Update MySQL allusers table
                   7349: 
                   7350: sub update_allusers_table {
                   7351:     my ($uname,$udom,$names) = @_;
                   7352:     my $homeserver = &homeserver($uname,$udom);
                   7353:     my $queryid=
                   7354:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7355:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7356:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7357:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7358:                'generation='.&escape($names->{'generation'}).'%%'.
                   7359:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7360:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7361:     return;
1.899     raeburn  7362: }
                   7363: 
1.508     raeburn  7364: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7365: 
                   7366: sub fetch_enrollment_query {
1.511     raeburn  7367:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7368:     my $homeserver;
1.547     raeburn  7369:     my $maxtries = 1;
1.508     raeburn  7370:     if ($context eq 'automated') {
                   7371:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7372:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7373:     } else {
                   7374:         $homeserver = &homeserver($cnum,$dom);
                   7375:     }
1.838     albertel 7376:     my $host=&hostname($homeserver);
1.506     raeburn  7377:     my $cmd = '';
1.1000    raeburn  7378:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7379:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7380:     }
                   7381:     $cmd =~ s/%%$//;
                   7382:     $cmd = &escape($cmd);
                   7383:     my $query = 'fetchenrollment';
1.620     albertel 7384:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7385:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7386:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7387:         return 'error: '.$queryid;
                   7388:     }
1.506     raeburn  7389:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7390:     my $tries = 1;
                   7391:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7392:         $reply = &get_query_reply($queryid);
                   7393:         $tries ++;
                   7394:     }
1.526     raeburn  7395:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7396:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7397:     } else {
1.901     albertel 7398:         my @responses = split(/:/,$reply);
1.515     raeburn  7399:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7400:             foreach my $line (@responses) {
                   7401:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7402:                 $$replyref{$key} = $value;
                   7403:             }
                   7404:         } else {
1.1117    foxr     7405:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7406:             foreach my $line (@responses) {
                   7407:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7408:                 $$replyref{$key} = $value;
                   7409:                 if ($value > 0) {
1.800     albertel 7410:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7411:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7412:                         my $destname = $pathname.'/'.$filename;
                   7413:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7414:                         if ($xml_classlist =~ /^error/) {
                   7415:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7416:                         } else {
1.506     raeburn  7417:                             if ( open(FILE,">$destname") ) {
                   7418:                                 print FILE &unescape($xml_classlist);
                   7419:                                 close(FILE);
1.526     raeburn  7420:                             } else {
                   7421:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7422:                             }
                   7423:                         }
                   7424:                     }
                   7425:                 }
                   7426:             }
                   7427:         }
                   7428:         return 'ok';
                   7429:     }
                   7430:     return 'error';
                   7431: }
                   7432: 
1.242     www      7433: sub get_query_reply {
                   7434:     my $queryid=shift;
1.1117    foxr     7435:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7436:     my $reply='';
                   7437:     for (1..100) {
                   7438: 	sleep 2;
                   7439:         if (-e $replyfile.'.end') {
1.448     albertel 7440: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7441: 		$reply = join('',<$fh>);
                   7442: 		close($fh);
1.240     www      7443: 	   } else { return 'error: reply_file_error'; }
1.242     www      7444:            return &unescape($reply);
                   7445: 	}
1.240     www      7446:     }
1.242     www      7447:     return 'timeout:'.$queryid;
1.240     www      7448: }
                   7449: 
                   7450: sub courselog_query {
1.241     www      7451: #
                   7452: # possible filters:
                   7453: # url: url or symb
                   7454: # username
                   7455: # domain
                   7456: # action: view, submit, grade
                   7457: # start: timestamp
                   7458: # end: timestamp
                   7459: #
1.240     www      7460:     my (%filters)=@_;
1.620     albertel 7461:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7462:     if ($filters{'url'}) {
                   7463: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7464:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7465:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7466:     }
1.620     albertel 7467:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7468:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7469:     return &log_query($cname,$cdom,'courselog',%filters);
                   7470: }
                   7471: 
                   7472: sub userlog_query {
1.858     raeburn  7473: #
                   7474: # possible filters:
                   7475: # action: log check role
                   7476: # start: timestamp
                   7477: # end: timestamp
                   7478: #
1.240     www      7479:     my ($uname,$udom,%filters)=@_;
                   7480:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7481: }
                   7482: 
1.506     raeburn  7483: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7484: 
                   7485: sub auto_run {
1.508     raeburn  7486:     my ($cnum,$cdom) = @_;
1.876     raeburn  7487:     my $response = 0;
                   7488:     my $settings;
                   7489:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7490:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7491:         $settings = $domconfig{'autoenroll'};
                   7492:         if ($settings->{'run'} eq '1') {
                   7493:             $response = 1;
                   7494:         }
                   7495:     } else {
1.934     raeburn  7496:         my $homeserver;
                   7497:         if (&is_course($cdom,$cnum)) {
                   7498:             $homeserver = &homeserver($cnum,$cdom);
                   7499:         } else {
                   7500:             $homeserver = &domain($cdom,'primary');
                   7501:         }
                   7502:         if ($homeserver ne 'no_host') {
                   7503:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7504:         }
1.876     raeburn  7505:     }
1.506     raeburn  7506:     return $response;
                   7507: }
1.776     albertel 7508: 
1.506     raeburn  7509: sub auto_get_sections {
1.508     raeburn  7510:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7511:     my $homeserver;
                   7512:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7513:         $homeserver = &homeserver($cnum,$cdom);
                   7514:     }
                   7515:     if (!defined($homeserver)) { 
                   7516:         if ($cdom =~ /^$match_domain$/) {
                   7517:             $homeserver = &domain($cdom,'primary');
                   7518:         }
                   7519:     }
                   7520:     my @secs;
                   7521:     if (defined($homeserver)) {
                   7522:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7523:         unless ($response eq 'refused') {
                   7524:             @secs = split(/:/,$response);
                   7525:         }
1.506     raeburn  7526:     }
                   7527:     return @secs;
                   7528: }
1.776     albertel 7529: 
1.506     raeburn  7530: sub auto_new_course {
1.1099    raeburn  7531:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7532:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7533:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7534:     return $response;
                   7535: }
1.776     albertel 7536: 
1.506     raeburn  7537: sub auto_validate_courseID {
1.508     raeburn  7538:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7539:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7540:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7541:     return $response;
                   7542: }
1.776     albertel 7543: 
1.1007    raeburn  7544: sub auto_validate_instcode {
1.1020    raeburn  7545:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7546:     my ($homeserver,$response);
                   7547:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7548:         $homeserver = &homeserver($cnum,$cdom);
                   7549:     }
                   7550:     if (!defined($homeserver)) {
                   7551:         if ($cdom =~ /^$match_domain$/) {
                   7552:             $homeserver = &domain($cdom,'primary');
                   7553:         }
                   7554:     }
1.1065    raeburn  7555:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7556:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7557:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7558:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7559: }
                   7560: 
1.506     raeburn  7561: sub auto_create_password {
1.873     raeburn  7562:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7563:     my ($homeserver,$response);
1.506     raeburn  7564:     my $create_passwd = 0;
                   7565:     my $authchk = '';
1.873     raeburn  7566:     if ($udom =~ /^$match_domain$/) {
                   7567:         $homeserver = &domain($udom,'primary');
                   7568:     }
                   7569:     if ($homeserver eq '') {
                   7570:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7571:             $homeserver = &homeserver($cnum,$cdom);
                   7572:         }
                   7573:     }
                   7574:     if ($homeserver eq '') {
                   7575:         $authchk = 'nodomain';
1.506     raeburn  7576:     } else {
1.873     raeburn  7577:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7578:         if ($response eq 'refused') {
                   7579:             $authchk = 'refused';
                   7580:         } else {
1.901     albertel 7581:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7582:         }
1.506     raeburn  7583:     }
                   7584:     return ($authparam,$create_passwd,$authchk);
                   7585: }
                   7586: 
1.706     raeburn  7587: sub auto_photo_permission {
                   7588:     my ($cnum,$cdom,$students) = @_;
                   7589:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7590:     my ($outcome,$perm_reqd,$conditions) = 
                   7591: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7592:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7593: 	return (undef,undef);
                   7594:     }
1.706     raeburn  7595:     return ($outcome,$perm_reqd,$conditions);
                   7596: }
                   7597: 
                   7598: sub auto_checkphotos {
                   7599:     my ($uname,$udom,$pid) = @_;
                   7600:     my $homeserver = &homeserver($uname,$udom);
                   7601:     my ($result,$resulttype);
                   7602:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7603: 				   &escape($uname).':'.&escape($pid),
                   7604: 				   $homeserver));
1.709     albertel 7605:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7606: 	return (undef,undef);
                   7607:     }
1.706     raeburn  7608:     if ($outcome) {
                   7609:         ($result,$resulttype) = split(/:/,$outcome);
                   7610:     } 
                   7611:     return ($result,$resulttype);
                   7612: }
                   7613: 
                   7614: sub auto_photochoice {
                   7615:     my ($cnum,$cdom) = @_;
                   7616:     my $homeserver = &homeserver($cnum,$cdom);
                   7617:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7618: 						       &escape($cdom),
                   7619: 						       $homeserver)));
1.709     albertel 7620:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7621: 	return (undef,undef);
                   7622:     }
1.706     raeburn  7623:     return ($update,$comment);
                   7624: }
                   7625: 
                   7626: sub auto_photoupdate {
                   7627:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7628:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7629:     my $host=&hostname($homeserver);
1.706     raeburn  7630:     my $cmd = '';
                   7631:     my $maxtries = 1;
1.800     albertel 7632:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7633:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7634:     }
                   7635:     $cmd =~ s/%%$//;
                   7636:     $cmd = &escape($cmd);
                   7637:     my $query = 'institutionalphotos';
                   7638:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7639:     unless ($queryid=~/^\Q$host\E\_/) {
                   7640:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7641:         return 'error: '.$queryid;
                   7642:     }
                   7643:     my $reply = &get_query_reply($queryid);
                   7644:     my $tries = 1;
                   7645:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7646:         $reply = &get_query_reply($queryid);
                   7647:         $tries ++;
                   7648:     }
                   7649:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7650:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7651:     } else {
                   7652:         my @responses = split(/:/,$reply);
                   7653:         my $outcome = shift(@responses); 
                   7654:         foreach my $item (@responses) {
                   7655:             my ($key,$value) = split(/=/,$item);
                   7656:             $$photo{$key} = $value;
                   7657:         }
                   7658:         return $outcome;
                   7659:     }
                   7660:     return 'error';
                   7661: }
                   7662: 
1.521     raeburn  7663: sub auto_instcode_format {
1.793     albertel 7664:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7665: 	$cat_order) = @_;
1.521     raeburn  7666:     my $courses = '';
1.772     raeburn  7667:     my @homeservers;
1.521     raeburn  7668:     if ($caller eq 'global') {
1.841     albertel 7669: 	my %servers = &get_servers($codedom,'library');
                   7670: 	foreach my $tryserver (keys(%servers)) {
                   7671: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7672: 		push(@homeservers,$tryserver);
                   7673: 	    }
1.584     raeburn  7674:         }
1.1022    raeburn  7675:     } elsif ($caller eq 'requests') {
                   7676:         if ($codedom =~ /^$match_domain$/) {
                   7677:             my $chome = &domain($codedom,'primary');
                   7678:             unless ($chome eq 'no_host') {
                   7679:                 push(@homeservers,$chome);
                   7680:             }
                   7681:         }
1.521     raeburn  7682:     } else {
1.772     raeburn  7683:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7684:     }
1.793     albertel 7685:     foreach my $code (keys(%{$instcodes})) {
                   7686:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7687:     }
                   7688:     chop($courses);
1.772     raeburn  7689:     my $ok_response = 0;
                   7690:     my $response;
                   7691:     while (@homeservers > 0 && $ok_response == 0) {
                   7692:         my $server = shift(@homeservers); 
                   7693:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7694:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7695:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7696: 		split(/:/,$response);
1.772     raeburn  7697:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7698:             push(@{$codetitles},&str2array($codetitles_str));
                   7699:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7700:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7701:             $ok_response = 1;
                   7702:         }
                   7703:     }
                   7704:     if ($ok_response) {
1.521     raeburn  7705:         return 'ok';
1.772     raeburn  7706:     } else {
                   7707:         return $response;
1.521     raeburn  7708:     }
                   7709: }
                   7710: 
1.792     raeburn  7711: sub auto_instcode_defaults {
                   7712:     my ($domain,$returnhash,$code_order) = @_;
                   7713:     my @homeservers;
1.841     albertel 7714: 
                   7715:     my %servers = &get_servers($domain,'library');
                   7716:     foreach my $tryserver (keys(%servers)) {
                   7717: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7718: 	    push(@homeservers,$tryserver);
                   7719: 	}
1.792     raeburn  7720:     }
1.841     albertel 7721: 
1.792     raeburn  7722:     my $response;
1.841     albertel 7723:     foreach my $server (@homeservers) {
1.792     raeburn  7724:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7725:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7726: 	
                   7727: 	foreach my $pair (split(/\&/,$response)) {
                   7728: 	    my ($name,$value)=split(/\=/,$pair);
                   7729: 	    if ($name eq 'code_order') {
                   7730: 		@{$code_order} = split(/\&/,&unescape($value));
                   7731: 	    } else {
                   7732: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7733: 	    }
                   7734: 	}
                   7735: 	return 'ok';
1.792     raeburn  7736:     }
1.841     albertel 7737: 
                   7738:     return $response;
1.1003    raeburn  7739: }
                   7740: 
                   7741: sub auto_possible_instcodes {
1.1007    raeburn  7742:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7743:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7744:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7745:         return;
                   7746:     }
1.1003    raeburn  7747:     my (@homeservers,$uhome);
                   7748:     if (defined(&domain($domain,'primary'))) {
                   7749:         $uhome=&domain($domain,'primary');
                   7750:         push(@homeservers,&domain($domain,'primary'));
                   7751:     } else {
                   7752:         my %servers = &get_servers($domain,'library');
                   7753:         foreach my $tryserver (keys(%servers)) {
                   7754:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7755:                 push(@homeservers,$tryserver);
                   7756:             }
                   7757:         }
                   7758:     }
                   7759:     my $response;
                   7760:     foreach my $server (@homeservers) {
                   7761:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7762:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7763:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7764:             split(':',$response);
                   7765:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7766:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7767:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7768:             my ($name,$value)=split('=',$item);
                   7769:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7770:         }
                   7771:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7772:             my ($name,$value)=split('=',$item);
                   7773:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7774:         }
                   7775:         return 'ok';
                   7776:     }
                   7777:     return $response;
                   7778: }
1.792     raeburn  7779: 
1.1010    raeburn  7780: sub auto_courserequest_checks {
                   7781:     my ($dom) = @_;
1.1020    raeburn  7782:     my ($homeserver,%validations);
                   7783:     if ($dom =~ /^$match_domain$/) {
                   7784:         $homeserver = &domain($dom,'primary');
                   7785:     }
                   7786:     unless ($homeserver eq 'no_host') {
                   7787:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7788:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7789:             my @items = split(/&/,$response);
                   7790:             foreach my $item (@items) {
                   7791:                 my ($key,$value) = split('=',$item);
                   7792:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7793:             }
                   7794:         }
                   7795:     }
1.1010    raeburn  7796:     return %validations; 
                   7797: }
                   7798: 
1.1020    raeburn  7799: sub auto_courserequest_validation {
                   7800:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7801:     my ($homeserver,$response);
                   7802:     if ($dom =~ /^$match_domain$/) {
                   7803:         $homeserver = &domain($dom,'primary');
                   7804:     }
                   7805:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7806:           
1.1020    raeburn  7807:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7808:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7809:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7810:                                     $homeserver));
                   7811:     }
                   7812:     return $response;
                   7813: }
                   7814: 
1.777     albertel 7815: sub auto_validate_class_sec {
1.918     raeburn  7816:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7817:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7818:     my $ownerlist;
                   7819:     if (ref($owners) eq 'ARRAY') {
                   7820:         $ownerlist = join(',',@{$owners});
                   7821:     } else {
                   7822:         $ownerlist = $owners;
                   7823:     }
1.773     raeburn  7824:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7825:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7826:     return $response;
                   7827: }
                   7828: 
1.679     raeburn  7829: # ------------------------------------------------------- Course Group routines
                   7830: 
                   7831: sub get_coursegroups {
1.809     raeburn  7832:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7833:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7834: }
                   7835: 
1.679     raeburn  7836: sub modify_coursegroup {
                   7837:     my ($cdom,$cnum,$groupsettings) = @_;
                   7838:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7839: }
                   7840: 
1.809     raeburn  7841: sub toggle_coursegroup_status {
                   7842:     my ($cdom,$cnum,$group,$action) = @_;
                   7843:     my ($from_namespace,$to_namespace);
                   7844:     if ($action eq 'delete') {
                   7845:         $from_namespace = 'coursegroups';
                   7846:         $to_namespace = 'deleted_groups';
                   7847:     } else {
                   7848:         $from_namespace = 'deleted_groups';
                   7849:         $to_namespace = 'coursegroups';
                   7850:     }
                   7851:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7852:     if (my $tmp = &error(%curr_group)) {
                   7853:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7854:         return ('read error',$tmp);
                   7855:     } else {
                   7856:         my %savedsettings = %curr_group; 
1.809     raeburn  7857:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7858:         my $deloutcome;
                   7859:         if ($result eq 'ok') {
1.809     raeburn  7860:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7861:         } else {
                   7862:             return ('write error',$result);
                   7863:         }
                   7864:         if ($deloutcome eq 'ok') {
                   7865:             return 'ok';
                   7866:         } else {
                   7867:             return ('delete error',$deloutcome);
                   7868:         }
                   7869:     }
                   7870: }
                   7871: 
1.679     raeburn  7872: sub modify_group_roles {
1.957     raeburn  7873:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7874:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7875:     my $role = 'gr/'.&escape($userprivs);
                   7876:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7877:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7878:     if ($result eq 'ok') {
                   7879:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7880:     }
1.679     raeburn  7881:     return $result;
                   7882: }
                   7883: 
                   7884: sub modify_coursegroup_membership {
                   7885:     my ($cdom,$cnum,$membership) = @_;
                   7886:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7887:     return $result;
                   7888: }
                   7889: 
1.682     raeburn  7890: sub get_active_groups {
                   7891:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7892:     my $now = time;
                   7893:     my %groups = ();
                   7894:     foreach my $key (keys(%env)) {
1.811     albertel 7895:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7896:             my ($start,$end) = split(/\./,$env{$key});
                   7897:             if (($end!=0) && ($end<$now)) { next; }
                   7898:             if (($start!=0) && ($start>$now)) { next; }
                   7899:             if ($1 eq $cdom && $2 eq $cnum) {
                   7900:                 $groups{$3} = $env{$key} ;
                   7901:             }
                   7902:         }
                   7903:     }
                   7904:     return %groups;
                   7905: }
                   7906: 
1.683     raeburn  7907: sub get_group_membership {
                   7908:     my ($cdom,$cnum,$group) = @_;
                   7909:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7910: }
                   7911: 
                   7912: sub get_users_groups {
                   7913:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7914:     my @usersgroups;
1.683     raeburn  7915:     my $cachetime=1800;
                   7916: 
                   7917:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7918:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7919:     if (defined($cached)) {
1.734     albertel 7920:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7921:     } else {  
                   7922:         $grouplist = '';
1.816     raeburn  7923:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7924:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7925:         my $access_end = $env{'course.'.$courseid.
                   7926:                               '.default_enrollment_end_date'};
                   7927:         my $now = time;
                   7928:         foreach my $key (keys(%roleshash)) {
                   7929:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7930:                 my $group = $1;
                   7931:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7932:                     my $start = $2;
                   7933:                     my $end = $1;
                   7934:                     if ($start == -1) { next; } # deleted from group
                   7935:                     if (($start!=0) && ($start>$now)) { next; }
                   7936:                     if (($end!=0) && ($end<$now)) {
                   7937:                         if ($access_end && $access_end < $now) {
                   7938:                             if ($access_end - $end < 86400) {
                   7939:                                 push(@usersgroups,$group);
1.733     raeburn  7940:                             }
                   7941:                         }
1.817     raeburn  7942:                         next;
1.733     raeburn  7943:                     }
1.817     raeburn  7944:                     push(@usersgroups,$group);
1.683     raeburn  7945:                 }
                   7946:             }
                   7947:         }
1.817     raeburn  7948:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7949:         $grouplist = join(':',@usersgroups);
                   7950:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7951:     }
1.733     raeburn  7952:     return @usersgroups;
1.683     raeburn  7953: }
                   7954: 
                   7955: sub devalidate_getgroups_cache {
                   7956:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7957:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7958: 
1.683     raeburn  7959:     my $hashid="$udom:$uname:$courseid";
                   7960:     &devalidate_cache_new('getgroups',$hashid);
                   7961: }
                   7962: 
1.12      www      7963: # ------------------------------------------------------------------ Plain Text
                   7964: 
                   7965: sub plaintext {
1.988     raeburn  7966:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7967:     if ($short =~ m{^cr/}) {
1.758     albertel 7968: 	return (split('/',$short))[-1];
                   7969:     }
1.742     raeburn  7970:     if (!defined($cid)) {
                   7971:         $cid = $env{'request.course.id'};
                   7972:     }
                   7973:     my %rolenames = (
1.1008    raeburn  7974:                       Course    => 'std',
                   7975:                       Community => 'alt1',
1.742     raeburn  7976:                     );
1.1037    raeburn  7977:     if ($cid ne '') {
                   7978:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7979:             unless ($forcedefault) {
                   7980:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7981:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7982:                 return &Apache::lonlocal::mt($roletext);
                   7983:             }
                   7984:         }
                   7985:     }
                   7986:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7987:         (defined($rolenames{$type})) && 
                   7988:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7989:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7990:     } elsif ($cid ne '') {
                   7991:         my $crstype = $env{'course.'.$cid.'.type'};
                   7992:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7993:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7994:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7995:         }
1.742     raeburn  7996:     }
1.1037    raeburn  7997:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7998: }
                   7999: 
                   8000: # ----------------------------------------------------------------- Assign Role
                   8001: 
                   8002: sub assignrole {
1.957     raeburn  8003:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8004:         $context)=@_;
1.21      www      8005:     my $mrole;
                   8006:     if ($role =~ /^cr\//) {
1.393     www      8007:         my $cwosec=$url;
1.811     albertel 8008:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8009: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8010:            my $refused = 1;
                   8011:            if ($context eq 'requestcourses') {
                   8012:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8013:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8014:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8015:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8016:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8017:                            if ($crsenv{'internal.courseowner'} eq
                   8018:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8019:                                $refused = '';
                   8020:                            }
                   8021:                        }
                   8022:                    }
                   8023:                }
                   8024:            }
                   8025:            if ($refused) {
                   8026:                &logthis('Refused custom assignrole: '.
                   8027:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8028:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8029:                return 'refused';
                   8030:            }
1.104     www      8031:         }
1.21      www      8032:         $mrole='cr';
1.678     raeburn  8033:     } elsif ($role =~ /^gr\//) {
                   8034:         my $cwogrp=$url;
1.811     albertel 8035:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8036:         unless (&allowed('mdg',$cwogrp)) {
                   8037:             &logthis('Refused group assignrole: '.
                   8038:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8039:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8040:             return 'refused';
                   8041:         }
                   8042:         $mrole='gr';
1.21      www      8043:     } else {
1.82      www      8044:         my $cwosec=$url;
1.811     albertel 8045:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8046:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8047:             my $refused;
                   8048:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8049:                 if (!(&allowed('c'.$role,$url))) {
                   8050:                     $refused = 1;
                   8051:                 }
                   8052:             } else {
                   8053:                 $refused = 1;
                   8054:             }
1.947     raeburn  8055:             if ($refused) {
1.1045    raeburn  8056:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8057:                 if (!$selfenroll && $context eq 'course') {
                   8058:                     my %crsenv;
                   8059:                     if ($role eq 'cc' || $role eq 'co') {
                   8060:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8061:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8062:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8063:                                 if ($crsenv{'internal.courseowner'} eq 
                   8064:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8065:                                     $refused = '';
                   8066:                                 }
                   8067:                             }
                   8068:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8069:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8070:                                 if ($crsenv{'internal.courseowner'} eq 
                   8071:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8072:                                     $refused = '';
                   8073:                                 }
                   8074:                             }
                   8075:                         }
                   8076:                     }
                   8077:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8078:                     $refused = '';
1.1017    raeburn  8079:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8080:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8081:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8082:                         my $wrongcc;
                   8083:                         if ($cnum =~ /^$match_community$/) {
                   8084:                             $wrongcc = 1 if ($role eq 'cc');
                   8085:                         } else {
                   8086:                             $wrongcc = 1 if ($role eq 'co');
                   8087:                         }
                   8088:                         unless ($wrongcc) {
                   8089:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8090:                             if ($crsenv{'internal.courseowner'} eq 
                   8091:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8092:                                 $refused = '';
                   8093:                             }
1.1017    raeburn  8094:                         }
                   8095:                     }
1.1183    raeburn  8096:                 } elsif ($context eq 'requestauthor') {
                   8097:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8098:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8099:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8100:                             $refused = '';
                   8101:                         } else {
                   8102:                             my %domdefaults = &get_domain_defaults($udom);
                   8103:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8104:                                 my $checkbystatus;
                   8105:                                 if ($env{'user.adv'}) { 
                   8106:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8107:                                     if ($disposition eq 'automatic') {
                   8108:                                         $refused = '';
                   8109:                                     } elsif ($disposition eq '') {
                   8110:                                         $checkbystatus = 1;
                   8111:                                     } 
                   8112:                                 } else {
                   8113:                                     $checkbystatus = 1;
                   8114:                                 }
                   8115:                                 if ($checkbystatus) {
                   8116:                                     if ($env{'environment.inststatus'}) {
                   8117:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8118:                                         foreach my $type (@inststatuses) {
                   8119:                                             if (($type ne '') &&
                   8120:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8121:                                                 $refused = '';
                   8122:                                             }
                   8123:                                         }
                   8124:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8125:                                         $refused = '';
                   8126:                                     }
                   8127:                                 }
                   8128:                             }
                   8129:                         }
                   8130:                     }
1.1017    raeburn  8131:                 }
                   8132:                 if ($refused) {
1.947     raeburn  8133:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8134:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8135: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8136:                     return 'refused';
                   8137:                 }
1.932     raeburn  8138:             }
1.1131    raeburn  8139:         } elsif ($role eq 'au') {
                   8140:             if ($url ne '/'.$udom.'/') {
                   8141:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8142:                          ' to assign author role for '.$uname.':'.$udom.
                   8143:                          ' in domain: '.$url.' refused (wrong domain).');
                   8144:                 return 'refused';
                   8145:             }
1.104     www      8146:         }
1.21      www      8147:         $mrole=$role;
                   8148:     }
1.620     albertel 8149:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8150:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8151:     if ($end) { $command.='_'.$end; }
1.21      www      8152:     if ($start) {
                   8153: 	if ($end) { 
1.81      www      8154:            $command.='_'.$start; 
1.21      www      8155:         } else {
1.81      www      8156:            $command.='_0_'.$start;
1.21      www      8157:         }
                   8158:     }
1.739     raeburn  8159:     my $origstart = $start;
                   8160:     my $origend = $end;
1.957     raeburn  8161:     my $delflag;
1.357     www      8162: # actually delete
                   8163:     if ($deleteflag) {
1.373     www      8164: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8165: # modify command to delete the role
1.620     albertel 8166:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8167:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8168: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8169: # set start and finish to negative values for userrolelog
                   8170:            $start=-1;
                   8171:            $end=-1;
1.957     raeburn  8172:            $delflag = 1;
1.357     www      8173:         }
                   8174:     }
                   8175: # send command
1.349     www      8176:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8177: # log new user role if status is ok
1.349     www      8178:     if ($answer eq 'ok') {
1.663     raeburn  8179: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8180:         if (($role eq 'cc') || ($role eq 'in') ||
                   8181:             ($role eq 'ep') || ($role eq 'ad') ||
                   8182:             ($role eq 'ta') || ($role eq 'st') ||
                   8183:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8184:             ($role eq 'co')) {
1.1200    raeburn  8185: # for course roles, perform group memberships changes triggered by role change.
                   8186:             unless ($role =~ /^gr/) {
                   8187:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8188:                                                  $origstart,$selfenroll,$context);
                   8189:             }
1.1184    raeburn  8190:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8191:                            $selfenroll,$context);
                   8192:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8193:                  ($role eq 'au') || ($role eq 'dc')) {
                   8194:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8195:                            $context);
                   8196:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8197:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8198:                              $context); 
                   8199:         }
1.1053    raeburn  8200:         if ($role eq 'cc') {
                   8201:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8202:         }
1.349     www      8203:     }
                   8204:     return $answer;
1.169     harris41 8205: }
                   8206: 
1.1053    raeburn  8207: sub autoupdate_coowners {
                   8208:     my ($url,$end,$start,$uname,$udom) = @_;
                   8209:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8210:     if (($cdom ne '') && ($cnum ne '')) {
                   8211:         my $now = time;
                   8212:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8213:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8214:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8215:             my $instcode = $coursehash{'internal.coursecode'};
                   8216:             if ($instcode ne '') {
1.1056    raeburn  8217:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8218:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8219:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8220:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8221:                         if ($result eq 'valid') {
                   8222:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8223:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8224:                                     push(@newcoowners,$coowner);
                   8225:                                 }
                   8226:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8227:                                     push(@newcoowners,$uname.':'.$udom);
                   8228:                                 }
                   8229:                                 @newcoowners = sort(@newcoowners);
                   8230:                             } else {
                   8231:                                 push(@newcoowners,$uname.':'.$udom);
                   8232:                             }
                   8233:                         } else {
                   8234:                             if ($coursehash{'internal.co-owners'}) {
                   8235:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8236:                                     unless ($coowner eq $uname.':'.$udom) {
                   8237:                                         push(@newcoowners,$coowner);
                   8238:                                     }
                   8239:                                 }
                   8240:                                 unless (@newcoowners > 0) {
                   8241:                                     $delcoowners = 1;
                   8242:                                     $coowners = '';
                   8243:                                 }
                   8244:                             }
                   8245:                         }
                   8246:                         if (@newcoowners || $delcoowners) {
                   8247:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8248:                                             $delcoowners,@newcoowners);
                   8249:                         }
                   8250:                     }
                   8251:                 }
                   8252:             }
                   8253:         }
                   8254:     }
                   8255: }
                   8256: 
                   8257: sub store_coowners {
                   8258:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8259:     my $cid = $cdom.'_'.$cnum;
                   8260:     my ($coowners,$delresult,$putresult);
                   8261:     if (@newcoowners) {
                   8262:         $coowners = join(',',@newcoowners);
                   8263:         my %coownershash = (
                   8264:                             'internal.co-owners' => $coowners,
                   8265:                            );
                   8266:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8267:         if ($putresult eq 'ok') {
                   8268:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8269:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8270:             }
                   8271:         }
                   8272:     }
                   8273:     if ($delcoowners) {
                   8274:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8275:         if ($delresult eq 'ok') {
                   8276:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8277:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8278:             }
                   8279:         }
                   8280:     }
                   8281:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8282:         my %crsinfo =
                   8283:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8284:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8285:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8286:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8287:         }
                   8288:     }
                   8289: }
                   8290: 
1.169     harris41 8291: # -------------------------------------------------- Modify user authentication
1.197     www      8292: # Overrides without validation
                   8293: 
1.169     harris41 8294: sub modifyuserauth {
                   8295:     my ($udom,$uname,$umode,$upass)=@_;
                   8296:     my $uhome=&homeserver($uname,$udom);
1.197     www      8297:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8298:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8299:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8300:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8301:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8302: 		     &escape($upass),$uhome);
1.620     albertel 8303:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8304:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8305:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8306:     &log($udom,,$uname,$uhome,
1.620     albertel 8307:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8308:                                      $env{'user.name'}.', '.$umode.
1.197     www      8309:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8310:     unless ($reply eq 'ok') {
1.197     www      8311:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8312: 	return 'error: '.$reply;
                   8313:     }   
1.170     harris41 8314:     return 'ok';
1.80      www      8315: }
                   8316: 
1.81      www      8317: # --------------------------------------------------------------- Modify a user
1.80      www      8318: 
1.81      www      8319: sub modifyuser {
1.206     matthew  8320:     my ($udom,    $uname, $uid,
                   8321:         $umode,   $upass, $first,
                   8322:         $middle,  $last,  $gene,
1.1058    raeburn  8323:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8324:     $udom= &LONCAPA::clean_domain($udom);
                   8325:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8326:     my $showcandelete = 'none';
                   8327:     if (ref($candelete) eq 'ARRAY') {
                   8328:         if (@{$candelete} > 0) {
                   8329:             $showcandelete = join(', ',@{$candelete});
                   8330:         }
                   8331:     }
1.81      www      8332:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8333:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8334: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8335:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8336:                                      ' desiredhome not specified'). 
1.620     albertel 8337:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8338:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8339:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8340:     my $newuser;
                   8341:     if ($uhome eq 'no_host') {
                   8342:         $newuser = 1;
                   8343:     }
1.80      www      8344: # ----------------------------------------------------------------- Create User
1.406     albertel 8345:     if (($uhome eq 'no_host') && 
                   8346: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8347:         my $unhome='';
1.844     albertel 8348:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8349:             $unhome = $desiredhome;
1.620     albertel 8350: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8351: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8352:         } else { # load balancing routine for determining $unhome
1.81      www      8353:             my $loadm=10000000;
1.841     albertel 8354: 	    my %servers = &get_servers($udom,'library');
                   8355: 	    foreach my $tryserver (keys(%servers)) {
                   8356: 		my $answer=reply('load',$tryserver);
                   8357: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8358: 		    $loadm=$answer;
                   8359: 		    $unhome=$tryserver;
                   8360: 		}
1.80      www      8361: 	    }
                   8362:         }
                   8363:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8364: 	    return 'error: unable to find a home server for '.$uname.
                   8365:                    ' in domain '.$udom;
1.80      www      8366:         }
                   8367:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8368:                          &escape($upass),$unhome);
                   8369: 	unless ($reply eq 'ok') {
                   8370:             return 'error: '.$reply;
                   8371:         }   
1.230     stredwic 8372:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8373:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8374: 	    return 'error: unable verify users home machine.';
1.80      www      8375:         }
1.209     matthew  8376:     }   # End of creation of new user
1.80      www      8377: # ---------------------------------------------------------------------- Add ID
                   8378:     if ($uid) {
                   8379:        $uid=~tr/A-Z/a-z/;
                   8380:        my %uidhash=&idrget($udom,$uname);
1.196     www      8381:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8382:          && (!$forceid)) {
1.80      www      8383: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8384: 	      return 'error: user id "'.$uid.'" does not match '.
                   8385:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8386:           }
                   8387:        } else {
                   8388: 	  &idput($udom,($uname => $uid));
                   8389:        }
                   8390:     }
                   8391: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8392:     my @tmp=&get('environment',
1.899     raeburn  8393: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8394:                     'permanentemail','inststatus'],
1.134     albertel 8395: 		   $udom,$uname);
1.1075    raeburn  8396:     my (%names,%oldnames);
1.313     matthew  8397:     if ($tmp[0] =~ m/^error:.*/) { 
                   8398:         %names=(); 
                   8399:     } else {
                   8400:         %names = @tmp;
1.1075    raeburn  8401:         %oldnames = %names;
1.313     matthew  8402:     }
1.388     www      8403: #
1.1058    raeburn  8404: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8405: # of users did not contain them), do not overwrite existing values
                   8406: # unless field is in $candelete array ref.  
                   8407: #
                   8408: 
                   8409:     my @fields = ('firstname','middlename','lastname','generation',
                   8410:                   'permanentemail','id');
                   8411:     my %newvalues;
                   8412:     if (ref($candelete) eq 'ARRAY') {
                   8413:         foreach my $field (@fields) {
                   8414:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8415:                 if ($field eq 'firstname') {
                   8416:                     $names{$field} = $first;
                   8417:                 } elsif ($field eq 'middlename') {
                   8418:                     $names{$field} = $middle;
                   8419:                 } elsif ($field eq 'lastname') {
                   8420:                     $names{$field} = $last;
                   8421:                 } elsif ($field eq 'generation') { 
                   8422:                     $names{$field} = $gene;
                   8423:                 } elsif ($field eq 'permanentemail') {
                   8424:                     $names{$field} = $email;
                   8425:                 } elsif ($field eq 'id') {
                   8426:                     $names{$field}  = $uid;
                   8427:                 }
                   8428:             }
                   8429:         }
                   8430:     }
1.388     www      8431:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8432:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8433:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8434:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8435:     if ($email) {
                   8436:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8437:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8438:     }
1.899     raeburn  8439:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8440:     if (defined($inststatus)) {
                   8441:         $names{'inststatus'} = '';
                   8442:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8443:         if (ref($usertypes) eq 'HASH') {
                   8444:             my @okstatuses; 
                   8445:             foreach my $item (split(/:/,$inststatus)) {
                   8446:                 if (defined($usertypes->{$item})) {
                   8447:                     push(@okstatuses,$item);  
                   8448:                 }
                   8449:             }
                   8450:             if (@okstatuses) {
                   8451:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8452:             }
                   8453:         }
                   8454:     }
1.1075    raeburn  8455:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8456:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8457:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8458:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8459:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8460:     } else {
                   8461:         $logmsg .= ' during self creation';
                   8462:     }
1.1075    raeburn  8463:     my $changed;
                   8464:     if ($newuser) {
                   8465:         $changed = 1;
                   8466:     } else {
                   8467:         foreach my $field (@fields) {
                   8468:             if ($names{$field} ne $oldnames{$field}) {
                   8469:                 $changed = 1;
                   8470:                 last;
                   8471:             }
                   8472:         }
                   8473:     }
                   8474:     unless ($changed) {
                   8475:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8476:         &logthis($logmsg);
                   8477:         return 'ok';
                   8478:     }
                   8479:     my $reply = &put('environment', \%names, $udom,$uname);
                   8480:     if ($reply ne 'ok') { 
                   8481:         return 'error: '.$reply;
                   8482:     }
1.1087    raeburn  8483:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8484:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8485:     }
1.1075    raeburn  8486:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8487:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8488:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8489:     &logthis($logmsg);
1.134     albertel 8490:     return 'ok';
1.80      www      8491: }
                   8492: 
1.81      www      8493: # -------------------------------------------------------------- Modify student
1.80      www      8494: 
1.81      www      8495: sub modifystudent {
                   8496:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8497:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8498:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8499:     if (!$cid) {
1.620     albertel 8500: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8501: 	    return 'not_in_class';
                   8502: 	}
1.80      www      8503:     }
                   8504: # --------------------------------------------------------------- Make the user
1.81      www      8505:     my $reply=&modifyuser
1.209     matthew  8506: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8507:          $desiredhome,$email,$inststatus);
1.80      www      8508:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8509:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8510:     # student's environment
1.297     matthew  8511:     $uid = undef if (!$forceid);
1.455     albertel 8512:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8513:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8514:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8515:     return $reply;
                   8516: }
                   8517: 
                   8518: sub modify_student_enrollment {
1.1216    raeburn  8519:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8520:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8521:     my ($cdom,$cnum,$chome);
                   8522:     if (!$cid) {
1.620     albertel 8523: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8524: 	    return 'not_in_class';
                   8525: 	}
1.620     albertel 8526: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8527: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8528:     } else {
                   8529: 	($cdom,$cnum)=split(/_/,$cid);
                   8530:     }
1.620     albertel 8531:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8532:     if (!$chome) {
1.457     raeburn  8533: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8534:     }
1.455     albertel 8535:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8536:     # Make sure the user exists
1.81      www      8537:     my $uhome=&homeserver($uname,$udom);
                   8538:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8539: 	return 'error: no such user';
                   8540:     }
1.297     matthew  8541:     # Get student data if we were not given enough information
                   8542:     if (!defined($first)  || $first  eq '' || 
                   8543:         !defined($last)   || $last   eq '' || 
                   8544:         !defined($uid)    || $uid    eq '' || 
                   8545:         !defined($middle) || $middle eq '' || 
                   8546:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8547:         # They did not supply us with enough data to enroll the student, so
                   8548:         # we need to pick up more information.
1.297     matthew  8549:         my %tmp = &get('environment',
1.294     matthew  8550:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8551:                        ,$udom,$uname);
                   8552: 
1.800     albertel 8553:         #foreach my $key (keys(%tmp)) {
                   8554:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8555:         #}
1.294     matthew  8556:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8557:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8558:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8559:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8560:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8561:     }
1.556     albertel 8562:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8563:     my $user = "$uname:$udom";
                   8564:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8565:     my $reply=cput('classlist',
1.1148    raeburn  8566: 		   {$user => 
1.1216    raeburn  8567: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8568: 		   $cdom,$cnum);
1.1148    raeburn  8569:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8570:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8571:     } else { 
1.81      www      8572: 	return 'error: '.$reply;
                   8573:     }
1.297     matthew  8574:     # Add student role to user
1.83      www      8575:     my $uurl='/'.$cid;
1.81      www      8576:     $uurl=~s/\_/\//g;
                   8577:     if ($usec) {
                   8578: 	$uurl.='/'.$usec;
                   8579:     }
1.1148    raeburn  8580:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8581:                              $selfenroll,$context);
                   8582:     if ($result ne 'ok') {
                   8583:         if ($old_entry{$user} ne '') {
                   8584:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8585:         } else {
                   8586:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8587:         }
                   8588:     }
                   8589:     return $result; 
1.21      www      8590: }
                   8591: 
1.556     albertel 8592: sub format_name {
                   8593:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8594:     my $name;
                   8595:     if ($first ne 'lastname') {
                   8596: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8597:     } else {
                   8598: 	if ($lastname=~/\S/) {
                   8599: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8600: 	    $name=~s/\s+,/,/;
                   8601: 	} else {
                   8602: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8603: 	}
                   8604:     }
                   8605:     $name=~s/^\s+//;
                   8606:     $name=~s/\s+$//;
                   8607:     $name=~s/\s+/ /g;
                   8608:     return $name;
                   8609: }
                   8610: 
1.84      www      8611: # ------------------------------------------------- Write to course preferences
                   8612: 
                   8613: sub writecoursepref {
                   8614:     my ($courseid,%prefs)=@_;
                   8615:     $courseid=~s/^\///;
                   8616:     $courseid=~s/\_/\//g;
                   8617:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8618:     my $chome=homeserver($cnum,$cdomain);
                   8619:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8620: 	return 'error: no such course';
                   8621:     }
                   8622:     my $cstring='';
1.800     albertel 8623:     foreach my $pref (keys(%prefs)) {
                   8624: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8625:     }
1.84      www      8626:     $cstring=~s/\&$//;
                   8627:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8628: }
                   8629: 
                   8630: # ---------------------------------------------------------- Make/modify course
                   8631: 
                   8632: sub createcourse {
1.741     raeburn  8633:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8634:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8635:     $url=&declutter($url);
                   8636:     my $cid='';
1.1028    raeburn  8637:     if ($context eq 'requestcourses') {
                   8638:         my $can_create = 0;
                   8639:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8640:         if ($udom eq $ownerdom) {
                   8641:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8642:                                   $context)) {
                   8643:                 $can_create = 1;
                   8644:             }
                   8645:         } else {
                   8646:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8647:                                            $category);
                   8648:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8649:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8650:                 if (@curr > 0) {
                   8651:                     my @options = qw(approval validate autolimit);
                   8652:                     my $optregex = join('|',@options);
                   8653:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8654:                         $can_create = 1;
                   8655:                     }
                   8656:                 }
                   8657:             }
                   8658:         }
                   8659:         if ($can_create) {
                   8660:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8661:                 unless (&allowed('ccc',$udom)) {
                   8662:                     return 'refused'; 
                   8663:                 }
1.1017    raeburn  8664:             }
                   8665:         } else {
                   8666:             return 'refused';
                   8667:         }
1.1028    raeburn  8668:     } elsif (!&allowed('ccc',$udom)) {
                   8669:         return 'refused';
1.84      www      8670:     }
1.1011    raeburn  8671: # --------------------------------------------------------------- Get Unique ID
                   8672:     my $uname;
                   8673:     if ($cnum =~ /^$match_courseid$/) {
                   8674:         my $chome=&homeserver($cnum,$udom,'true');
                   8675:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8676:             $uname = $cnum;
                   8677:         } else {
1.1038    raeburn  8678:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8679:         }
                   8680:     } else {
1.1038    raeburn  8681:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8682:     }
                   8683:     return $uname if ($uname =~ /^error/);
                   8684: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8685:     if (!defined($course_server)) {
                   8686:         if (defined(&domain($udom,'primary'))) {
                   8687:             $course_server = &domain($udom,'primary');
                   8688:         } else {
                   8689:             $course_server = $env{'user.home'}; 
                   8690:         }
                   8691:     }
                   8692:     my %host_servers =
                   8693:         &Apache::lonnet::get_servers($udom,'library');
                   8694:     unless ($host_servers{$course_server}) {
                   8695:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8696:     }
1.84      www      8697: # ------------------------------------------------------------- Make the course
                   8698:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8699:                       $course_server);
1.84      www      8700:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8701:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8702:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8703: 	return 'error: no such course';
                   8704:     }
1.271     www      8705: # ----------------------------------------------------------------- Course made
1.516     raeburn  8706: # log existence
1.1029    raeburn  8707:     my $now = time;
1.918     raeburn  8708:     my $newcourse = {
                   8709:                     $udom.'_'.$uname => {
1.921     raeburn  8710:                                      description => $description,
                   8711:                                      inst_code   => $inst_code,
                   8712:                                      owner       => $course_owner,
                   8713:                                      type        => $crstype,
1.1029    raeburn  8714:                                      creator     => $env{'user.name'}.':'.
                   8715:                                                     $env{'user.domain'},
                   8716:                                      created     => $now,
                   8717:                                      context     => $context,
1.918     raeburn  8718:                                                 },
                   8719:                     };
1.921     raeburn  8720:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8721: # set toplevel url
1.271     www      8722:     my $topurl=$url;
                   8723:     unless ($nonstandard) {
                   8724: # ------------------------------------------ For standard courses, make top url
                   8725:         my $mapurl=&clutter($url);
1.278     www      8726:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8727:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8728: <map>
                   8729: <resource id="1" type="start"></resource>
                   8730: <resource id="2" src="$mapurl"></resource>
                   8731: <resource id="3" type="finish"></resource>
                   8732: <link index="1" from="1" to="2"></link>
                   8733: <link index="2" from="2" to="3"></link>
                   8734: </map>
                   8735: ENDINITMAP
                   8736:         $topurl=&declutter(
1.638     albertel 8737:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8738:                           );
                   8739:     }
                   8740: # ----------------------------------------------------------- Write preferences
1.84      www      8741:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8742:                      ('description'              => $description,
                   8743:                       'url'                      => $topurl,
                   8744:                       'internal.creator'         => $env{'user.name'}.':'.
                   8745:                                                     $env{'user.domain'},
                   8746:                       'internal.created'         => $now,
                   8747:                       'internal.creationcontext' => $context)
                   8748:                     );
1.84      www      8749:     return '/'.$udom.'/'.$uname;
                   8750: }
                   8751: 
1.1011    raeburn  8752: # ------------------------------------------------------------------- Create ID
                   8753: sub generate_coursenum {
1.1038    raeburn  8754:     my ($udom,$crstype) = @_;
1.1011    raeburn  8755:     my $domdesc = &domain($udom);
                   8756:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8757:     my $first;
                   8758:     if ($crstype eq 'Community') {
                   8759:         $first = '0';
                   8760:     } else {
                   8761:         $first = int(1+rand(9)); 
                   8762:     } 
                   8763:     my $uname=$first.
1.1011    raeburn  8764:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8765:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8766:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8767: # ----------------------------------------------- Make sure that does not exist
                   8768:     my $uhome=&homeserver($uname,$udom,'true');
                   8769:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8770:         if ($crstype eq 'Community') {
                   8771:             $first = '0';
                   8772:         } else {
                   8773:             $first = int(1+rand(9));
                   8774:         }
                   8775:         $uname=$first.
1.1011    raeburn  8776:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8777:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8778:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8779:         $uhome=&homeserver($uname,$udom,'true');
                   8780:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8781:             return 'error: unable to generate unique course-ID';
                   8782:         }
                   8783:     }
                   8784:     return $uname;
                   8785: }
                   8786: 
1.813     albertel 8787: sub is_course {
1.1167    droeschl 8788:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8789:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8790: 
                   8791:     return unless $cdom and $cnum;
                   8792: 
                   8793:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8794:         '.');
                   8795: 
1.1219    raeburn  8796:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8797:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8798: }
                   8799: 
1.1015    raeburn  8800: sub store_userdata {
                   8801:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8802:     my $result;
1.1016    raeburn  8803:     if ($datakey ne '') {
1.1013    raeburn  8804:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8805:             if ($udom eq '' || $uname eq '') {
                   8806:                 $udom = $env{'user.domain'};
                   8807:                 $uname = $env{'user.name'};
                   8808:             }
                   8809:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8810:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8811:                 $result = 'error: no_host';
                   8812:             } else {
                   8813:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8814:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8815: 
                   8816:                 my $namevalue='';
                   8817:                 foreach my $key (keys(%{$storehash})) {
                   8818:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8819:                 }
                   8820:                 $namevalue=~s/\&$//;
1.1224    raeburn  8821:                 unless ($namespace eq 'courserequests') {
                   8822:                     $datakey = &escape($datakey);
                   8823:                 }
1.1105    raeburn  8824:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8825:                                   $namevalue,$uhome);
1.1013    raeburn  8826:             }
                   8827:         } else {
                   8828:             $result = 'error: data to store was not a hash reference'; 
                   8829:         }
                   8830:     } else {
                   8831:         $result= 'error: invalid requestkey'; 
                   8832:     }
                   8833:     return $result;
                   8834: }
                   8835: 
1.21      www      8836: # ---------------------------------------------------------- Assign Custom Role
                   8837: 
                   8838: sub assigncustomrole {
1.957     raeburn  8839:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8840:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8841:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8842: }
                   8843: 
                   8844: # ----------------------------------------------------------------- Revoke Role
                   8845: 
                   8846: sub revokerole {
1.957     raeburn  8847:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8848:     my $now=time;
1.965     raeburn  8849:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8850: }
                   8851: 
                   8852: # ---------------------------------------------------------- Revoke Custom Role
                   8853: 
                   8854: sub revokecustomrole {
1.957     raeburn  8855:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8856:     my $now=time;
1.357     www      8857:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8858:            $deleteflag,$selfenroll,$context);
1.17      www      8859: }
                   8860: 
1.533     banghart 8861: # ------------------------------------------------------------ Disk usage
1.535     albertel 8862: sub diskusage {
1.955     raeburn  8863:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8864:     $directorypath =~ s/\/$//;
                   8865:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8866:                        .&escape($getpropath).':'.&escape($uname).':'
                   8867:                        .&escape($udom),homeserver($uname,$udom));
                   8868:     if ($listing eq 'unknown_cmd') {
                   8869:         if ($getpropath) {
                   8870:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8871:         }
                   8872:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8873:     }
1.514     albertel 8874:     return $listing;
1.512     banghart 8875: }
                   8876: 
1.566     banghart 8877: sub is_locked {
1.1096    raeburn  8878:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8879:     my @check;
                   8880:     my $is_locked;
1.1093    raeburn  8881:     push (@check,$file_name);
1.613     albertel 8882:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8883: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8884:     my ($tmp)=keys(%locked);
                   8885:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8886:     
1.566     banghart 8887:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8888:         $is_locked = 'false';
                   8889:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8890:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8891:                $is_locked = 'true';
1.1096    raeburn  8892:                if (ref($which) eq 'ARRAY') {
                   8893:                    push(@{$which},$entry);
                   8894:                } else {
                   8895:                    last;
                   8896:                }
1.745     raeburn  8897:            }
                   8898:        }
1.566     banghart 8899:     } else {
                   8900:         $is_locked = 'false';
                   8901:     }
1.1093    raeburn  8902:     return $is_locked;
1.566     banghart 8903: }
                   8904: 
1.759     albertel 8905: sub declutter_portfile {
                   8906:     my ($file) = @_;
1.833     albertel 8907:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8908:     return $file;
                   8909: }
                   8910: 
1.559     banghart 8911: # ------------------------------------------------------------- Mark as Read Only
                   8912: 
                   8913: sub mark_as_readonly {
                   8914:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8915:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8916:     my ($tmp)=keys(%current_permissions);
                   8917:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8918:     foreach my $file (@{$files}) {
1.759     albertel 8919: 	$file = &declutter_portfile($file);
1.561     banghart 8920:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8921:     }
1.613     albertel 8922:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8923:     return;
                   8924: }
                   8925: 
1.572     banghart 8926: # ------------------------------------------------------------Save Selected Files
                   8927: 
                   8928: sub save_selected_files {
                   8929:     my ($user, $path, @files) = @_;
                   8930:     my $filename = $user."savedfiles";
1.573     banghart 8931:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8932:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8933:     foreach my $file (@files) {
1.620     albertel 8934:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8935:     }
                   8936:     foreach my $file (@other_files) {
1.574     banghart 8937:         print (OUT $file."\n");
1.572     banghart 8938:     }
1.574     banghart 8939:     close (OUT);
1.572     banghart 8940:     return 'ok';
                   8941: }
                   8942: 
1.574     banghart 8943: sub clear_selected_files {
                   8944:     my ($user) = @_;
                   8945:     my $filename = $user."savedfiles";
1.1117    foxr     8946:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8947:     print (OUT undef);
                   8948:     close (OUT);
                   8949:     return ("ok");    
                   8950: }
                   8951: 
1.572     banghart 8952: sub files_in_path {
                   8953:     my ($user, $path) = @_;
                   8954:     my $filename = $user."savedfiles";
                   8955:     my %return_files;
1.1117    foxr     8956:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8957:     while (my $line_in = <IN>) {
1.574     banghart 8958:         chomp ($line_in);
                   8959:         my @paths_and_file = split (m!/!, $line_in);
                   8960:         my $file_part = pop (@paths_and_file);
                   8961:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8962:         $path_part.='/';
                   8963:         my $path_and_file = $path_part.$file_part;
                   8964:         if ($path_part eq $path) {
                   8965:             $return_files{$file_part}= 'selected';
                   8966:         }
                   8967:     }
1.574     banghart 8968:     close (IN);
                   8969:     return (\%return_files);
1.572     banghart 8970: }
                   8971: 
                   8972: # called in portfolio select mode, to show files selected NOT in current directory
                   8973: sub files_not_in_path {
                   8974:     my ($user, $path) = @_;
                   8975:     my $filename = $user."savedfiles";
                   8976:     my @return_files;
                   8977:     my $path_part;
1.1117    foxr     8978:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8979:     while (my $line = <IN>) {
1.572     banghart 8980:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8981:         my @paths_and_file = split(m|/|, $line);
                   8982:         my $file_part = pop(@paths_and_file);
                   8983:         chomp($file_part);
                   8984:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8985:         $path_part .= '/';
                   8986:         my $path_and_file = $path_part.$file_part;
                   8987:         if ($path_part ne $path) {
1.800     albertel 8988:             push(@return_files, ($path_and_file));
1.572     banghart 8989:         }
                   8990:     }
1.800     albertel 8991:     close(OUT);
1.574     banghart 8992:     return (@return_files);
1.572     banghart 8993: }
                   8994: 
1.745     raeburn  8995: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8996: 
1.745     raeburn  8997: sub get_portfile_permissions {
                   8998:     my ($domain,$user) = @_;
1.613     albertel 8999:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9000:     my ($tmp)=keys(%current_permissions);
                   9001:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9002:     return \%current_permissions;
                   9003: }
                   9004: 
                   9005: #---------------------------------------------Get portfolio file access controls
                   9006: 
1.749     raeburn  9007: sub get_access_controls {
1.745     raeburn  9008:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9009:     my %access;
                   9010:     my $real_file = $file;
                   9011:     $file =~ s/\.meta$//;
1.745     raeburn  9012:     if (defined($file)) {
1.749     raeburn  9013:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9014:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9015:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9016:             }
                   9017:         }
1.745     raeburn  9018:     } else {
1.749     raeburn  9019:         foreach my $key (keys(%{$current_permissions})) {
                   9020:             if ($key =~ /\0accesscontrol$/) {
                   9021:                 if (defined($group)) {
                   9022:                     if ($key !~ m-^\Q$group\E/-) {
                   9023:                         next;
                   9024:                     }
                   9025:                 }
                   9026:                 my ($fullpath) = split(/\0/,$key);
                   9027:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9028:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9029:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9030:                     }
                   9031:                 }
                   9032:             }
                   9033:         }
                   9034:     }
                   9035:     return %access;
                   9036: }
                   9037: 
                   9038: sub modify_access_controls {
                   9039:     my ($file_name,$changes,$domain,$user)=@_;
                   9040:     my ($outcome,$deloutcome);
                   9041:     my %store_permissions;
                   9042:     my %new_values;
                   9043:     my %new_control;
                   9044:     my %translation;
                   9045:     my @deletions = ();
                   9046:     my $now = time;
                   9047:     if (exists($$changes{'activate'})) {
                   9048:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9049:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9050:             my $numnew = scalar(@newitems);
                   9051:             for (my $i=0; $i<$numnew; $i++) {
                   9052:                 my $newkey = $newitems[$i];
                   9053:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9054:                 if ($newkey =~ /^\d+:/) { 
                   9055:                     $newkey =~ s/^(\d+)/$newid/;
                   9056:                     $translation{$1} = $newid;
                   9057:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9058:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9059:                     $translation{$1} = $newid;
                   9060:                 }
1.749     raeburn  9061:                 $new_values{$file_name."\0".$newkey} = 
                   9062:                                           $$changes{'activate'}{$newitems[$i]};
                   9063:                 $new_control{$newkey} = $now;
                   9064:             }
                   9065:         }
                   9066:     }
                   9067:     my %todelete;
                   9068:     my %changed_items;
                   9069:     foreach my $action ('delete','update') {
                   9070:         if (exists($$changes{$action})) {
                   9071:             if (ref($$changes{$action}) eq 'HASH') {
                   9072:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9073:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9074:                     if ($action eq 'delete') { 
                   9075:                         $todelete{$itemnum} = 1;
                   9076:                     } else {
                   9077:                         $changed_items{$itemnum} = $key;
                   9078:                     }
                   9079:                 }
1.745     raeburn  9080:             }
                   9081:         }
1.749     raeburn  9082:     }
                   9083:     # get lock on access controls for file.
                   9084:     my $lockhash = {
                   9085:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9086:                                                        ':'.$env{'user.domain'},
                   9087:                    }; 
                   9088:     my $tries = 0;
                   9089:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9090:    
                   9091:     while (($gotlock ne 'ok') && $tries <3) {
                   9092:         $tries ++;
                   9093:         sleep 1;
                   9094:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9095:     }
                   9096:     if ($gotlock eq 'ok') {
                   9097:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9098:         my ($tmp)=keys(%curr_permissions);
                   9099:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9100:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9101:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9102:             if (ref($curr_controls) eq 'HASH') {
                   9103:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9104:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9105:                     if (defined($todelete{$itemnum})) {
                   9106:                         push(@deletions,$file_name."\0".$control_item);
                   9107:                     } else {
                   9108:                         if (defined($changed_items{$itemnum})) {
                   9109:                             $new_control{$changed_items{$itemnum}} = $now;
                   9110:                             push(@deletions,$file_name."\0".$control_item);
                   9111:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9112:                         } else {
                   9113:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9114:                         }
                   9115:                     }
1.745     raeburn  9116:                 }
                   9117:             }
                   9118:         }
1.970     raeburn  9119:         my ($group);
                   9120:         if (&is_course($domain,$user)) {
                   9121:             ($group,my $file) = split(/\//,$file_name,2);
                   9122:         }
1.749     raeburn  9123:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9124:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9125:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9126:         #  remove lock
                   9127:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9128:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9129:         my $sqlresult =
1.970     raeburn  9130:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9131:                                     $group);
1.749     raeburn  9132:     } else {
                   9133:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9134:     }
1.749     raeburn  9135:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9136: }
                   9137: 
1.827     raeburn  9138: sub make_public_indefinitely {
                   9139:     my ($requrl) = @_;
                   9140:     my $now = time;
                   9141:     my $action = 'activate';
                   9142:     my $aclnum = 0;
                   9143:     if (&is_portfolio_url($requrl)) {
                   9144:         my (undef,$udom,$unum,$file_name,$group) =
                   9145:             &parse_portfolio_url($requrl);
                   9146:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9147:         my %access_controls = &get_access_controls($current_perms,
                   9148:                                                    $group,$file_name);
                   9149:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9150:             my ($num,$scope,$end,$start) = 
                   9151:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9152:             if ($scope eq 'public') {
                   9153:                 if ($start <= $now && $end == 0) {
                   9154:                     $action = 'none';
                   9155:                 } else {
                   9156:                     $action = 'update';
                   9157:                     $aclnum = $num;
                   9158:                 }
                   9159:                 last;
                   9160:             }
                   9161:         }
                   9162:         if ($action eq 'none') {
                   9163:              return 'ok';
                   9164:         } else {
                   9165:             my %changes;
                   9166:             my $newend = 0;
                   9167:             my $newstart = $now;
                   9168:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9169:             $changes{$action}{$newkey} = {
                   9170:                 type => 'public',
                   9171:                 time => {
                   9172:                     start => $newstart,
                   9173:                     end   => $newend,
                   9174:                 },
                   9175:             };
                   9176:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9177:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9178:             return $outcome;
                   9179:         }
                   9180:     } else {
                   9181:         return 'invalid';
                   9182:     }
                   9183: }
                   9184: 
1.745     raeburn  9185: #------------------------------------------------------Get Marked as Read Only
                   9186: 
                   9187: sub get_marked_as_readonly {
                   9188:     my ($domain,$user,$what,$group) = @_;
                   9189:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9190:     my @readonly_files;
1.629     banghart 9191:     my $cmp1=$what;
                   9192:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9193:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9194:         if (defined($group)) {
                   9195:             if ($file_name !~ m-^\Q$group\E/-) {
                   9196:                 next;
                   9197:             }
                   9198:         }
1.561     banghart 9199:         if (ref($value) eq "ARRAY"){
                   9200:             foreach my $stored_what (@{$value}) {
1.629     banghart 9201:                 my $cmp2=$stored_what;
1.759     albertel 9202:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9203:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9204:                 }
1.629     banghart 9205:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9206:                     push(@readonly_files, $file_name);
1.745     raeburn  9207:                     last;
1.563     banghart 9208:                 } elsif (!defined($what)) {
                   9209:                     push(@readonly_files, $file_name);
1.745     raeburn  9210:                     last;
1.561     banghart 9211:                 }
                   9212:             }
1.745     raeburn  9213:         }
1.561     banghart 9214:     }
                   9215:     return @readonly_files;
                   9216: }
1.577     banghart 9217: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9218: 
1.577     banghart 9219: sub get_marked_as_readonly_hash {
1.745     raeburn  9220:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9221:     my %readonly_files;
1.745     raeburn  9222:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9223:         if (defined($group)) {
                   9224:             if ($file_name !~ m-^\Q$group\E/-) {
                   9225:                 next;
                   9226:             }
                   9227:         }
1.577     banghart 9228:         if (ref($value) eq "ARRAY"){
                   9229:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9230:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9231:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9232:                         if ($lock_descriptor eq 'graded') {
                   9233:                             $readonly_files{$file_name} = 'graded';
                   9234:                         } elsif ($lock_descriptor eq 'handback') {
                   9235:                             $readonly_files{$file_name} = 'handback';
                   9236:                         } else {
                   9237:                             if (!exists($readonly_files{$file_name})) {
                   9238:                                 $readonly_files{$file_name} = 'locked';
                   9239:                             }
                   9240:                         }
1.745     raeburn  9241:                     }
1.750     banghart 9242:                 } 
1.577     banghart 9243:             }
                   9244:         } 
                   9245:     }
                   9246:     return %readonly_files;
                   9247: }
1.559     banghart 9248: # ------------------------------------------------------------ Unmark as Read Only
                   9249: 
                   9250: sub unmark_as_readonly {
1.629     banghart 9251:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9252:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9253:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9254:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9255:     my $symb_crs = $what;
                   9256:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9257:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9258:     my ($tmp)=keys(%current_permissions);
                   9259:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9260:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9261:     foreach my $file (@readonly_files) {
1.759     albertel 9262: 	my $clean_file = &declutter_portfile($file);
                   9263: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9264: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9265:         my @new_locks;
                   9266:         my @del_keys;
                   9267:         if (ref($current_locks) eq "ARRAY"){
                   9268:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9269:                 my $compare=$locker;
1.749     raeburn  9270:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9271:                     $compare=join('',@{$locker});
1.746     raeburn  9272:                     if ($compare ne $symb_crs) {
                   9273:                         push(@new_locks, $locker);
                   9274:                     }
1.563     banghart 9275:                 }
                   9276:             }
1.650     albertel 9277:             if (scalar(@new_locks) > 0) {
1.563     banghart 9278:                 $current_permissions{$file} = \@new_locks;
                   9279:             } else {
                   9280:                 push(@del_keys, $file);
1.613     albertel 9281:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9282:                 delete($current_permissions{$file});
1.563     banghart 9283:             }
                   9284:         }
1.561     banghart 9285:     }
1.613     albertel 9286:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9287:     return;
                   9288: }
1.512     banghart 9289: 
1.17      www      9290: # ------------------------------------------------------------ Directory lister
                   9291: 
                   9292: sub dirlist {
1.955     raeburn  9293:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9294:     $uri=~s/^\///;
                   9295:     $uri=~s/\/$//;
1.253     stredwic 9296:     my ($udom, $uname);
1.955     raeburn  9297:     if ($getuserdir) {
1.253     stredwic 9298:         $udom = $userdomain;
                   9299:         $uname = $username;
1.955     raeburn  9300:     } else {
                   9301:         (undef,$udom,$uname)=split(/\//,$uri);
                   9302:         if(defined($userdomain)) {
                   9303:             $udom = $userdomain;
                   9304:         }
                   9305:         if(defined($username)) {
                   9306:             $uname = $username;
                   9307:         }
1.253     stredwic 9308:     }
1.955     raeburn  9309:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9310: 
1.955     raeburn  9311:     $dirRoot = $perlvar{'lonDocRoot'};
                   9312:     if (defined($getpropath)) {
                   9313:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9314:         $dirRoot =~ s/\/$//;
1.955     raeburn  9315:     } elsif (defined($getuserdir)) {
                   9316:         my $subdir=$uname.'__';
                   9317:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9318:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9319:                    ."/$udom/$subdir/$uname";
                   9320:     } elsif (defined($alternateRoot)) {
                   9321:         $dirRoot = $alternateRoot;
1.751     banghart 9322:     }
1.253     stredwic 9323: 
                   9324:     if($udom) {
                   9325:         if($uname) {
1.1135    raeburn  9326:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9327:             if ($uhome eq 'no_host') {
                   9328:                 return ([],'no_host');
                   9329:             }
1.955     raeburn  9330:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9331:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9332:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9333:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9334:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9335:             } else {
                   9336:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9337:             }
1.605     matthew  9338:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9339:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9340:                 @listing_results = split(/:/,$listing);
                   9341:             } else {
                   9342:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9343:             }
1.1135    raeburn  9344:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9345:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9346:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9347:                 return ([],$listing);
                   9348:             } else {
                   9349:                 return (\@listing_results);
1.1135    raeburn  9350:             }
1.955     raeburn  9351:         } elsif(!$alternateRoot) {
1.1136    raeburn  9352:             my (%allusers,%listerror);
1.841     albertel 9353: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9354:  	    foreach my $tryserver (keys(%servers)) {
                   9355:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9356:                                   &escape($udom),$tryserver);
                   9357:                 if ($listing eq 'unknown_cmd') {
                   9358: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9359: 				      $udom, $tryserver);
                   9360:                 } else {
                   9361:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9362:                 }
1.841     albertel 9363: 		if ($listing eq 'unknown_cmd') {
                   9364: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9365: 				      $udom, $tryserver);
                   9366: 		    @listing_results = split(/:/,$listing);
                   9367: 		} else {
                   9368: 		    @listing_results =
                   9369: 			map { &unescape($_); } split(/:/,$listing);
                   9370: 		}
1.1136    raeburn  9371:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9372:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9373:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9374:                     $listerror{$tryserver} = $listing;
                   9375:                 } else {
1.841     albertel 9376: 		    foreach my $line (@listing_results) {
                   9377: 			my ($entry) = split(/&/,$line,2);
                   9378: 			$allusers{$entry} = 1;
                   9379: 		    }
                   9380: 		}
1.253     stredwic 9381:             }
1.1136    raeburn  9382:             my @alluserslist=();
1.800     albertel 9383:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9384:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9385:             }
1.1136    raeburn  9386:             return (\@alluserslist);
1.253     stredwic 9387:         } else {
1.1136    raeburn  9388:             return ([],'missing username');
1.253     stredwic 9389:         }
1.955     raeburn  9390:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9391:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9392:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9393:         return (\@all_domains);
1.955     raeburn  9394:     } else {
1.1136    raeburn  9395:         return ([],'missing domain');
1.275     stredwic 9396:     }
                   9397: }
                   9398: 
                   9399: # --------------------------------------------- GetFileTimestamp
                   9400: # This function utilizes dirlist and returns the date stamp for
                   9401: # when it was last modified.  It will also return an error of -1
                   9402: # if an error occurs
                   9403: 
                   9404: sub GetFileTimestamp {
1.955     raeburn  9405:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9406:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9407:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9408:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9409:                                     undef,$getuserdir);
                   9410:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9411:         return -1;
                   9412:     }
                   9413:     if (ref($fileref) eq 'ARRAY') {
                   9414:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9415:         # @stats contains first the filename, then the stat output
                   9416:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9417:     } else {
                   9418:         return -1;
1.253     stredwic 9419:     }
1.26      www      9420: }
                   9421: 
1.712     albertel 9422: sub stat_file {
                   9423:     my ($uri) = @_;
1.787     albertel 9424:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9425: 
1.955     raeburn  9426:     my ($udom,$uname,$file);
1.712     albertel 9427:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9428: 	($udom,$uname,$file) =
1.811     albertel 9429: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9430: 	$file = 'userfiles/'.$file;
                   9431:     }
                   9432:     if ($uri =~ m-^/res/-) {
                   9433: 	($udom,$uname) = 
1.807     albertel 9434: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9435: 	$file = $uri;
                   9436:     }
                   9437: 
                   9438:     if (!$udom || !$uname || !$file) {
                   9439: 	# unable to handle the uri
                   9440: 	return ();
                   9441:     }
1.956     raeburn  9442:     my $getpropath;
                   9443:     if ($file =~ /^userfiles\//) {
                   9444:         $getpropath = 1;
                   9445:     }
1.1136    raeburn  9446:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9447:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9448:         return ();
                   9449:     } else {
                   9450:         if (ref($listref) eq 'ARRAY') {
                   9451:             my @stats = split('&',$listref->[0]);
                   9452: 	    shift(@stats); #filename is first
                   9453: 	    return @stats;
                   9454:         }
1.712     albertel 9455:     }
                   9456:     return ();
                   9457: }
                   9458: 
1.26      www      9459: # -------------------------------------------------------- Value of a Condition
                   9460: 
1.713     albertel 9461: # gets the value of a specific preevaluated condition
                   9462: #    stored in the string  $env{user.state.<cid>}
                   9463: # or looks up a condition reference in the bighash and if if hasn't
                   9464: # already been evaluated recurses into docondval to get the value of
                   9465: # the condition, then memoizing it to 
                   9466: #   $env{user.state.<cid>.<condition>}
1.40      www      9467: sub directcondval {
                   9468:     my $number=shift;
1.620     albertel 9469:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9470: 	&Apache::lonuserstate::evalstate();
                   9471:     }
1.713     albertel 9472:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9473: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9474:     } elsif ($number =~ /^_/) {
                   9475: 	my $sub_condition;
                   9476: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9477: 		&GDBM_READER(),0640)) {
                   9478: 	    $sub_condition=$bighash{'conditions'.$number};
                   9479: 	    untie(%bighash);
                   9480: 	}
                   9481: 	my $value = &docondval($sub_condition);
1.949     raeburn  9482: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9483: 	return $value;
                   9484:     }
1.620     albertel 9485:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9486:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9487:     } else {
                   9488:        return 2;
                   9489:     }
                   9490: }
                   9491: 
1.713     albertel 9492: # get the collection of conditions for this resource
1.26      www      9493: sub condval {
                   9494:     my $condidx=shift;
1.54      www      9495:     my $allpathcond='';
1.713     albertel 9496:     foreach my $cond (split(/\|/,$condidx)) {
                   9497: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9498: 	    $allpathcond.=
                   9499: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9500: 	}
1.191     harris41 9501:     }
1.54      www      9502:     $allpathcond=~s/\|$//;
1.713     albertel 9503:     return &docondval($allpathcond);
                   9504: }
                   9505: 
                   9506: #evaluates an expression of conditions
                   9507: sub docondval {
                   9508:     my ($allpathcond) = @_;
                   9509:     my $result=0;
                   9510:     if ($env{'request.course.id'}
                   9511: 	&& defined($allpathcond)) {
                   9512: 	my $operand='|';
                   9513: 	my @stack;
                   9514: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9515: 	    if ($chunk eq '(') {
                   9516: 		push @stack,($operand,$result);
                   9517: 	    } elsif ($chunk eq ')') {
                   9518: 		my $before=pop @stack;
                   9519: 		if (pop @stack eq '&') {
                   9520: 		    $result=$result>$before?$before:$result;
                   9521: 		} else {
                   9522: 		    $result=$result>$before?$result:$before;
                   9523: 		}
                   9524: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9525: 		$operand=$chunk;
                   9526: 	    } else {
                   9527: 		my $new=directcondval($chunk);
                   9528: 		if ($operand eq '&') {
                   9529: 		    $result=$result>$new?$new:$result;
                   9530: 		} else {
                   9531: 		    $result=$result>$new?$result:$new;
                   9532: 		}
                   9533: 	    }
                   9534: 	}
1.26      www      9535:     }
                   9536:     return $result;
1.421     albertel 9537: }
                   9538: 
                   9539: # ---------------------------------------------------- Devalidate courseresdata
                   9540: 
                   9541: sub devalidatecourseresdata {
                   9542:     my ($coursenum,$coursedomain)=@_;
                   9543:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9544:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9545: }
                   9546: 
1.763     www      9547: 
1.200     www      9548: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9549: #
                   9550: #  Parameters:
                   9551: #      $coursenum    - Number of the course.
                   9552: #      $coursedomain - Domain at which the course was created.
                   9553: #  Returns:
                   9554: #     A hash of the course parameters along (I think) with timestamps
                   9555: #     and version info.
1.877     foxr     9556: 
1.624     albertel 9557: sub get_courseresdata {
                   9558:     my ($coursenum,$coursedomain)=@_;
1.200     www      9559:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9560:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9561:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9562:     my %dumpreply;
1.417     albertel 9563:     unless (defined($cached)) {
1.624     albertel 9564: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9565: 	$result=\%dumpreply;
1.251     albertel 9566: 	my ($tmp) = keys(%dumpreply);
                   9567: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9568: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9569: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9570: 	    return $tmp;
1.416     albertel 9571: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9572: 	    $result=undef;
1.599     albertel 9573: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9574: 	}
                   9575:     }
1.624     albertel 9576:     return $result;
                   9577: }
                   9578: 
1.633     albertel 9579: sub devalidateuserresdata {
                   9580:     my ($uname,$udom)=@_;
                   9581:     my $hashid="$udom:$uname";
                   9582:     &devalidate_cache_new('userres',$hashid);
                   9583: }
                   9584: 
1.624     albertel 9585: sub get_userresdata {
                   9586:     my ($uname,$udom)=@_;
                   9587:     #most student don\'t have any data set, check if there is some data
                   9588:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9589: 
                   9590:     my $hashid="$udom:$uname";
                   9591:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9592:     if (!defined($cached)) {
                   9593: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9594: 	$result=\%resourcedata;
                   9595: 	&do_cache_new('userres',$hashid,$result,600);
                   9596:     }
                   9597:     my ($tmp)=keys(%$result);
                   9598:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9599: 	return $result;
                   9600:     }
                   9601:     #error 2 occurs when the .db doesn't exist
                   9602:     if ($tmp!~/error: 2 /) {
1.672     albertel 9603: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9604: 		 " Trying to get resource data for ".
                   9605: 		 $uname." at ".$udom.": ".
                   9606: 		 $tmp."</font>");
                   9607:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9608: 	#&EXT_cache_set($udom,$uname);
                   9609: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9610: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9611:     }
                   9612:     return $tmp;
                   9613: }
1.879     foxr     9614: #----------------------------------------------- resdata - return resource data
                   9615: #  Purpose:
                   9616: #    Return resource data for either users or for a course.
                   9617: #  Parameters:
                   9618: #     $name      - Course/user name.
                   9619: #     $domain    - Name of the domain the user/course is registered on.
                   9620: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9621: #     @which     - Array of names of resources desired.
                   9622: #  Returns:
                   9623: #     The value of the first reasource in @which that is found in the
                   9624: #     resource hash.
                   9625: #  Exceptional Conditions:
                   9626: #     If the $type passed in is not valid (not the string 'course' or 
                   9627: #     'user', an undefined  reference is returned.
                   9628: #     If none of the resources are found, an undef is returned
1.624     albertel 9629: sub resdata {
                   9630:     my ($name,$domain,$type,@which)=@_;
                   9631:     my $result;
                   9632:     if ($type eq 'course') {
                   9633: 	$result=&get_courseresdata($name,$domain);
                   9634:     } elsif ($type eq 'user') {
                   9635: 	$result=&get_userresdata($name,$domain);
                   9636:     }
                   9637:     if (!ref($result)) { return $result; }    
1.251     albertel 9638:     foreach my $item (@which) {
1.927     albertel 9639: 	if (defined($result->{$item->[0]})) {
                   9640: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9641: 	}
1.250     albertel 9642:     }
1.291     albertel 9643:     return undef;
1.200     www      9644: }
                   9645: 
1.1236    raeburn  9646: sub get_numsuppfiles {
                   9647:     my ($cnum,$cdom,$ignorecache)=@_;
                   9648:     my $hashid=$cnum.':'.$cdom;
                   9649:     my ($suppcount,$cached);
                   9650:     unless ($ignorecache) {
                   9651:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9652:     }
                   9653:     unless (defined($cached)) {
                   9654:         my $chome=&homeserver($cnum,$cdom);
                   9655:         unless ($chome eq 'no_host') {
                   9656:             ($suppcount,my $errors) = (0,0);
                   9657:             my $suppmap = 'supplemental.sequence';
                   9658:             ($suppcount,$errors) = 
                   9659:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9660:         }
                   9661:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9662:     }
                   9663:     return $suppcount;
                   9664: }
                   9665: 
1.379     matthew  9666: #
                   9667: # EXT resource caching routines
                   9668: #
                   9669: 
                   9670: sub clear_EXT_cache_status {
1.383     albertel 9671:     &delenv('cache.EXT.');
1.379     matthew  9672: }
                   9673: 
                   9674: sub EXT_cache_status {
                   9675:     my ($target_domain,$target_user) = @_;
1.383     albertel 9676:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9677:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9678:         # We know already the user has no data
                   9679:         return 1;
                   9680:     } else {
                   9681:         return 0;
                   9682:     }
                   9683: }
                   9684: 
                   9685: sub EXT_cache_set {
                   9686:     my ($target_domain,$target_user) = @_;
1.383     albertel 9687:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9688:     #&appenv({$cachename => time});
1.379     matthew  9689: }
                   9690: 
1.28      www      9691: # --------------------------------------------------------- Value of a Variable
1.58      www      9692: sub EXT {
1.715     albertel 9693: 
1.1228    raeburn  9694:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9695:     unless ($varname) { return ''; }
1.218     albertel 9696:     #get real user name/domain, courseid and symb
                   9697:     my $courseid;
1.359     albertel 9698:     my $publicuser;
1.427     www      9699:     if ($symbparm) {
                   9700: 	$symbparm=&get_symb_from_alias($symbparm);
                   9701:     }
1.218     albertel 9702:     if (!($uname && $udom)) {
1.790     albertel 9703:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9704:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9705:     } else {
1.620     albertel 9706: 	$courseid=$env{'request.course.id'};
1.218     albertel 9707:     }
1.48      www      9708:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9709:     my $rest;
1.320     albertel 9710:     if (defined($therest[0])) {
1.48      www      9711:        $rest=join('.',@therest);
                   9712:     } else {
                   9713:        $rest='';
                   9714:     }
1.320     albertel 9715: 
1.57      www      9716:     my $qualifierrest=$qualifier;
                   9717:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9718:     my $spacequalifierrest=$space;
                   9719:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9720:     if ($realm eq 'user') {
1.48      www      9721: # --------------------------------------------------------------- user.resource
                   9722: 	if ($space eq 'resource') {
1.651     albertel 9723: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9724: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9725: 		 &&
1.744     albertel 9726: 		 ($symbparm eq &symbread()) ) {	
                   9727: 		# if we are in the middle of processing the resource the
                   9728: 		# get the value we are planning on committing
                   9729:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9730:                     return $Apache::lonhomework::results{$qualifierrest};
                   9731:                 } else {
                   9732:                     return $Apache::lonhomework::history{$qualifierrest};
                   9733:                 }
1.335     albertel 9734: 	    } else {
1.359     albertel 9735: 		my %restored;
1.620     albertel 9736: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9737: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9738: 		} else {
                   9739: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9740: 		}
1.335     albertel 9741: 		return $restored{$qualifierrest};
                   9742: 	    }
1.48      www      9743: # ----------------------------------------------------------------- user.access
                   9744:         } elsif ($space eq 'access') {
1.218     albertel 9745: 	    # FIXME - not supporting calls for a specific user
1.48      www      9746:             return &allowed($qualifier,$rest);
                   9747: # ------------------------------------------ user.preferences, user.environment
                   9748:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9749: 	    if (($uname eq $env{'user.name'}) &&
                   9750: 		($udom eq $env{'user.domain'})) {
                   9751: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9752: 	    } else {
1.359     albertel 9753: 		my %returnhash;
                   9754: 		if (!$publicuser) {
                   9755: 		    %returnhash=&userenvironment($udom,$uname,
                   9756: 						 $qualifierrest);
                   9757: 		}
1.218     albertel 9758: 		return $returnhash{$qualifierrest};
                   9759: 	    }
1.48      www      9760: # ----------------------------------------------------------------- user.course
                   9761:         } elsif ($space eq 'course') {
1.218     albertel 9762: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9763:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9764: # ------------------------------------------------------------------- user.role
                   9765:         } elsif ($space eq 'role') {
1.218     albertel 9766: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9767:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9768:             if ($qualifier eq 'value') {
                   9769: 		return $role;
                   9770:             } elsif ($qualifier eq 'extent') {
                   9771:                 return $where;
                   9772:             }
                   9773: # ----------------------------------------------------------------- user.domain
                   9774:         } elsif ($space eq 'domain') {
1.218     albertel 9775:             return $udom;
1.48      www      9776: # ------------------------------------------------------------------- user.name
                   9777:         } elsif ($space eq 'name') {
1.218     albertel 9778:             return $uname;
1.48      www      9779: # ---------------------------------------------------- Any other user namespace
1.29      www      9780:         } else {
1.359     albertel 9781: 	    my %reply;
                   9782: 	    if (!$publicuser) {
                   9783: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9784: 	    }
                   9785: 	    return $reply{$qualifierrest};
1.48      www      9786:         }
1.236     www      9787:     } elsif ($realm eq 'query') {
                   9788: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9789:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9790: 						[$spacequalifierrest]);
1.620     albertel 9791: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9792:    } elsif ($realm eq 'request') {
1.48      www      9793: # ------------------------------------------------------------- request.browser
                   9794:         if ($space eq 'browser') {
1.1145    bisitz   9795:             return $env{'browser.'.$qualifier};
1.57      www      9796: # ------------------------------------------------------------ request.filename
                   9797:         } else {
1.620     albertel 9798:             return $env{'request.'.$spacequalifierrest};
1.29      www      9799:         }
1.28      www      9800:     } elsif ($realm eq 'course') {
1.48      www      9801: # ---------------------------------------------------------- course.description
1.620     albertel 9802:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9803:     } elsif ($realm eq 'resource') {
1.165     www      9804: 
1.620     albertel 9805: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9806: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9807: 	}
1.693     albertel 9808: 
1.1232    raeburn  9809:         if ($qualifier eq '') {
                   9810: 	    if ($space eq 'title') {
                   9811: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9812: 	        return &gettitle($symbparm);
                   9813: 	    }
1.693     albertel 9814: 	
1.1232    raeburn  9815: 	    if ($space eq 'map') {
                   9816: 	        my ($map) = &decode_symb($symbparm);
                   9817: 	        return &symbread($map);
                   9818: 	    }
                   9819:             if ($space eq 'maptitle') {
                   9820:                 my ($map) = &decode_symb($symbparm);
                   9821:                 return &gettitle($map);
                   9822:             }
                   9823: 	    if ($space eq 'filename') {
                   9824: 	        if ($symbparm) {
                   9825: 		    return &clutter((&decode_symb($symbparm))[2]);
                   9826: 	        }
                   9827: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9828: 	    }
1.1232    raeburn  9829: 
1.1233    raeburn  9830:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   9831:                 if ($space eq 'visibleparts') {
                   9832:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9833:                     my $item;
                   9834:                     if (ref($navmap)) {
                   9835:                         my $res = $navmap->getBySymb($symbparm);
                   9836:                         my $parts = $res->parts();
                   9837:                         if (ref($parts) eq 'ARRAY') {
                   9838:                             $item = join(',',@{$parts});
                   9839:                         }
                   9840:                         undef($navmap);
1.1232    raeburn  9841:                     }
1.1233    raeburn  9842:                     return $item;
1.1232    raeburn  9843:                 }
                   9844:             }
                   9845:         }
1.693     albertel 9846: 
                   9847: 	my ($section, $group, @groups);
1.593     albertel 9848: 	my ($courselevelm,$courselevel);
1.1228    raeburn  9849:         if (($courseid eq '') && ($cid)) {
                   9850:             $courseid = $cid;
                   9851:         }
                   9852: 	if (($symbparm && $courseid) && 
                   9853: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      9854: 
1.218     albertel 9855: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9856: 
1.60      www      9857: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9858: 	    my $symbp=$symbparm;
1.735     albertel 9859: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9860: 
                   9861: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9862: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9863: 
1.620     albertel 9864: 	    if (($env{'user.name'} eq $uname) &&
                   9865: 		($env{'user.domain'} eq $udom)) {
                   9866: 		$section=$env{'request.course.sec'};
1.733     raeburn  9867:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9868:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9869: 	    } else {
1.539     albertel 9870: 		if (! defined($usection)) {
1.551     albertel 9871: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9872: 		} else {
                   9873: 		    $section = $usection;
                   9874: 		}
1.733     raeburn  9875:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9876: 	    }
                   9877: 
                   9878: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9879: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9880: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9881: 
1.593     albertel 9882: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9883: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9884: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9885: 
1.60      www      9886: # ----------------------------------------------------------- first, check user
1.624     albertel 9887: 
                   9888: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9889: 				       ([$courselevelr,'resource'],
                   9890: 					[$courselevelm,'map'     ],
                   9891: 					[$courselevel, 'course'  ]));
1.931     albertel 9892: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9893: 
1.594     albertel 9894: # ------------------------------------------------ second, check some of course
1.684     raeburn  9895:             my $coursereply;
1.691     raeburn  9896:             if (@groups > 0) {
                   9897:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9898:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9899:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9900:             }
1.96      www      9901: 
1.684     raeburn  9902: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9903: 				  $env{'course.'.$courseid.'.domain'},
                   9904: 				  'course',
                   9905: 				  ([$seclevelr,   'resource'],
                   9906: 				   [$seclevelm,   'map'     ],
                   9907: 				   [$seclevel,    'course'  ],
                   9908: 				   [$courselevelr,'resource']));
                   9909: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9910: 
1.60      www      9911: # ------------------------------------------------------ third, check map parms
1.218     albertel 9912: 	    my %parmhash=();
                   9913: 	    my $thisparm='';
                   9914: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9915: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9916: 		    &GDBM_READER(),0640)) {
1.218     albertel 9917: 		$thisparm=$parmhash{$symbparm};
                   9918: 		untie(%parmhash);
                   9919: 	    }
1.927     albertel 9920: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9921: 	}
1.594     albertel 9922: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9923: 
1.218     albertel 9924: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9925: 	my $filename;
                   9926: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9927: 	if ($symbparm) {
1.409     www      9928: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9929: 	} else {
1.620     albertel 9930: 	    $filename=$env{'request.filename'};
1.282     albertel 9931: 	}
                   9932: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9933: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9934: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9935: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9936: 
1.927     albertel 9937: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9938: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9939: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9940: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9941: 				     $env{'course.'.$courseid.'.domain'},
                   9942: 				     'course',
1.927     albertel 9943: 				     ([$courselevelm,'map'   ],
                   9944: 				      [$courselevel, 'course']));
                   9945: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9946: 	}
1.145     www      9947: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9948: 	unless ($space eq '0') {
1.336     albertel 9949: 	    my @parts=split(/_/,$space);
                   9950: 	    my $id=pop(@parts);
                   9951: 	    my $part=join('_',@parts);
                   9952: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9953: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9954: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9955: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9956: 	}
1.395     albertel 9957: 	if ($recurse) { return undef; }
                   9958: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9959: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9960: # ---------------------------------------------------- Any other user namespace
                   9961:     } elsif ($realm eq 'environment') {
                   9962: # ----------------------------------------------------------------- environment
1.620     albertel 9963: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9964: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9965: 	} else {
1.770     albertel 9966: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9967: 		return '';
                   9968: 	    }
1.219     albertel 9969: 	    my %returnhash=&userenvironment($udom,$uname,
                   9970: 					    $spacequalifierrest);
                   9971: 	    return $returnhash{$spacequalifierrest};
                   9972: 	}
1.28      www      9973:     } elsif ($realm eq 'system') {
1.48      www      9974: # ----------------------------------------------------------------- system.time
                   9975: 	if ($space eq 'time') {
                   9976: 	    return time;
                   9977:         }
1.696     albertel 9978:     } elsif ($realm eq 'server') {
                   9979: # ----------------------------------------------------------------- system.time
                   9980: 	if ($space eq 'name') {
                   9981: 	    return $ENV{'SERVER_NAME'};
                   9982:         }
1.28      www      9983:     }
1.48      www      9984:     return '';
1.61      www      9985: }
                   9986: 
1.927     albertel 9987: sub get_reply {
                   9988:     my ($reply_value) = @_;
1.940     raeburn  9989:     if (ref($reply_value) eq 'ARRAY') {
                   9990:         if (wantarray) {
                   9991: 	    return @$reply_value;
                   9992:         }
                   9993:         return $reply_value->[0];
                   9994:     } else {
                   9995:         return $reply_value;
1.927     albertel 9996:     }
                   9997: }
                   9998: 
1.691     raeburn  9999: sub check_group_parms {
                   10000:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10001:     my @groupitems = ();
                   10002:     my $resultitem;
1.927     albertel 10003:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10004:     foreach my $group (@{$groups}) {
                   10005:         foreach my $level (@levels) {
1.927     albertel 10006:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10007:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10008:         }
                   10009:     }
                   10010:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10011:                             $env{'course.'.$courseid.'.domain'},
                   10012:                                      'course',@groupitems);
                   10013:     return $coursereply;
                   10014: }
                   10015: 
                   10016: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10017:     my ($courseid,@groups) = @_;
                   10018:     @groups = sort(@groups);
1.691     raeburn  10019:     return @groups;
                   10020: }
                   10021: 
1.395     albertel 10022: sub packages_tab_default {
                   10023:     my ($uri,$varname)=@_;
                   10024:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10025: 
                   10026:     my (@extension,@specifics,$do_default);
                   10027:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10028: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10029: 	if ($pack_type eq 'default') {
                   10030: 	    $do_default=1;
                   10031: 	} elsif ($pack_type eq 'extension') {
                   10032: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10033: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10034: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10035: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10036: 	}
                   10037:     }
                   10038:     # first look for a package that matches the requested part id
                   10039:     foreach my $package (@specifics) {
                   10040: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10041: 	next if ($pack_part ne $part);
                   10042: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10043: 	    return $packagetab{"$pack_type&$name&default"};
                   10044: 	}
                   10045:     }
                   10046:     # look for any possible matching non extension_ package
                   10047:     foreach my $package (@specifics) {
                   10048: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10049: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10050: 	    return $packagetab{"$pack_type&$name&default"};
                   10051: 	}
1.585     albertel 10052: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10053: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10054: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10055: 	}
                   10056:     }
1.738     albertel 10057:     # look for any posible extension_ match
                   10058:     foreach my $package (@extension) {
                   10059: 	my ($package,$pack_type)=@{$package};
                   10060: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10061: 	    return $packagetab{"$pack_type&$name&default"};
                   10062: 	}
                   10063: 	if (defined($packagetab{$package."&$name&default"})) {
                   10064: 	    return $packagetab{$package."&$name&default"};
                   10065: 	}
                   10066:     }
                   10067:     # look for a global default setting
                   10068:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10069: 	return $packagetab{"default&$name&default"};
                   10070:     }
1.395     albertel 10071:     return undef;
                   10072: }
                   10073: 
1.334     albertel 10074: sub add_prefix_and_part {
                   10075:     my ($prefix,$part)=@_;
                   10076:     my $keyroot;
                   10077:     if (defined($prefix) && $prefix !~ /^__/) {
                   10078: 	# prefix that has a part already
                   10079: 	$keyroot=$prefix;
                   10080:     } elsif (defined($prefix)) {
                   10081: 	# prefix that is missing a part
                   10082: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10083:     } else {
                   10084: 	# no prefix at all
                   10085: 	if (defined($part)) { $keyroot='_'.$part; }
                   10086:     }
                   10087:     return $keyroot;
                   10088: }
                   10089: 
1.71      www      10090: # ---------------------------------------------------------------- Get metadata
                   10091: 
1.599     albertel 10092: my %metaentry;
1.1070    www      10093: my %importedpartids;
1.71      www      10094: sub metadata {
1.176     www      10095:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10096:     $uri=&declutter($uri);
1.288     albertel 10097:     # if it is a non metadata possible uri return quickly
1.529     albertel 10098:     if (($uri eq '') || 
                   10099: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10100: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10101:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10102: 	return undef;
                   10103:     }
1.1140    www      10104:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10105: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10106: 	return undef;
1.288     albertel 10107:     }
1.73      www      10108:     my $filename=$uri;
                   10109:     $uri=~s/\.meta$//;
1.172     www      10110: #
                   10111: # Is the metadata already cached?
1.177     www      10112: # Look at timestamp of caching
1.172     www      10113: # Everything is cached by the main uri, libraries are never directly cached
                   10114: #
1.428     albertel 10115:     if (!defined($liburi)) {
1.599     albertel 10116: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10117: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10118:     }
                   10119:     {
1.1069    www      10120: # Imported parts would go here
1.1070    www      10121:         my %importedids=();
                   10122:         my @origfileimportpartids=();
1.1069    www      10123:         my $importedparts=0;
1.172     www      10124: #
                   10125: # Is this a recursive call for a library?
                   10126: #
1.599     albertel 10127: #	if (! exists($metacache{$uri})) {
                   10128: #	    $metacache{$uri}={};
                   10129: #	}
1.924     albertel 10130: 	my $cachetime = 60*60;
1.171     www      10131:         if ($liburi) {
                   10132: 	    $liburi=&declutter($liburi);
                   10133:             $filename=$liburi;
1.401     bowersj2 10134:         } else {
1.599     albertel 10135: 	    &devalidate_cache_new('meta',$uri);
                   10136: 	    undef(%metaentry);
1.401     bowersj2 10137: 	}
1.140     www      10138:         my %metathesekeys=();
1.73      www      10139:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10140: 	my $metastring;
1.1140    www      10141: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10142: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10143: 	    $metastring = 
1.929     albertel 10144: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10145: 					  ('grade_target' => 'meta'));
                   10146: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10147: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10148:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10149: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10150: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10151: 	    $metastring=&getfile($file);
1.489     albertel 10152: 	}
1.208     albertel 10153:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10154:         my $token;
1.140     www      10155:         undef %metathesekeys;
1.71      www      10156:         while ($token=$parser->get_token) {
1.339     albertel 10157: 	    if ($token->[0] eq 'S') {
                   10158: 		if (defined($token->[2]->{'package'})) {
1.172     www      10159: #
                   10160: # This is a package - get package info
                   10161: #
1.339     albertel 10162: 		    my $package=$token->[2]->{'package'};
                   10163: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10164: 		    if (defined($token->[2]->{'id'})) { 
                   10165: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10166: 		    }
1.599     albertel 10167: 		    if ($metaentry{':packages'}) {
                   10168: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10169: 		    } else {
1.599     albertel 10170: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10171: 		    }
1.736     albertel 10172: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10173: 			my $part=$keyroot;
                   10174: 			$part=~s/^\_//;
1.736     albertel 10175: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10176: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10177: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10178: 			    # ignore package.tab specified default values
                   10179:                             # here &package_tab_default() will fetch those
                   10180: 			    if ($subp eq 'default') { next; }
1.736     albertel 10181: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10182: 			    my $unikey;
                   10183: 			    if ($pack =~ /_0$/) {
                   10184: 				$unikey='parameter_0_'.$name;
                   10185: 				$part=0;
                   10186: 			    } else {
                   10187: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10188: 			    }
1.339     albertel 10189: 			    if ($subp eq 'display') {
                   10190: 				$value.=' [Part: '.$part.']';
                   10191: 			    }
1.599     albertel 10192: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10193: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10194: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10195: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10196: 			    }
1.599     albertel 10197: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10198: 				$metaentry{':'.$unikey}=
                   10199: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10200: 			    }
1.339     albertel 10201: 			}
                   10202: 		    }
                   10203: 		} else {
1.172     www      10204: #
                   10205: # This is not a package - some other kind of start tag
1.339     albertel 10206: #
                   10207: 		    my $entry=$token->[1];
1.1068    www      10208: 		    my $unikey='';
1.175     www      10209: 
1.339     albertel 10210: 		    if ($entry eq 'import') {
1.175     www      10211: #
                   10212: # Importing a library here
1.339     albertel 10213: #
1.1067    www      10214:                         my $location=$parser->get_text('/import');
                   10215:                         my $dir=$filename;
                   10216:                         $dir=~s|[^/]*$||;
                   10217:                         $location=&filelocation($dir,$location);
1.1069    www      10218:                        
1.1068    www      10219:                         my $importmode=$token->[2]->{'importmode'};
                   10220:                         if ($importmode eq 'problem') {
1.1069    www      10221: # Import as problem/response
1.1068    www      10222:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10223:                         } elsif ($importmode eq 'part') {
                   10224: # Import as part(s)
1.1069    www      10225:                            $importedparts=1;
                   10226: # We need to get the original file and the imported file to get the part order correct
                   10227: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10228: # Load and inspect original file
1.1070    www      10229:                            if ($#origfileimportpartids<0) {
                   10230:                               undef(%importedpartids);
                   10231:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10232:                               my $origfile=&getfile($origfilelocation);
                   10233:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10234:                            }
                   10235: 
1.1069    www      10236: # Load and inspect imported file
                   10237:                            my $impfile=&getfile($location);
                   10238:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10239:                            if ($#impfilepartids>=0) {
                   10240: # This problem had parts
1.1070    www      10241:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10242:                            } else {
                   10243: # Importing by turning a single problem into a problem part
                   10244: # It gets the import-tags ID as part-ID
                   10245:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10246:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10247:                            }
1.1068    www      10248:                         } else {
                   10249: # Normal import
                   10250:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10251:                            if (defined($token->[2]->{'id'})) {
                   10252:                               $unikey.='_'.$token->[2]->{'id'};
                   10253:                            }
1.1067    www      10254:                         }
                   10255: 
1.339     albertel 10256: 			if ($depthcount<20) {
1.736     albertel 10257: 			    my $metadata = 
                   10258: 				&metadata($uri,'keys', $location,$unikey,
                   10259: 					  $depthcount+1);
                   10260: 			    foreach my $meta (split(',',$metadata)) {
                   10261: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10262: 				$metathesekeys{$meta}=1;
1.339     albertel 10263: 			    }
1.1068    www      10264: 			
                   10265:                         }
1.1067    www      10266: 		    } else {
                   10267: #
                   10268: # Not importing, some other kind of non-package, non-library start tag
                   10269: # 
                   10270:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10271:                         if (defined($token->[2]->{'id'})) {
                   10272:                             $unikey.='_'.$token->[2]->{'id'};
                   10273:                         }
1.339     albertel 10274: 			if (defined($token->[2]->{'name'})) { 
                   10275: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10276: 			}
                   10277: 			$metathesekeys{$unikey}=1;
1.736     albertel 10278: 			foreach my $param (@{$token->[3]}) {
                   10279: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10280: 				$token->[2]->{$param};
1.339     albertel 10281: 			}
                   10282: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10283: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10284: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10285: 		 # only ws inside the tag, and not in default, so use default
                   10286: 		 # as value
1.599     albertel 10287: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10288: 			} elsif ( $internaltext =~ /\S/ ) {
                   10289: 		  # something interesting inside the tag
                   10290: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10291: 			} else {
1.908     albertel 10292: 		  # no interesting values, don't set a default
1.339     albertel 10293: 			}
1.172     www      10294: # end of not-a-package not-a-library import
1.339     albertel 10295: 		    }
1.172     www      10296: # end of not-a-package start tag
1.339     albertel 10297: 		}
1.172     www      10298: # the next is the end of "start tag"
1.339     albertel 10299: 	    }
                   10300: 	}
1.483     albertel 10301: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10302: 	$extension = lc($extension);
                   10303: 	if ($extension eq 'htm') { $extension='html'; }
                   10304: 
1.737     albertel 10305: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10306: 	    #no specific packages #how's our extension
                   10307: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10308: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10309: 					 \%metathesekeys);
                   10310: 	}
1.883     albertel 10311: 
                   10312: 	if (!exists($metaentry{':packages'})
                   10313: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10314: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10315: 		#no specific packages well let's get default then
                   10316: 		if ($key!~/^default&/) { next; }
1.488     albertel 10317: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10318: 					     \%metathesekeys);
                   10319: 	    }
                   10320: 	}
1.338     www      10321: # are there custom rights to evaluate
1.599     albertel 10322: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10323: 
1.338     www      10324:     #
                   10325:     # Importing a rights file here
1.339     albertel 10326:     #
                   10327: 	    unless ($depthcount) {
1.599     albertel 10328: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10329: 		my $dir=$filename;
                   10330: 		$dir=~s|[^/]*$||;
                   10331: 		$location=&filelocation($dir,$location);
1.736     albertel 10332: 		my $rights_metadata =
                   10333: 		    &metadata($uri,'keys',$location,'_rights',
                   10334: 			      $depthcount+1);
                   10335: 		foreach my $rights (split(',',$rights_metadata)) {
                   10336: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10337: 		    $metathesekeys{$rights}=1;
1.339     albertel 10338: 		}
                   10339: 	    }
                   10340: 	}
1.737     albertel 10341: 	# uniqifiy package listing
                   10342: 	my %seen;
                   10343: 	my @uniq_packages =
                   10344: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10345: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10346: 
1.1070    www      10347:         if ($importedparts) {
                   10348: # We had imported parts and need to rebuild partorder
                   10349:            $metaentry{':partorder'}='';
                   10350:            $metathesekeys{'partorder'}=1;
                   10351:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10352:                if ($origfileimportpartids[$index] eq 'part') {
                   10353: # original part, part of the problem
                   10354:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10355:                } else {
                   10356: # we have imported parts at this position
                   10357:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10358:                }
                   10359:            }
                   10360:            $metaentry{':partorder'}=~s/^\,//;
                   10361:         }
                   10362: 
1.737     albertel 10363: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10364: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10365: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10366: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10367: # this is the end of "was not already recently cached
1.71      www      10368:     }
1.599     albertel 10369:     return $metaentry{':'.$what};
1.261     albertel 10370: }
                   10371: 
1.488     albertel 10372: sub metadata_create_package_def {
1.483     albertel 10373:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10374:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10375:     if ($subp eq 'default') { next; }
                   10376:     
1.599     albertel 10377:     if (defined($metaentry{':packages'})) {
                   10378: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10379:     } else {
1.599     albertel 10380: 	$metaentry{':packages'}=$package;
1.483     albertel 10381:     }
                   10382:     my $value=$packagetab{$key};
                   10383:     my $unikey;
                   10384:     $unikey='parameter_0_'.$name;
1.599     albertel 10385:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10386:     $$metathesekeys{$unikey}=1;
1.599     albertel 10387:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10388: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10389:     }
1.599     albertel 10390:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10391: 	$metaentry{':'.$unikey}=
                   10392: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10393:     }
                   10394: }
                   10395: 
1.261     albertel 10396: sub metadata_generate_part0 {
                   10397:     my ($metadata,$metacache,$uri) = @_;
                   10398:     my %allnames;
1.737     albertel 10399:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10400: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10401: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10402: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10403: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10404: 	    $allnames{$name}=$part;
                   10405: 	  }
                   10406: 	}
                   10407:     }
                   10408:     foreach my $name (keys(%allnames)) {
                   10409:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10410:       my $key=":parameter_0_$name";
1.261     albertel 10411:       $$metacache{"$key.part"}='0';
                   10412:       $$metacache{"$key.name"}=$name;
1.428     albertel 10413:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10414: 					   $allnames{$name}.'_'.$name.
                   10415: 					   '.type'};
1.428     albertel 10416:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10417: 			     '.display'};
1.644     www      10418:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10419:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10420:       $$metacache{"$key.display"}=$olddis;
                   10421:     }
1.71      www      10422: }
                   10423: 
1.764     albertel 10424: # ------------------------------------------------------ Devalidate title cache
                   10425: 
                   10426: sub devalidate_title_cache {
                   10427:     my ($url)=@_;
                   10428:     if (!$env{'request.course.id'}) { return; }
                   10429:     my $symb=&symbread($url);
                   10430:     if (!$symb) { return; }
                   10431:     my $key=$env{'request.course.id'}."\0".$symb;
                   10432:     &devalidate_cache_new('title',$key);
                   10433: }
                   10434: 
1.1014    droeschl 10435: # ------------------------------------------------- Get the title of a course
                   10436: 
                   10437: sub current_course_title {
                   10438:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10439: }
1.301     www      10440: # ------------------------------------------------- Get the title of a resource
                   10441: 
                   10442: sub gettitle {
                   10443:     my $urlsymb=shift;
                   10444:     my $symb=&symbread($urlsymb);
1.534     albertel 10445:     if ($symb) {
1.620     albertel 10446: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10447: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10448: 	if (defined($cached)) { 
                   10449: 	    return $result;
                   10450: 	}
1.534     albertel 10451: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10452: 	my $title='';
1.907     albertel 10453: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10454: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10455: 	} else {
                   10456: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10457: 		    &GDBM_READER(),0640)) {
                   10458: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10459: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10460: 		untie(%bighash);
                   10461: 	    }
1.534     albertel 10462: 	}
                   10463: 	$title=~s/\&colon\;/\:/gs;
                   10464: 	if ($title) {
1.1159    www      10465: # Remember both $symb and $title for dynamic metadata
                   10466:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10467:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10468: # Cache this title and then return it
1.599     albertel 10469: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10470: 	}
                   10471: 	$urlsymb=$url;
                   10472:     }
                   10473:     my $title=&metadata($urlsymb,'title');
                   10474:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10475:     return $title;
1.301     www      10476: }
1.613     albertel 10477: 
1.614     albertel 10478: sub get_slot {
                   10479:     my ($which,$cnum,$cdom)=@_;
                   10480:     if (!$cnum || !$cdom) {
1.790     albertel 10481: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10482: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10483: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10484:     }
1.703     albertel 10485:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10486:     my %slotinfo;
                   10487:     if (exists($remembered{$key})) {
                   10488: 	$slotinfo{$which} = $remembered{$key};
                   10489:     } else {
                   10490: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10491: 	&Apache::lonhomework::showhash(%slotinfo);
                   10492: 	my ($tmp)=keys(%slotinfo);
                   10493: 	if ($tmp=~/^error:/) { return (); }
                   10494: 	$remembered{$key} = $slotinfo{$which};
                   10495:     }
1.616     albertel 10496:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10497: 	return %{$slotinfo{$which}};
                   10498:     }
                   10499:     return $slotinfo{$which};
1.614     albertel 10500: }
1.1150    raeburn  10501: 
                   10502: sub get_reservable_slots {
                   10503:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10504:     my $now = time;
                   10505:     my $reservable_info;
                   10506:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10507:     if (exists($remembered{$key})) {
                   10508:         $reservable_info = $remembered{$key};
                   10509:     } else {
                   10510:         my %resv;
                   10511:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10512:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10513:         $reservable_info = \%resv;
                   10514:         $remembered{$key} = $reservable_info;
                   10515:     }
                   10516:     return $reservable_info;
                   10517: }
                   10518: 
                   10519: sub get_course_slots {
                   10520:     my ($cnum,$cdom) = @_;
                   10521:     my $hashid=$cnum.':'.$cdom;
                   10522:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10523:     if (defined($cached)) {
                   10524:         if (ref($result) eq 'HASH') {
                   10525:             return %{$result};
                   10526:         }
                   10527:     } else {
                   10528:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10529:         my ($tmp) = keys(%slots);
                   10530:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10531:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10532:             return %slots;
                   10533:         }
                   10534:     }
                   10535:     return;
                   10536: }
                   10537: 
                   10538: sub devalidate_slots_cache {
                   10539:     my ($cnum,$cdom)=@_;
                   10540:     my $hashid=$cnum.':'.$cdom;
                   10541:     &devalidate_cache_new('allslots',$hashid);
                   10542: }
                   10543: 
1.1181    raeburn  10544: sub get_coursechange {
                   10545:     my ($cdom,$cnum) = @_;
                   10546:     if ($cdom eq '' || $cnum eq '') {
                   10547:         return unless ($env{'request.course.id'});
                   10548:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10549:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10550:     }
                   10551:     my $hashid=$cdom.'_'.$cnum;
                   10552:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10553:     if ((defined($cached)) && ($change ne '')) {
                   10554:         return $change;
                   10555:     } else {
                   10556:         my %crshash;
                   10557:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10558:         if ($crshash{'internal.contentchange'} eq '') {
                   10559:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10560:             if ($change eq '') {
                   10561:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10562:                 $change = $crshash{'internal.created'};
                   10563:             }
                   10564:         } else {
                   10565:             $change = $crshash{'internal.contentchange'};
                   10566:         }
                   10567:         my $cachetime = 600;
                   10568:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10569:     }
                   10570:     return $change;
                   10571: }
                   10572: 
                   10573: sub devalidate_coursechange_cache {
                   10574:     my ($cnum,$cdom)=@_;
                   10575:     my $hashid=$cnum.':'.$cdom;
                   10576:     &devalidate_cache_new('crschange',$hashid);
                   10577: }
                   10578: 
1.31      www      10579: # ------------------------------------------------- Update symbolic store links
                   10580: 
                   10581: sub symblist {
                   10582:     my ($mapname,%newhash)=@_;
1.438     www      10583:     $mapname=&deversion(&declutter($mapname));
1.31      www      10584:     my %hash;
1.620     albertel 10585:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10586:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10587:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10588: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10589: 		next if ($url eq 'last_known'
                   10590: 			 && $env{'form.no_update_last_known'});
                   10591: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10592: 						    $newhash{$url}->[1],
                   10593: 						    $newhash{$url}->[0]);
1.191     harris41 10594:             }
1.31      www      10595:             if (untie(%hash)) {
                   10596: 		return 'ok';
                   10597:             }
                   10598:         }
                   10599:     }
                   10600:     return 'error';
1.212     www      10601: }
                   10602: 
                   10603: # --------------------------------------------------------------- Verify a symb
                   10604: 
                   10605: sub symbverify {
1.1190    raeburn  10606:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10607:     my $thisfn=$thisurl;
1.439     www      10608:     $thisfn=&declutter($thisfn);
1.215     www      10609: # direct jump to resource in page or to a sequence - will construct own symbs
                   10610:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10611: # check URL part
1.409     www      10612:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10613: 
1.431     www      10614:     unless ($url eq $thisfn) { return 0; }
1.213     www      10615: 
1.216     www      10616:     $symb=&symbclean($symb);
1.510     www      10617:     $thisurl=&deversion($thisurl);
1.439     www      10618:     $thisfn=&deversion($thisfn);
1.213     www      10619: 
                   10620:     my %bighash;
                   10621:     my $okay=0;
1.431     www      10622: 
1.620     albertel 10623:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10624:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10625:         my $noclutter;
1.1032    raeburn  10626:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10627:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10628:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10629:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10630:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10631:                 $noclutter = 1;
                   10632:             }
                   10633:         }
                   10634:         my $ids;
                   10635:         if ($noclutter) {
                   10636:             $ids=$bighash{'ids_'.$thisurl};
                   10637:         } else {
                   10638:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10639:         }
1.1102    raeburn  10640:         unless ($ids) {
                   10641:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10642:             $ids=$bighash{$idkey};
1.216     www      10643:         }
                   10644:         if ($ids) {
                   10645: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10646:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10647:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10648:             }
1.800     albertel 10649: 	    foreach my $id (split(/\,/,$ids)) {
                   10650: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10651:                if (
                   10652:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10653:    eq $symb) {
                   10654:                    if (ref($encstate)) {
                   10655:                        $$encstate = $bighash{'encrypted_'.$id};
                   10656:                    }
1.620     albertel 10657: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10658: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10659:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10660: 		       $okay=1;
1.1202    raeburn  10661:                        last;
1.582     albertel 10662: 		   }
                   10663: 	       }
1.216     www      10664: 	   }
                   10665:         }
1.213     www      10666: 	untie(%bighash);
                   10667:     }
                   10668:     return $okay;
1.31      www      10669: }
                   10670: 
1.210     www      10671: # --------------------------------------------------------------- Clean-up symb
                   10672: 
                   10673: sub symbclean {
                   10674:     my $symb=shift;
1.568     albertel 10675:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10676: # remove version from map
                   10677:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10678: 
1.210     www      10679: # remove version from URL
                   10680:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10681: 
1.507     www      10682: # remove wrapper
                   10683: 
1.510     www      10684:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10685:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10686:     return $symb;
1.409     www      10687: }
                   10688: 
                   10689: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10690: 
                   10691: sub encode_symb {
                   10692:     my ($map,$resid,$url)=@_;
                   10693:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10694: }
1.409     www      10695: 
                   10696: sub decode_symb {
1.568     albertel 10697:     my $symb=shift;
                   10698:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10699:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10700:     return (&fixversion($map),$resid,&fixversion($url));
                   10701: }
                   10702: 
                   10703: sub fixversion {
                   10704:     my $fn=shift;
1.609     banghart 10705:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10706:     my %bighash;
                   10707:     my $uri=&clutter($fn);
1.620     albertel 10708:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10709: # is this cached?
1.599     albertel 10710:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10711:     if (defined($cached)) { return $result; }
                   10712: # unfortunately not cached, or expired
1.620     albertel 10713:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10714: 	    &GDBM_READER(),0640)) {
                   10715:  	if ($bighash{'version_'.$uri}) {
                   10716:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10717:  	    unless (($version eq 'mostrecent') || 
                   10718: 		    ($version==&getversion($uri))) {
1.440     www      10719:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10720:  	    }
                   10721:  	}
                   10722:  	untie %bighash;
1.413     www      10723:     }
1.599     albertel 10724:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10725: }
                   10726: 
                   10727: sub deversion {
                   10728:     my $url=shift;
                   10729:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10730:     return $url;
1.210     www      10731: }
                   10732: 
1.31      www      10733: # ------------------------------------------------------ Return symb list entry
                   10734: 
                   10735: sub symbread {
1.249     www      10736:     my ($thisfn,$donotrecurse)=@_;
1.1206    raeburn  10737:     my $cache_str;
                   10738:     if ($thisfn ne '') {
                   10739:         $cache_str='request.symbread.cached.'.$thisfn;
                   10740:         if ($env{$cache_str} ne '') {
1.1179    raeburn  10741:             return $env{$cache_str};
                   10742:         }
1.1206    raeburn  10743:     } else {
1.242     www      10744: # no filename provided? try from environment
1.620     albertel 10745:         if ($env{'request.symb'}) {
                   10746: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10747: 	}
1.620     albertel 10748: 	$thisfn=$env{'request.filename'};
1.44      www      10749:     }
1.569     albertel 10750:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10751: # is that filename actually a symb? Verify, clean, and return
                   10752:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10753: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10754: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10755: 	}
1.242     www      10756:     }
1.44      www      10757:     $thisfn=declutter($thisfn);
1.31      www      10758:     my %hash;
1.37      www      10759:     my %bighash;
                   10760:     my $syval='';
1.620     albertel 10761:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10762:         my $targetfn = $thisfn;
1.609     banghart 10763:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10764:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10765:         }
1.687     albertel 10766: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10767: 	    $targetfn=$1;
                   10768: 	}
1.620     albertel 10769:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10770:                       &GDBM_READER(),0640)) {
1.481     raeburn  10771: 	    $syval=$hash{$targetfn};
1.37      www      10772:             untie(%hash);
                   10773:         }
                   10774: # ---------------------------------------------------------- There was an entry
                   10775:         if ($syval) {
1.601     albertel 10776: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10777: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10778: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10779: 		    #return $env{$cache_str}='';
1.601     albertel 10780: 		#}    
                   10781: 		#$syval.=$1;
                   10782: 	    #}
1.37      www      10783:         } else {
                   10784: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10785:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10786:                             &GDBM_READER(),0640)) {
1.37      www      10787: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10788:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10789:               unless ($ids) { 
                   10790:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10791:               }
                   10792:               unless ($ids) {
                   10793: # alias?
                   10794: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10795:               }
1.37      www      10796:               if ($ids) {
                   10797: # ------------------------------------------------------------------- Has ID(s)
                   10798:                  my @possibilities=split(/\,/,$ids);
1.39      www      10799:                  if ($#possibilities==0) {
                   10800: # ----------------------------------------------- There is only one possibility
1.37      www      10801: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10802: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10803: 						    $resid,$thisfn);
1.249     www      10804:                  } elsif (!$donotrecurse) {
1.39      www      10805: # ------------------------------------------ There is more than one possibility
                   10806:                      my $realpossible=0;
1.800     albertel 10807:                      foreach my $id (@possibilities) {
                   10808: 			 my $file=$bighash{'src_'.$id};
1.39      www      10809:                          if (&allowed('bre',$file)) {
1.800     albertel 10810:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10811:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10812: 				$realpossible++;
1.626     albertel 10813:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10814: 						    $resid,$thisfn);
1.39      www      10815:                             }
                   10816: 			 }
1.191     harris41 10817:                      }
1.39      www      10818: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10819:                  } else {
                   10820:                      $syval='';
1.37      www      10821:                  }
                   10822: 	      }
                   10823:               untie(%bighash)
1.481     raeburn  10824:            }
1.31      www      10825:         }
1.62      www      10826:         if ($syval) {
1.620     albertel 10827: 	    return $env{$cache_str}=$syval;
1.62      www      10828:         }
1.31      www      10829:     }
1.949     raeburn  10830:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10831:     return $env{$cache_str}='';
1.31      www      10832: }
                   10833: 
                   10834: # ---------------------------------------------------------- Return random seed
                   10835: 
1.32      www      10836: sub numval {
                   10837:     my $txt=shift;
                   10838:     $txt=~tr/A-J/0-9/;
                   10839:     $txt=~tr/a-j/0-9/;
                   10840:     $txt=~tr/K-T/0-9/;
                   10841:     $txt=~tr/k-t/0-9/;
                   10842:     $txt=~tr/U-Z/0-5/;
                   10843:     $txt=~tr/u-z/0-5/;
                   10844:     $txt=~s/\D//g;
1.564     albertel 10845:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10846:     return int($txt);
1.368     albertel 10847: }
                   10848: 
1.484     albertel 10849: sub numval2 {
                   10850:     my $txt=shift;
                   10851:     $txt=~tr/A-J/0-9/;
                   10852:     $txt=~tr/a-j/0-9/;
                   10853:     $txt=~tr/K-T/0-9/;
                   10854:     $txt=~tr/k-t/0-9/;
                   10855:     $txt=~tr/U-Z/0-5/;
                   10856:     $txt=~tr/u-z/0-5/;
                   10857:     $txt=~s/\D//g;
                   10858:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10859:     my $total;
                   10860:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10861:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10862:     return int($total);
                   10863: }
                   10864: 
1.575     albertel 10865: sub numval3 {
                   10866:     use integer;
                   10867:     my $txt=shift;
                   10868:     $txt=~tr/A-J/0-9/;
                   10869:     $txt=~tr/a-j/0-9/;
                   10870:     $txt=~tr/K-T/0-9/;
                   10871:     $txt=~tr/k-t/0-9/;
                   10872:     $txt=~tr/U-Z/0-5/;
                   10873:     $txt=~tr/u-z/0-5/;
                   10874:     $txt=~s/\D//g;
                   10875:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10876:     my $total;
                   10877:     foreach my $val (@txts) { $total+=$val; }
                   10878:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10879:     return $total;
                   10880: }
                   10881: 
1.675     albertel 10882: sub digest {
                   10883:     my ($data)=@_;
                   10884:     my $digest=&Digest::MD5::md5($data);
                   10885:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10886:     my ($e,$f);
                   10887:     {
                   10888:         use integer;
                   10889:         $e=($a+$b);
                   10890:         $f=($c+$d);
                   10891:         if ($_64bit) {
                   10892:             $e=(($e<<32)>>32);
                   10893:             $f=(($f<<32)>>32);
                   10894:         }
                   10895:     }
                   10896:     if (wantarray) {
                   10897: 	return ($e,$f);
                   10898:     } else {
                   10899: 	my $g;
                   10900: 	{
                   10901: 	    use integer;
                   10902: 	    $g=($e+$f);
                   10903: 	    if ($_64bit) {
                   10904: 		$g=(($g<<32)>>32);
                   10905: 	    }
                   10906: 	}
                   10907: 	return $g;
                   10908:     }
                   10909: }
                   10910: 
1.368     albertel 10911: sub latest_rnd_algorithm_id {
1.675     albertel 10912:     return '64bit5';
1.366     albertel 10913: }
1.32      www      10914: 
1.503     albertel 10915: sub get_rand_alg {
                   10916:     my ($courseid)=@_;
1.790     albertel 10917:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10918:     if ($courseid) {
1.620     albertel 10919: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10920:     }
                   10921:     return &latest_rnd_algorithm_id();
                   10922: }
                   10923: 
1.562     albertel 10924: sub validCODE {
                   10925:     my ($CODE)=@_;
                   10926:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10927:     return 0;
                   10928: }
                   10929: 
1.491     albertel 10930: sub getCODE {
1.620     albertel 10931:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10932:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10933: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10934: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10935: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10936:     }
                   10937:     return undef;
                   10938: }
1.1133    foxr     10939: #
                   10940: #  Determines the random seed for a specific context:
                   10941: #
                   10942: # parameters:
                   10943: #   symb      - in course context the symb for the seed.
                   10944: #   course_id - The course id of the form domain_coursenum.
                   10945: #   domain    - Domain for the user.
                   10946: #   course    - Course for the user.
                   10947: #   cenv      - environment of the course.
                   10948: #
                   10949: # NOTE:
                   10950: #   All parameters are picked out of the environment if missing
                   10951: #   or not defined.
                   10952: #   If a symb cannot be determined the current time is used instead.
                   10953: #
                   10954: #  For a given well defined symb, courside, domain, username,
                   10955: #  and course environment, the seed is reproducible.
                   10956: #
1.31      www      10957: sub rndseed {
1.1133    foxr     10958:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10959:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10960:     if (!defined($symb)) {
1.366     albertel 10961: 	unless ($symb=$wsymb) { return time; }
                   10962:     }
1.1146    foxr     10963:     if (!defined $courseid) { 
                   10964: 	$courseid=$wcourseid; 
                   10965:     }
                   10966:     if (!defined $domain) { $domain=$wdomain; }
                   10967:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10968: 
                   10969:     my $which;
                   10970:     if (defined($cenv->{'rndseed'})) {
                   10971: 	$which = $cenv->{'rndseed'};
                   10972:     } else {
                   10973: 	$which =&get_rand_alg($courseid);
                   10974:     }
1.491     albertel 10975:     if (defined(&getCODE())) {
1.1133    foxr     10976: 
1.675     albertel 10977: 	if ($which eq '64bit5') {
                   10978: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10979: 	} elsif ($which eq '64bit4') {
1.575     albertel 10980: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10981: 	} else {
                   10982: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10983: 	}
1.675     albertel 10984:     } elsif ($which eq '64bit5') {
                   10985: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10986:     } elsif ($which eq '64bit4') {
                   10987: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10988:     } elsif ($which eq '64bit3') {
                   10989: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10990:     } elsif ($which eq '64bit2') {
                   10991: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10992:     } elsif ($which eq '64bit') {
                   10993: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10994:     }
                   10995:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10996: }
                   10997: 
                   10998: sub rndseed_32bit {
                   10999:     my ($symb,$courseid,$domain,$username)=@_;
                   11000:     {
                   11001: 	use integer;
                   11002: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11003: 	my $symbseed=numval($symb) << 22;
                   11004: 	my $namechck=unpack("%32C*",$username) << 17;
                   11005: 	my $nameseed=numval($username) << 12;
                   11006: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11007: 	my $courseseed=unpack("%32C*",$courseid);
                   11008: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11009: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11010: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11011: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11012: 	return $num;
                   11013:     }
                   11014: }
                   11015: 
                   11016: sub rndseed_64bit {
                   11017:     my ($symb,$courseid,$domain,$username)=@_;
                   11018:     {
                   11019: 	use integer;
                   11020: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11021: 	my $symbseed=numval($symb) << 10;
                   11022: 	my $namechck=unpack("%32S*",$username);
                   11023: 	
                   11024: 	my $nameseed=numval($username) << 21;
                   11025: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11026: 	my $courseseed=unpack("%32S*",$courseid);
                   11027: 	
                   11028: 	my $num1=$symbchck+$symbseed+$namechck;
                   11029: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11030: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11031: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11032: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11033: 	return "$num1,$num2";
1.155     albertel 11034:     }
1.366     albertel 11035: }
                   11036: 
1.443     albertel 11037: sub rndseed_64bit2 {
                   11038:     my ($symb,$courseid,$domain,$username)=@_;
                   11039:     {
                   11040: 	use integer;
                   11041: 	# strings need to be an even # of cahracters long, it it is odd the
                   11042:         # last characters gets thrown away
                   11043: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11044: 	my $symbseed=numval($symb) << 10;
                   11045: 	my $namechck=unpack("%32S*",$username.' ');
                   11046: 	
                   11047: 	my $nameseed=numval($username) << 21;
1.501     albertel 11048: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11049: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11050: 	
                   11051: 	my $num1=$symbchck+$symbseed+$namechck;
                   11052: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11053: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11054: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11055: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11056: 	return "$num1,$num2";
                   11057:     }
                   11058: }
                   11059: 
                   11060: sub rndseed_64bit3 {
                   11061:     my ($symb,$courseid,$domain,$username)=@_;
                   11062:     {
                   11063: 	use integer;
                   11064: 	# strings need to be an even # of cahracters long, it it is odd the
                   11065:         # last characters gets thrown away
                   11066: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11067: 	my $symbseed=numval2($symb) << 10;
                   11068: 	my $namechck=unpack("%32S*",$username.' ');
                   11069: 	
                   11070: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11071: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11072: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11073: 	
                   11074: 	my $num1=$symbchck+$symbseed+$namechck;
                   11075: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11076: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11077: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11078: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11079: 	
1.503     albertel 11080: 	return "$num1:$num2";
1.443     albertel 11081:     }
                   11082: }
                   11083: 
1.575     albertel 11084: sub rndseed_64bit4 {
                   11085:     my ($symb,$courseid,$domain,$username)=@_;
                   11086:     {
                   11087: 	use integer;
                   11088: 	# strings need to be an even # of cahracters long, it it is odd the
                   11089:         # last characters gets thrown away
                   11090: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11091: 	my $symbseed=numval3($symb) << 10;
                   11092: 	my $namechck=unpack("%32S*",$username.' ');
                   11093: 	
                   11094: 	my $nameseed=numval3($username) << 21;
                   11095: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11096: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11097: 	
                   11098: 	my $num1=$symbchck+$symbseed+$namechck;
                   11099: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11100: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11101: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11102: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11103: 	
1.575     albertel 11104: 	return "$num1:$num2";
                   11105:     }
                   11106: }
                   11107: 
1.675     albertel 11108: sub rndseed_64bit5 {
                   11109:     my ($symb,$courseid,$domain,$username)=@_;
                   11110:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11111:     return "$num1:$num2";
                   11112: }
                   11113: 
1.366     albertel 11114: sub rndseed_CODE_64bit {
                   11115:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11116:     {
1.366     albertel 11117: 	use integer;
1.443     albertel 11118: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11119: 	my $symbseed=numval2($symb);
1.491     albertel 11120: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11121: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11122: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11123: 	my $num1=$symbseed+$CODEchck;
                   11124: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11125: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11126: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11127: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11128: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11129: 	return "$num1:$num2";
1.366     albertel 11130:     }
                   11131: }
                   11132: 
1.575     albertel 11133: sub rndseed_CODE_64bit4 {
                   11134:     my ($symb,$courseid,$domain,$username)=@_;
                   11135:     {
                   11136: 	use integer;
                   11137: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11138: 	my $symbseed=numval3($symb);
                   11139: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11140: 	my $CODEseed=numval3(&getCODE());
                   11141: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11142: 	my $num1=$symbseed+$CODEchck;
                   11143: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11144: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11145: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11146: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11147: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11148: 	return "$num1:$num2";
                   11149:     }
                   11150: }
                   11151: 
1.675     albertel 11152: sub rndseed_CODE_64bit5 {
                   11153:     my ($symb,$courseid,$domain,$username)=@_;
                   11154:     my $code = &getCODE();
                   11155:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11156:     return "$num1:$num2";
                   11157: }
                   11158: 
1.366     albertel 11159: sub setup_random_from_rndseed {
                   11160:     my ($rndseed)=@_;
1.503     albertel 11161:     if ($rndseed =~/([,:])/) {
                   11162: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11163: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11164:     } else {
                   11165: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11166:     }
1.36      albertel 11167: }
                   11168: 
1.474     albertel 11169: sub latest_receipt_algorithm_id {
1.835     albertel 11170:     return 'receipt3';
1.474     albertel 11171: }
                   11172: 
1.480     www      11173: sub recunique {
                   11174:     my $fucourseid=shift;
                   11175:     my $unique;
1.835     albertel 11176:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11177: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11178: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11179:     } else {
                   11180: 	$unique=$perlvar{'lonReceipt'};
                   11181:     }
                   11182:     return unpack("%32C*",$unique);
                   11183: }
                   11184: 
                   11185: sub recprefix {
                   11186:     my $fucourseid=shift;
                   11187:     my $prefix;
1.835     albertel 11188:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11189: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11190: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11191:     } else {
                   11192: 	$prefix=$perlvar{'lonHostID'};
                   11193:     }
                   11194:     return unpack("%32C*",$prefix);
                   11195: }
                   11196: 
1.76      www      11197: sub ireceipt {
1.474     albertel 11198:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11199: 
                   11200:     my $return =&recprefix($fucourseid).'-';
                   11201: 
                   11202:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11203: 	$env{'request.state'} eq 'construct') {
                   11204: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11205: 	return $return;
                   11206:     }
                   11207: 
1.76      www      11208:     my $cuname=unpack("%32C*",$funame);
                   11209:     my $cudom=unpack("%32C*",$fudom);
                   11210:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11211:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11212:     my $cunique=&recunique($fucourseid);
1.474     albertel 11213:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11214:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11215: 
1.790     albertel 11216: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11217: 			       
                   11218: 	$return.= ($cunique%$cuname+
                   11219: 		   $cunique%$cudom+
                   11220: 		   $cusymb%$cuname+
                   11221: 		   $cusymb%$cudom+
                   11222: 		   $cucourseid%$cuname+
                   11223: 		   $cucourseid%$cudom+
                   11224: 		   $cpart%$cuname+
                   11225: 		   $cpart%$cudom);
                   11226:     } else {
                   11227: 	$return.= ($cunique%$cuname+
                   11228: 		   $cunique%$cudom+
                   11229: 		   $cusymb%$cuname+
                   11230: 		   $cusymb%$cudom+
                   11231: 		   $cucourseid%$cuname+
                   11232: 		   $cucourseid%$cudom);
                   11233:     }
                   11234:     return $return;
1.76      www      11235: }
                   11236: 
                   11237: sub receipt {
1.474     albertel 11238:     my ($part)=@_;
1.790     albertel 11239:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11240:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11241: }
1.260     ng       11242: 
1.790     albertel 11243: sub whichuser {
                   11244:     my ($passedsymb)=@_;
                   11245:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11246:     if (defined($env{'form.grade_symb'})) {
                   11247: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11248: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11249: 	if (!$allowed &&
                   11250: 	    exists($env{'request.course.sec'}) &&
                   11251: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11252: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11253: 			      '/'.$env{'request.course.sec'});
                   11254: 	}
                   11255: 	if ($allowed) {
                   11256: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11257: 	    $courseid=$tmp_courseid;
                   11258: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11259: 	    ($name)=&get_env_multiple('form.grade_username');
                   11260: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11261: 	}
                   11262:     }
                   11263:     if (!$passedsymb) {
                   11264: 	$symb=&symbread();
                   11265:     } else {
                   11266: 	$symb=$passedsymb;
                   11267:     }
                   11268:     $courseid=$env{'request.course.id'};
                   11269:     $domain=$env{'user.domain'};
                   11270:     $name=$env{'user.name'};
                   11271:     if ($name eq 'public' && $domain eq 'public') {
                   11272: 	if (!defined($env{'form.username'})) {
                   11273: 	    $env{'form.username'}.=time.rand(10000000);
                   11274: 	}
                   11275: 	$name.=$env{'form.username'};
                   11276:     }
                   11277:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11278: 
                   11279: }
                   11280: 
1.36      albertel 11281: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11282: # returns either the contents of the file or 
                   11283: # -1 if the file doesn't exist
1.481     raeburn  11284: #
                   11285: # if the target is a file that was uploaded via DOCS, 
                   11286: # a check will be made to see if a current copy exists on the local server,
                   11287: # if it does this will be served, otherwise a copy will be retrieved from
                   11288: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11289: # the local server.   
1.472     albertel 11290: 
1.36      albertel 11291: sub getfile {
1.538     albertel 11292:     my ($file) = @_;
1.609     banghart 11293:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11294:     &repcopy($file);
                   11295:     return &readfile($file);
                   11296: }
                   11297: 
                   11298: sub repcopy_userfile {
                   11299:     my ($file)=@_;
1.1142    raeburn  11300:     my $londocroot = $perlvar{'lonDocRoot'};
                   11301:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11302:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11303:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11304: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11305:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11306:     if (-e "$file") {
1.828     www      11307: # we already have a local copy, check it out
1.538     albertel 11308: 	my @fileinfo = stat($file);
1.828     www      11309: 	my $rtncode;
                   11310: 	my $info;
1.538     albertel 11311: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11312: 	if ($lwpresp ne 'ok') {
1.828     www      11313: # there is no such file anymore, even though we had a local copy
1.482     albertel 11314: 	    if ($rtncode eq '404') {
1.538     albertel 11315: 		unlink($file);
1.482     albertel 11316: 	    }
                   11317: 	    return -1;
                   11318: 	}
                   11319: 	if ($info < $fileinfo[9]) {
1.828     www      11320: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11321: 	    return 'ok';
1.828     www      11322: 	} else {
                   11323: # the file is outdated, get rid of it
                   11324: 	    unlink($file);
1.482     albertel 11325: 	}
1.828     www      11326:     }
                   11327: # one way or the other, at this point, we don't have the file
                   11328: # construct the correct path for the file
                   11329:     my @parts = ($cdom,$cnum); 
                   11330:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11331: 	push @parts, split(/\//,$1);
                   11332:     }
                   11333:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11334:     foreach my $part (@parts) {
                   11335: 	$path .= '/'.$part;
                   11336: 	if (!-e $path) {
                   11337: 	    mkdir($path,0770);
1.482     albertel 11338: 	}
                   11339:     }
1.828     www      11340: # now the path exists for sure
                   11341: # get a user agent
                   11342:     my $ua=new LWP::UserAgent;
                   11343:     my $transferfile=$file.'.in.transfer';
                   11344: # FIXME: this should flock
                   11345:     if (-e $transferfile) { return 'ok'; }
                   11346:     my $request;
                   11347:     $uri=~s/^\///;
1.980     raeburn  11348:     my $homeserver = &homeserver($cnum,$cdom);
                   11349:     my $protocol = $protocol{$homeserver};
                   11350:     $protocol = 'http' if ($protocol ne 'https');
                   11351:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11352:     my $response=$ua->request($request,$transferfile);
                   11353: # did it work?
                   11354:     if ($response->is_error()) {
                   11355: 	unlink($transferfile);
                   11356: 	&logthis("Userfile repcopy failed for $uri");
                   11357: 	return -1;
                   11358:     }
                   11359: # worked, rename the transfer file
                   11360:     rename($transferfile,$file);
1.607     raeburn  11361:     return 'ok';
1.481     raeburn  11362: }
                   11363: 
1.517     albertel 11364: sub tokenwrapper {
                   11365:     my $uri=shift;
1.980     raeburn  11366:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11367:     $uri=~s|^/||;
1.620     albertel 11368:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11369:     my $token=$1;
1.552     albertel 11370:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11371:     if ($udom && $uname && $file) {
                   11372: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11373:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11374:         my $homeserver = &homeserver($uname,$udom);
                   11375:         my $protocol = $protocol{$homeserver};
                   11376:         $protocol = 'http' if ($protocol ne 'https');
                   11377:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11378:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11379:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11380:     } else {
                   11381:         return '/adm/notfound.html';
                   11382:     }
                   11383: }
                   11384: 
1.828     www      11385: # call with reqtype HEAD: get last modification time
                   11386: # call with reqtype GET: get the file contents
                   11387: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11388: #
1.481     raeburn  11389: sub getuploaded {
                   11390:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11391:     $uri=~s/^\///;
1.980     raeburn  11392:     my $homeserver = &homeserver($cnum,$cdom);
                   11393:     my $protocol = $protocol{$homeserver};
                   11394:     $protocol = 'http' if ($protocol ne 'https');
                   11395:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11396:     my $ua=new LWP::UserAgent;
                   11397:     my $request=new HTTP::Request($reqtype,$uri);
                   11398:     my $response=$ua->request($request);
                   11399:     $$rtncode = $response->code;
1.482     albertel 11400:     if (! $response->is_success()) {
                   11401: 	return 'failed';
                   11402:     }      
                   11403:     if ($reqtype eq 'HEAD') {
1.486     www      11404: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11405:     } elsif ($reqtype eq 'GET') {
                   11406: 	$$info = $response->content;
1.472     albertel 11407:     }
1.482     albertel 11408:     return 'ok';
1.36      albertel 11409: }
                   11410: 
1.481     raeburn  11411: sub readfile {
                   11412:     my $file = shift;
                   11413:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11414:     my $fh;
                   11415:     open($fh,"<$file");
                   11416:     my $a='';
1.800     albertel 11417:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11418:     return $a;
                   11419: }
                   11420: 
1.36      albertel 11421: sub filelocation {
1.590     banghart 11422:     my ($dir,$file) = @_;
                   11423:     my $location;
                   11424:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11425: 
                   11426:     if ($file =~ m-^/adm/-) {
                   11427: 	$file=~s-^/adm/wrapper/-/-;
                   11428: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11429:     }
1.882     albertel 11430: 
1.1139    www      11431:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11432:         $location = $file;
1.609     banghart 11433:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11434:         my ($udom,$uname,$filename)=
1.811     albertel 11435:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11436:         my $home=&homeserver($uname,$udom);
                   11437:         my $is_me=0;
                   11438:         my @ids=&current_machine_ids();
                   11439:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11440:         if ($is_me) {
1.1117    foxr     11441:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11442:         } else {
                   11443:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11444:   	      $udom.'/'.$uname.'/'.$filename;
                   11445:         }
1.882     albertel 11446:     } elsif ($file =~ m-^/adm/-) {
                   11447: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11448:     } else {
                   11449:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11450:         $file=~s:^/(res|priv)/:/:;
                   11451:         my $space=$1;
1.590     banghart 11452:         if ( !( $file =~ m:^/:) ) {
                   11453:             $location = $dir. '/'.$file;
                   11454:         } else {
1.1142    raeburn  11455:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11456:         }
1.59      albertel 11457:     }
1.590     banghart 11458:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11459:     while ($location=~m{/\.\./}) {
                   11460: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11461: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11462: 	} else {
                   11463: 	    $location=~ s{/\.\./}{/}g;
                   11464: 	}
                   11465:     } #remove dir/..
1.590     banghart 11466:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11467:     return $location;
1.46      www      11468: }
1.36      albertel 11469: 
1.46      www      11470: sub hreflocation {
                   11471:     my ($dir,$file)=@_;
1.980     raeburn  11472:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11473: 	$file=filelocation($dir,$file);
1.700     albertel 11474:     } elsif ($file=~m-^/adm/-) {
                   11475: 	$file=~s-^/adm/wrapper/-/-;
                   11476: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11477:     }
                   11478:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11479: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11480:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11481: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11482: 	        {/uploaded/$1/$2/}x;
1.46      www      11483:     }
1.913     albertel 11484:     if ($file=~ m{^/userfiles/}) {
                   11485: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11486:     }
1.462     albertel 11487:     return $file;
1.465     albertel 11488: }
                   11489: 
1.1139    www      11490: 
                   11491: 
                   11492: 
                   11493: 
1.465     albertel 11494: sub current_machine_domains {
1.853     albertel 11495:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11496: }
                   11497: 
                   11498: sub machine_domains {
                   11499:     my ($hostname) = @_;
1.465     albertel 11500:     my @domains;
1.838     albertel 11501:     my %hostname = &all_hostnames();
1.465     albertel 11502:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11503: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11504: 	if ($hostname eq $name) {
1.844     albertel 11505: 	    push(@domains,&host_domain($id));
1.465     albertel 11506: 	}
                   11507:     }
                   11508:     return @domains;
                   11509: }
                   11510: 
                   11511: sub current_machine_ids {
1.853     albertel 11512:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11513: }
                   11514: 
                   11515: sub machine_ids {
                   11516:     my ($hostname) = @_;
                   11517:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11518:     my @ids;
1.888     albertel 11519:     my %name_to_host = &all_names();
1.889     albertel 11520:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11521: 	return @{ $name_to_host{$hostname} };
                   11522:     }
                   11523:     return;
1.31      www      11524: }
                   11525: 
1.824     raeburn  11526: sub additional_machine_domains {
                   11527:     my @domains;
                   11528:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11529:     while( my $line = <$fh>) {
                   11530:         $line =~ s/\s//g;
                   11531:         push(@domains,$line);
                   11532:     }
                   11533:     return @domains;
                   11534: }
                   11535: 
                   11536: sub default_login_domain {
                   11537:     my $domain = $perlvar{'lonDefDomain'};
                   11538:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11539:     foreach my $posdom (&current_machine_domains(),
                   11540:                         &additional_machine_domains()) {
                   11541:         if (lc($posdom) eq lc($testdomain)) {
                   11542:             $domain=$posdom;
                   11543:             last;
                   11544:         }
                   11545:     }
                   11546:     return $domain;
                   11547: }
                   11548: 
1.31      www      11549: # ------------------------------------------------------------- Declutters URLs
                   11550: 
                   11551: sub declutter {
                   11552:     my $thisfn=shift;
1.569     albertel 11553:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11554:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11555:     $thisfn=~s/^\///;
1.697     albertel 11556:     $thisfn=~s|^adm/wrapper/||;
                   11557:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11558:     $thisfn=~s/^res\///;
1.1172    bisitz   11559:     $thisfn=~s/^priv\///;
1.1032    raeburn  11560:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11561:         $thisfn=~s/\?.+$//;
                   11562:     }
1.268     www      11563:     return $thisfn;
                   11564: }
                   11565: 
                   11566: # ------------------------------------------------------------- Clutter up URLs
                   11567: 
                   11568: sub clutter {
                   11569:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11570:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11571: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11572:        $thisfn='/res'.$thisfn; 
                   11573:     }
1.1031    raeburn  11574:     if ($thisfn !~m|^/adm|) {
                   11575: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11576: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11577: 	} else {
                   11578: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11579: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11580: 	    if ($embstyle eq 'ssi'
                   11581: 		|| ($embstyle eq 'hdn')
                   11582: 		|| ($embstyle eq 'rat')
                   11583: 		|| ($embstyle eq 'prv')
                   11584: 		|| ($embstyle eq 'ign')) {
                   11585: 		#do nothing with these
                   11586: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11587: 		|| ($embstyle eq 'emb')
                   11588: 		|| ($embstyle eq 'wrp')) {
                   11589: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11590: 	    } elsif ($embstyle eq 'unk'
                   11591: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11592: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11593: 	    } else {
1.718     www      11594: #		&logthis("Got a blank emb style");
1.695     albertel 11595: 	    }
1.694     albertel 11596: 	}
                   11597:     }
1.31      www      11598:     return $thisfn;
1.12      www      11599: }
                   11600: 
1.787     albertel 11601: sub clutter_with_no_wrapper {
                   11602:     my $uri = &clutter(shift);
                   11603:     if ($uri =~ m-^/adm/-) {
                   11604: 	$uri =~ s-^/adm/wrapper/-/-;
                   11605: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11606:     }
                   11607:     return $uri;
                   11608: }
                   11609: 
1.557     albertel 11610: sub freeze_escape {
                   11611:     my ($value)=@_;
                   11612:     if (ref($value)) {
                   11613: 	$value=&nfreeze($value);
                   11614: 	return '__FROZEN__'.&escape($value);
                   11615:     }
                   11616:     return &escape($value);
                   11617: }
                   11618: 
1.11      www      11619: 
1.557     albertel 11620: sub thaw_unescape {
                   11621:     my ($value)=@_;
                   11622:     if ($value =~ /^__FROZEN__/) {
                   11623: 	substr($value,0,10,undef);
                   11624: 	$value=&unescape($value);
                   11625: 	return &thaw($value);
                   11626:     }
                   11627:     return &unescape($value);
                   11628: }
                   11629: 
1.436     albertel 11630: sub correct_line_ends {
                   11631:     my ($result)=@_;
                   11632:     $$result =~s/\r\n/\n/mg;
                   11633:     $$result =~s/\r/\n/mg;
1.415     albertel 11634: }
1.1       albertel 11635: # ================================================================ Main Program
                   11636: 
1.184     www      11637: sub goodbye {
1.204     albertel 11638:    &logthis("Starting Shut down");
1.443     albertel 11639: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11640:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11641: #converted
1.599     albertel 11642: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11643:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11644: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11645: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11646: #1.1 only
1.870     albertel 11647: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11648: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11649: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11650: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11651:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11652:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11653:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11654:    &flushcourselogs();
                   11655:    &logthis("Shutting down");
                   11656: }
                   11657: 
1.852     albertel 11658: sub get_dns {
1.1210    raeburn  11659:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11660:     if (!$ignore_cache) {
                   11661: 	my ($content,$cached)=
                   11662: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11663: 	if ($cached) {
1.1210    raeburn  11664: 	    &$func($content,$hashref);
1.869     albertel 11665: 	    return;
                   11666: 	}
                   11667:     }
                   11668: 
                   11669:     my %alldns;
1.852     albertel 11670:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11671:     foreach my $dns (<$config>) {
                   11672: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11673:         my $line = $1;
                   11674:         my ($host,$protocol) = split(/:/,$line);
                   11675:         if ($protocol ne 'https') {
                   11676:             $protocol = 'http';
                   11677:         }
                   11678: 	$alldns{$host} = $protocol;
1.869     albertel 11679:     }
                   11680:     while (%alldns) {
                   11681: 	my ($dns) = keys(%alldns);
1.852     albertel 11682: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11683:         $ua->timeout(30);
1.979     raeburn  11684: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11685: 	my $response=$ua->request($request);
1.979     raeburn  11686:         delete($alldns{$dns});
1.852     albertel 11687: 	next if ($response->is_error());
                   11688: 	my @content = split("\n",$response->content);
1.1210    raeburn  11689: 	unless ($nocache) {
1.1219    raeburn  11690: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  11691: 	}
                   11692: 	&$func(\@content,$hashref);
1.869     albertel 11693: 	return;
1.852     albertel 11694:     }
                   11695:     close($config);
1.871     albertel 11696:     my $which = (split('/',$url))[3];
                   11697:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11698:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11699:     my @content = <$config>;
1.1210    raeburn  11700:     &$func(\@content,$hashref);
                   11701:     return;
                   11702: }
                   11703: 
                   11704: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11705: sub parse_dns_checksums_tab {
1.1210    raeburn  11706:     my ($lines,$hashref) = @_;
                   11707:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11708:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11709:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11710:     my (%chksum,%revnum);
                   11711:     if (ref($lines) eq 'ARRAY') {
                   11712:         chomp(@{$lines});
1.1238    raeburn  11713:         my $version = shift(@{$lines});
                   11714:         if ($version eq $release) {  
1.1210    raeburn  11715:             foreach my $line (@{$lines}) {
1.1238    raeburn  11716:                 my ($file,$version,$shasum) = split(/,/,$line);
                   11717:                 $chksum{$file} = $shasum;
                   11718:                 $revnum{$file} = $version;
1.1210    raeburn  11719:             }
                   11720:             if (ref($hashref) eq 'HASH') {
                   11721:                 %{$hashref} = (
                   11722:                                 sums     => \%chksum,
                   11723:                                 versions => \%revnum,
                   11724:                               );
                   11725:             }
                   11726:         }
                   11727:     }
1.869     albertel 11728:     return;
1.852     albertel 11729: }
1.1210    raeburn  11730: 
                   11731: sub fetch_dns_checksums {
1.1238    raeburn  11732:     my %checksums;
                   11733:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11734:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11735:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11736:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  11737:              \%checksums);
1.1210    raeburn  11738:     return \%checksums;
                   11739: }
                   11740: 
1.327     albertel 11741: # ------------------------------------------------------------ Read domain file
                   11742: {
1.852     albertel 11743:     my $loaded;
1.846     albertel 11744:     my %domain;
                   11745: 
1.852     albertel 11746:     sub parse_domain_tab {
                   11747: 	my ($lines) = @_;
                   11748: 	foreach my $line (@$lines) {
                   11749: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11750: 
1.846     albertel 11751: 	    chomp($line);
1.852     albertel 11752: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11753: 	    my %this_domain;
                   11754: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11755: 			       'lang_def', 'city', 'longi', 'lati',
                   11756: 			       'primary') {
                   11757: 		$this_domain{$field} = shift(@elements);
                   11758: 	    }
                   11759: 	    $domain{$name} = \%this_domain;
1.852     albertel 11760: 	}
                   11761:     }
1.864     albertel 11762: 
                   11763:     sub reset_domain_info {
                   11764: 	undef($loaded);
                   11765: 	undef(%domain);
                   11766:     }
                   11767: 
1.852     albertel 11768:     sub load_domain_tab {
1.869     albertel 11769: 	my ($ignore_cache) = @_;
                   11770: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11771: 	my $fh;
                   11772: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11773: 	    my @lines = <$fh>;
                   11774: 	    &parse_domain_tab(\@lines);
1.448     albertel 11775: 	}
1.852     albertel 11776: 	close($fh);
                   11777: 	$loaded = 1;
1.327     albertel 11778:     }
1.846     albertel 11779: 
                   11780:     sub domain {
1.852     albertel 11781: 	&load_domain_tab() if (!$loaded);
                   11782: 
1.846     albertel 11783: 	my ($name,$what) = @_;
                   11784: 	return if ( !exists($domain{$name}) );
                   11785: 
                   11786: 	if (!$what) {
                   11787: 	    return $domain{$name}{'description'};
                   11788: 	}
                   11789: 	return $domain{$name}{$what};
                   11790:     }
1.974     raeburn  11791: 
                   11792:     sub domain_info {
                   11793:         &load_domain_tab() if (!$loaded);
                   11794:         return %domain;
                   11795:     }
                   11796: 
1.327     albertel 11797: }
                   11798: 
                   11799: 
1.1       albertel 11800: # ------------------------------------------------------------- Read hosts file
                   11801: {
1.838     albertel 11802:     my %hostname;
1.844     albertel 11803:     my %hostdom;
1.845     albertel 11804:     my %libserv;
1.852     albertel 11805:     my $loaded;
1.888     albertel 11806:     my %name_to_host;
1.1074    raeburn  11807:     my %internetdom;
1.1107    raeburn  11808:     my %LC_dns_serv;
1.852     albertel 11809: 
                   11810:     sub parse_hosts_tab {
                   11811: 	my ($file) = @_;
                   11812: 	foreach my $configline (@$file) {
                   11813: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11814:             chomp($configline);
                   11815: 	    if ($configline =~ /^\^/) {
                   11816:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11817:                     $LC_dns_serv{$1} = 1;
                   11818:                 }
                   11819:                 next;
                   11820:             }
1.1074    raeburn  11821: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11822: 	    $name=~s/\s//g;
                   11823: 	    if ($id && $domain && $role && $name) {
                   11824: 		$hostname{$id}=$name;
1.888     albertel 11825: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11826: 		$hostdom{$id}=$domain;
                   11827: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11828:                 if (defined($protocol)) {
                   11829:                     if ($protocol eq 'https') {
                   11830:                         $protocol{$id} = $protocol;
                   11831:                     } else {
                   11832:                         $protocol{$id} = 'http'; 
                   11833:                     }
1.968     raeburn  11834:                 } else {
1.969     raeburn  11835:                     $protocol{$id} = 'http';
1.968     raeburn  11836:                 }
1.1074    raeburn  11837:                 if (defined($intdom)) {
                   11838:                     $internetdom{$id} = $intdom;
                   11839:                 }
1.852     albertel 11840: 	    }
                   11841: 	}
                   11842:     }
1.864     albertel 11843:     
                   11844:     sub reset_hosts_info {
1.897     albertel 11845: 	&purge_remembered();
1.864     albertel 11846: 	&reset_domain_info();
                   11847: 	&reset_hosts_ip_info();
1.892     albertel 11848: 	undef(%name_to_host);
1.864     albertel 11849: 	undef(%hostname);
                   11850: 	undef(%hostdom);
                   11851: 	undef(%libserv);
                   11852: 	undef($loaded);
                   11853:     }
1.1       albertel 11854: 
1.852     albertel 11855:     sub load_hosts_tab {
1.869     albertel 11856: 	my ($ignore_cache) = @_;
                   11857: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11858: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11859: 	my @config = <$config>;
                   11860: 	&parse_hosts_tab(\@config);
                   11861: 	close($config);
                   11862: 	$loaded=1;
1.1       albertel 11863:     }
1.852     albertel 11864: 
1.838     albertel 11865:     sub hostname {
1.852     albertel 11866: 	&load_hosts_tab() if (!$loaded);
                   11867: 
1.838     albertel 11868: 	my ($lonid) = @_;
                   11869: 	return $hostname{$lonid};
                   11870:     }
1.845     albertel 11871: 
1.838     albertel 11872:     sub all_hostnames {
1.852     albertel 11873: 	&load_hosts_tab() if (!$loaded);
                   11874: 
1.838     albertel 11875: 	return %hostname;
                   11876:     }
1.845     albertel 11877: 
1.888     albertel 11878:     sub all_names {
                   11879: 	&load_hosts_tab() if (!$loaded);
                   11880: 
                   11881: 	return %name_to_host;
                   11882:     }
                   11883: 
1.974     raeburn  11884:     sub all_host_domain {
                   11885:         &load_hosts_tab() if (!$loaded);
                   11886:         return %hostdom;
                   11887:     }
                   11888: 
1.845     albertel 11889:     sub is_library {
1.852     albertel 11890: 	&load_hosts_tab() if (!$loaded);
                   11891: 
1.845     albertel 11892: 	return exists($libserv{$_[0]});
                   11893:     }
                   11894: 
                   11895:     sub all_library {
1.852     albertel 11896: 	&load_hosts_tab() if (!$loaded);
                   11897: 
1.845     albertel 11898: 	return %libserv;
                   11899:     }
                   11900: 
1.1062    droeschl 11901:     sub unique_library {
                   11902: 	#2x reverse removes all hostnames that appear more than once
                   11903:         my %unique = reverse &all_library();
                   11904:         return reverse %unique;
                   11905:     }
                   11906: 
1.841     albertel 11907:     sub get_servers {
1.852     albertel 11908: 	&load_hosts_tab() if (!$loaded);
                   11909: 
1.841     albertel 11910: 	my ($domain,$type) = @_;
                   11911: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11912: 	                                          : %hostname;
                   11913: 	my %result;
1.842     albertel 11914: 	if (ref($domain) eq 'ARRAY') {
                   11915: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11916: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11917: 		    $result{$host} = $hostname;
                   11918: 		}
                   11919: 	    }
                   11920: 	} else {
                   11921: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11922: 		if ($hostdom{$host} eq $domain) {
                   11923: 		    $result{$host} = $hostname;
                   11924: 		}
1.841     albertel 11925: 	    }
                   11926: 	}
                   11927: 	return %result;
                   11928:     }
1.845     albertel 11929: 
1.1062    droeschl 11930:     sub get_unique_servers {
                   11931:         my %unique = reverse &get_servers(@_);
                   11932: 	return reverse %unique;
                   11933:     }
                   11934: 
1.844     albertel 11935:     sub host_domain {
1.852     albertel 11936: 	&load_hosts_tab() if (!$loaded);
                   11937: 
1.844     albertel 11938: 	my ($lonid) = @_;
                   11939: 	return $hostdom{$lonid};
                   11940:     }
                   11941: 
1.841     albertel 11942:     sub all_domains {
1.852     albertel 11943: 	&load_hosts_tab() if (!$loaded);
                   11944: 
1.841     albertel 11945: 	my %seen;
                   11946: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11947: 	return @uniq;
                   11948:     }
1.1074    raeburn  11949: 
                   11950:     sub internet_dom {
                   11951:         &load_hosts_tab() if (!$loaded);
                   11952: 
                   11953:         my ($lonid) = @_;
                   11954:         return $internetdom{$lonid};
                   11955:     }
1.1107    raeburn  11956: 
                   11957:     sub is_LC_dns {
                   11958:         &load_hosts_tab() if (!$loaded);
                   11959: 
                   11960:         my ($hostname) = @_;
                   11961:         return exists($LC_dns_serv{$hostname});
                   11962:     }
                   11963: 
1.1       albertel 11964: }
                   11965: 
1.847     albertel 11966: { 
                   11967:     my %iphost;
1.856     albertel 11968:     my %name_to_ip;
                   11969:     my %lonid_to_ip;
1.869     albertel 11970: 
1.847     albertel 11971:     sub get_hosts_from_ip {
                   11972: 	my ($ip) = @_;
                   11973: 	my %iphosts = &get_iphost();
                   11974: 	if (ref($iphosts{$ip})) {
                   11975: 	    return @{$iphosts{$ip}};
                   11976: 	}
                   11977: 	return;
1.839     albertel 11978:     }
1.864     albertel 11979:     
                   11980:     sub reset_hosts_ip_info {
                   11981: 	undef(%iphost);
                   11982: 	undef(%name_to_ip);
                   11983: 	undef(%lonid_to_ip);
                   11984:     }
1.856     albertel 11985: 
                   11986:     sub get_host_ip {
                   11987: 	my ($lonid) = @_;
                   11988: 	if (exists($lonid_to_ip{$lonid})) {
                   11989: 	    return $lonid_to_ip{$lonid};
                   11990: 	}
                   11991: 	my $name=&hostname($lonid);
                   11992:    	my $ip = gethostbyname($name);
                   11993: 	return if (!$ip || length($ip) ne 4);
                   11994: 	$ip=inet_ntoa($ip);
                   11995: 	$name_to_ip{$name}   = $ip;
                   11996: 	$lonid_to_ip{$lonid} = $ip;
                   11997: 	return $ip;
                   11998:     }
1.847     albertel 11999:     
                   12000:     sub get_iphost {
1.869     albertel 12001: 	my ($ignore_cache) = @_;
1.894     albertel 12002: 
1.869     albertel 12003: 	if (!$ignore_cache) {
                   12004: 	    if (%iphost) {
                   12005: 		return %iphost;
                   12006: 	    }
                   12007: 	    my ($ip_info,$cached)=
                   12008: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12009: 	    if ($cached) {
                   12010: 		%iphost      = %{$ip_info->[0]};
                   12011: 		%name_to_ip  = %{$ip_info->[1]};
                   12012: 		%lonid_to_ip = %{$ip_info->[2]};
                   12013: 		return %iphost;
                   12014: 	    }
                   12015: 	}
1.894     albertel 12016: 
                   12017: 	# get yesterday's info for fallback
                   12018: 	my %old_name_to_ip;
                   12019: 	my ($ip_info,$cached)=
                   12020: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12021: 	if ($cached) {
                   12022: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12023: 	}
                   12024: 
1.888     albertel 12025: 	my %name_to_host = &all_names();
                   12026: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12027: 	    my $ip;
                   12028: 	    if (!exists($name_to_ip{$name})) {
                   12029: 		$ip = gethostbyname($name);
                   12030: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12031: 		    if (defined($old_name_to_ip{$name})) {
                   12032: 			$ip = $old_name_to_ip{$name};
                   12033: 			&logthis("Can't find $name defaulting to old $ip");
                   12034: 		    } else {
                   12035: 			&logthis("Name $name no IP found");
                   12036: 			next;
                   12037: 		    }
                   12038: 		} else {
                   12039: 		    $ip=inet_ntoa($ip);
1.847     albertel 12040: 		}
                   12041: 		$name_to_ip{$name} = $ip;
                   12042: 	    } else {
                   12043: 		$ip = $name_to_ip{$name};
1.653     albertel 12044: 	    }
1.888     albertel 12045: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12046: 		$lonid_to_ip{$id} = $ip;
                   12047: 	    }
                   12048: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12049: 	}
1.1219    raeburn  12050: 	&do_cache_new('iphost','iphost',
                   12051: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12052: 		      48*60*60);
1.869     albertel 12053: 
1.847     albertel 12054: 	return %iphost;
1.598     albertel 12055:     }
                   12056: 
1.992     raeburn  12057:     #
                   12058:     #  Given a DNS returns the loncapa host name for that DNS 
                   12059:     # 
                   12060:     sub host_from_dns {
                   12061:         my ($dns) = @_;
                   12062:         my @hosts;
                   12063:         my $ip;
                   12064: 
1.993     raeburn  12065:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12066:             $ip = $name_to_ip{$dns};
                   12067:         }
                   12068:         if (!$ip) {
                   12069:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12070:             if (length($ip) == 4) { 
                   12071: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12072:             }
                   12073:         }
                   12074:         if ($ip) {
                   12075: 	    @hosts = get_hosts_from_ip($ip);
                   12076: 	    return $hosts[0];
                   12077:         }
                   12078:         return undef;
1.986     foxr     12079:     }
1.992     raeburn  12080: 
1.1074    raeburn  12081:     sub get_internet_names {
                   12082:         my ($lonid) = @_;
                   12083:         return if ($lonid eq '');
                   12084:         my ($idnref,$cached)=
                   12085:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12086:         if ($cached) {
                   12087:             return $idnref;
                   12088:         }
                   12089:         my $ip = &get_host_ip($lonid);
                   12090:         my @hosts = &get_hosts_from_ip($ip);
                   12091:         my %iphost = &get_iphost();
                   12092:         my (@idns,%seen);
                   12093:         foreach my $id (@hosts) {
                   12094:             my $dom = &host_domain($id);
                   12095:             my $prim_id = &domain($dom,'primary');
                   12096:             my $prim_ip = &get_host_ip($prim_id);
                   12097:             next if ($seen{$prim_ip});
                   12098:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12099:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12100:                     my $intdom = &internet_dom($id);
                   12101:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12102:                         push(@idns,$intdom);
                   12103:                     }
                   12104:                 }
                   12105:             }
                   12106:             $seen{$prim_ip} = 1;
                   12107:         }
1.1219    raeburn  12108:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12109:     }
                   12110: 
1.986     foxr     12111: }
                   12112: 
1.1079    raeburn  12113: sub all_loncaparevs {
                   12114:     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);
                   12115: }
                   12116: 
1.1227    raeburn  12117: # ---------------------------------------------------------- Read loncaparev table
                   12118: {
                   12119:     sub load_loncaparevs { 
                   12120:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12121:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12122:                 while (my $configline=<$config>) {
                   12123:                     chomp($configline);
                   12124:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12125:                     $loncaparevs{$hostid}=$loncaparev;
                   12126:                 }
                   12127:                 close($config);
                   12128:             }
                   12129:         }
                   12130:     }
                   12131: }
                   12132: 
                   12133: # ---------------------------------------------------------- Read serverhostID table
                   12134: {
                   12135:     sub load_serverhomeIDs {
                   12136:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12137:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12138:                 while (my $configline=<$config>) {
                   12139:                     chomp($configline);
                   12140:                     my ($name,$id)=split(/:/,$configline);
                   12141:                     $serverhomeIDs{$name}=$id;
                   12142:                 }
                   12143:                 close($config);
                   12144:             }
                   12145:         }
                   12146:     }
                   12147: }
                   12148: 
                   12149: 
1.862     albertel 12150: BEGIN {
                   12151: 
                   12152: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12153:     unless ($readit) {
                   12154: {
                   12155:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12156:     %perlvar = (%perlvar,%{$configvars});
                   12157: }
                   12158: 
                   12159: 
1.1       albertel 12160: # ------------------------------------------------------ Read spare server file
                   12161: {
1.448     albertel 12162:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12163: 
                   12164:     while (my $configline=<$config>) {
                   12165:        chomp($configline);
1.284     matthew  12166:        if ($configline) {
1.784     albertel 12167: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12168: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12169: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12170:        }
                   12171:     }
1.448     albertel 12172:     close($config);
1.1       albertel 12173: }
1.11      www      12174: # ------------------------------------------------------------ Read permissions
                   12175: {
1.448     albertel 12176:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12177: 
                   12178:     while (my $configline=<$config>) {
1.448     albertel 12179: 	chomp($configline);
                   12180: 	if ($configline) {
                   12181: 	    my ($role,$perm)=split(/ /,$configline);
                   12182: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12183: 	}
1.11      www      12184:     }
1.448     albertel 12185:     close($config);
1.11      www      12186: }
                   12187: 
                   12188: # -------------------------------------------- Read plain texts for permissions
                   12189: {
1.448     albertel 12190:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12191: 
                   12192:     while (my $configline=<$config>) {
1.448     albertel 12193: 	chomp($configline);
                   12194: 	if ($configline) {
1.742     raeburn  12195: 	    my ($short,@plain)=split(/:/,$configline);
                   12196:             %{$prp{$short}} = ();
                   12197: 	    if (@plain > 0) {
                   12198:                 $prp{$short}{'std'} = $plain[0];
                   12199:                 for (my $i=1; $i<@plain; $i++) {
                   12200:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12201:                 }
                   12202:             }
1.448     albertel 12203: 	}
1.135     www      12204:     }
1.448     albertel 12205:     close($config);
1.135     www      12206: }
                   12207: 
                   12208: # ---------------------------------------------------------- Read package table
                   12209: {
1.448     albertel 12210:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12211: 
                   12212:     while (my $configline=<$config>) {
1.483     albertel 12213: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12214: 	chomp($configline);
                   12215: 	my ($short,$plain)=split(/:/,$configline);
                   12216: 	my ($pack,$name)=split(/\&/,$short);
                   12217: 	if ($plain ne '') {
                   12218: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12219: 	    $packagetab{$short}=$plain; 
                   12220: 	}
1.11      www      12221:     }
1.448     albertel 12222:     close($config);
1.329     matthew  12223: }
                   12224: 
1.1073    raeburn  12225: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12226: 
                   12227: &load_loncaparevs();
1.1073    raeburn  12228: 
1.1074    raeburn  12229: # ---------------------------------------------------------- Read serverhostID table
                   12230: 
1.1227    raeburn  12231: &load_serverhomeIDs();
                   12232: 
                   12233: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12234: {
                   12235:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12236:     if (-e $file) {
                   12237:         my $parser = HTML::LCParser->new($file);
                   12238:         while (my $token = $parser->get_token()) {
                   12239:             if ($token->[0] eq 'S') {
                   12240:                 my $item = $token->[1];
                   12241:                 my $name = $token->[2]{'name'};
                   12242:                 my $value = $token->[2]{'value'};
                   12243:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12244:                     my $release = $parser->get_text();
                   12245:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12246:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12247:                 }
                   12248:             }
                   12249:         }
                   12250:     }
1.1073    raeburn  12251: }
                   12252: 
1.1138    raeburn  12253: # ---------------------------------------------------------- Read managers table
                   12254: {
                   12255:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12256:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12257:             while (my $configline=<$config>) {
                   12258:                 chomp($configline);
                   12259:                 next if ($configline =~ /^\#/);
                   12260:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12261:                     $managerstab{$configline} = 1;
                   12262:                 }
                   12263:             }
                   12264:             close($config);
                   12265:         }
                   12266:     }
                   12267: }
                   12268: 
1.329     matthew  12269: # ------------- set up temporary directory
                   12270: {
1.1117    foxr     12271:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12272: 
1.11      www      12273: }
                   12274: 
1.794     albertel 12275: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12276: 				'compress_threshold'=> 20_000,
                   12277:  			        });
1.185     www      12278: 
1.281     www      12279: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12280: $dumpcount=0;
1.958     www      12281: $locknum=0;
1.22      www      12282: 
1.163     harris41 12283: &logtouch();
1.672     albertel 12284: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12285: $readit=1;
1.564     albertel 12286:     {
                   12287: 	use integer;
                   12288: 	my $test=(2**32)+1;
1.568     albertel 12289: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12290: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12291:     }
1.1214    raeburn  12292: 
                   12293:     {
                   12294:         eval {
                   12295:             ($apache) =
                   12296:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12297:         };
                   12298:         if ($@) {
                   12299:            $apache = 1.3;
1.1213    raeburn  12300:         }
                   12301:     }
1.1214    raeburn  12302: 
1.195     www      12303: }
1.1       albertel 12304: }
1.179     www      12305: 
1.1       albertel 12306: 1;
1.191     harris41 12307: __END__
                   12308: 
1.243     albertel 12309: =pod
                   12310: 
1.191     harris41 12311: =head1 NAME
                   12312: 
1.243     albertel 12313: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12314: 
                   12315: =head1 SYNOPSIS
                   12316: 
1.243     albertel 12317: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12318: 
                   12319:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12320: 
1.243     albertel 12321: Common parameters:
                   12322: 
                   12323: =over 4
                   12324: 
                   12325: =item *
                   12326: 
                   12327: $uname : an internal username (if $cname expecting a course Id specifically)
                   12328: 
                   12329: =item *
                   12330: 
                   12331: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12332: 
                   12333: =item *
                   12334: 
                   12335: $symb : a resource instance identifier
                   12336: 
                   12337: =item *
                   12338: 
                   12339: $namespace : the name of a .db file that contains the data needed or
                   12340: being set.
                   12341: 
                   12342: =back
                   12343: 
1.394     bowersj2 12344: =head1 OVERVIEW
1.191     harris41 12345: 
1.394     bowersj2 12346: lonnet provides subroutines which interact with the
                   12347: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12348: about classes, users, and resources.
1.243     albertel 12349: 
                   12350: For many of these objects you can also use this to store data about
                   12351: them or modify them in various ways.
1.191     harris41 12352: 
1.394     bowersj2 12353: =head2 Symbs
1.191     harris41 12354: 
1.394     bowersj2 12355: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12356: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12357: map, the resource number of the resource in the map, and the URL of
                   12358: the resource itself. The latter is somewhat redundant, but might help
                   12359: if maps change.
                   12360: 
                   12361: An example is
                   12362: 
                   12363:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12364: 
                   12365: The respective map entry is
                   12366: 
                   12367:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12368:   title="Problem 2">
                   12369:  </resource>
                   12370: 
                   12371: Symbs are used by the random number generator, as well as to store and
                   12372: restore data specific to a certain instance of for example a problem.
                   12373: 
                   12374: =head2 Storing And Retrieving Data
                   12375: 
                   12376: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12377: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12378: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12379: is is the non-critical message twin of cstore. These functions are for
                   12380: handlers to store a perl hash to a user's permanent data space in an
                   12381: easy manner, and to retrieve it again on another call. It is expected
                   12382: that a handler would use this once at the beginning to retrieve data,
                   12383: and then again once at the end to send only the new data back.
                   12384: 
                   12385: The data is stored in the user's data directory on the user's
                   12386: homeserver under the ID of the course.
                   12387: 
                   12388: The hash that is returned by restore will have all of the previous
                   12389: value for all of the elements of the hash.
                   12390: 
                   12391: Example:
                   12392: 
                   12393:  #creating a hash
                   12394:  my %hash;
                   12395:  $hash{'foo'}='bar';
                   12396: 
                   12397:  #storing it
                   12398:  &Apache::lonnet::cstore(\%hash);
                   12399: 
                   12400:  #changing a value
                   12401:  $hash{'foo'}='notbar';
                   12402: 
                   12403:  #adding a new value
                   12404:  $hash{'bar'}='foo';
                   12405:  &Apache::lonnet::cstore(\%hash);
                   12406: 
                   12407:  #retrieving the hash
                   12408:  my %history=&Apache::lonnet::restore();
                   12409: 
                   12410:  #print the hash
                   12411:  foreach my $key (sort(keys(%history))) {
                   12412:    print("\%history{$key} = $history{$key}");
                   12413:  }
                   12414: 
                   12415: Will print out:
1.191     harris41 12416: 
1.394     bowersj2 12417:  %history{1:foo} = bar
                   12418:  %history{1:keys} = foo:timestamp
                   12419:  %history{1:timestamp} = 990455579
                   12420:  %history{2:bar} = foo
                   12421:  %history{2:foo} = notbar
                   12422:  %history{2:keys} = foo:bar:timestamp
                   12423:  %history{2:timestamp} = 990455580
                   12424:  %history{bar} = foo
                   12425:  %history{foo} = notbar
                   12426:  %history{timestamp} = 990455580
                   12427:  %history{version} = 2
                   12428: 
                   12429: Note that the special hash entries C<keys>, C<version> and
                   12430: C<timestamp> were added to the hash. C<version> will be equal to the
                   12431: total number of versions of the data that have been stored. The
                   12432: C<timestamp> attribute will be the UNIX time the hash was
                   12433: stored. C<keys> is available in every historical section to list which
                   12434: keys were added or changed at a specific historical revision of a
                   12435: hash.
                   12436: 
                   12437: B<Warning>: do not store the hash that restore returns directly. This
                   12438: will cause a mess since it will restore the historical keys as if the
                   12439: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12440: 
1.394     bowersj2 12441: Calling convention:
1.191     harris41 12442: 
1.1225    raeburn  12443:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12444:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12445: 
1.394     bowersj2 12446: For more detailed information, see lonnet specific documentation.
1.191     harris41 12447: 
1.394     bowersj2 12448: =head1 RETURN MESSAGES
1.191     harris41 12449: 
1.394     bowersj2 12450: =over 4
1.191     harris41 12451: 
1.394     bowersj2 12452: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12453: 
1.394     bowersj2 12454: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12455: when the connection is brought back up
1.191     harris41 12456: 
1.394     bowersj2 12457: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12458: for later delivery
1.191     harris41 12459: 
1.967     bisitz   12460: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12461: 
1.394     bowersj2 12462: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12463: that was requested
1.191     harris41 12464: 
1.243     albertel 12465: =back
1.191     harris41 12466: 
1.243     albertel 12467: =head1 PUBLIC SUBROUTINES
1.191     harris41 12468: 
1.243     albertel 12469: =head2 Session Environment Functions
1.191     harris41 12470: 
1.243     albertel 12471: =over 4
1.191     harris41 12472: 
1.394     bowersj2 12473: =item * 
                   12474: X<appenv()>
1.949     raeburn  12475: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12476: the user envirnoment file, and will be restored for each access this
1.620     albertel 12477: user makes during this session, also modifies the %env for the current
1.949     raeburn  12478: process. Optional rolesarrayref - if defined contains a reference to an array
                   12479: of roles which are exempt from the restriction on modifying user.role entries 
                   12480: in the user's environment.db and in %env.    
1.191     harris41 12481: 
                   12482: =item *
1.394     bowersj2 12483: X<delenv()>
1.987     raeburn  12484: B<delenv($delthis,$regexp)>: removes all items from the session
                   12485: environment file that begin with $delthis. If the 
                   12486: optional second arg - $regexp - is true, $delthis is treated as a 
                   12487: regular expression, otherwise \Q$delthis\E is used. 
                   12488: The values are also deleted from the current processes %env.
1.191     harris41 12489: 
1.795     albertel 12490: =item * get_env_multiple($name) 
                   12491: 
                   12492: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12493: values may be defined and end up as an array ref.
                   12494: 
                   12495: returns an array of values
                   12496: 
1.243     albertel 12497: =back
                   12498: 
                   12499: =head2 User Information
1.191     harris41 12500: 
1.243     albertel 12501: =over 4
1.191     harris41 12502: 
                   12503: =item *
1.394     bowersj2 12504: X<queryauthenticate()>
                   12505: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12506: authentication scheme
                   12507: 
                   12508: =item *
1.394     bowersj2 12509: X<authenticate()>
1.1073    raeburn  12510: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12511: authenticate user from domain's lib servers (first use the current
                   12512: one). C<$upass> should be the users password.
1.1073    raeburn  12513: $checkdefauth is optional (value is 1 if a check should be made to
                   12514:    authenticate user using default authentication method, and allow
                   12515:    account creation if username does not have account in the domain).
                   12516: $clientcancheckhost is optional (value is 1 if checking whether the
                   12517:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12518: 
                   12519: =item *
1.394     bowersj2 12520: X<homeserver()>
                   12521: B<homeserver($uname,$udom)>: find the server which has
                   12522: the user's directory and files (there must be only one), this caches
                   12523: the answer, and also caches if there is a borken connection.
1.191     harris41 12524: 
                   12525: =item *
1.394     bowersj2 12526: X<idget()>
                   12527: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12528: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12529: username, and only 1 username per ID in a specific domain) (returns
                   12530: hash: id=>name,id=>name)
1.191     harris41 12531: 
                   12532: =item *
1.394     bowersj2 12533: X<idrget()>
                   12534: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12535: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12536: 
                   12537: =item *
1.394     bowersj2 12538: X<idput()>
                   12539: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12540: 
                   12541: =item *
1.394     bowersj2 12542: X<rolesinit()>
1.1169    droeschl 12543: B<rolesinit($udom,$username)>: get user privileges.
                   12544: returns user role, first access and timer interval hashes
1.243     albertel 12545: 
                   12546: =item *
1.1171    droeschl 12547: X<privileged()>
                   12548: B<privileged($username,$domain)>: returns a true if user has a
                   12549: privileged and active role (i.e. su or dc), false otherwise.
                   12550: 
                   12551: =item *
1.551     albertel 12552: X<getsection()>
                   12553: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12554: course $cname, return section name/number or '' for "not in course"
                   12555: and '-1' for "no section"
                   12556: 
                   12557: =item *
1.394     bowersj2 12558: X<userenvironment()>
                   12559: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12560: passed in @what from the requested user's environment, returns a hash
                   12561: 
1.858     raeburn  12562: =item * 
                   12563: X<userlog_query()>
1.859     albertel 12564: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12565: activity.log file. %filters defines filters applied when parsing the
                   12566: log file. These can be start or end timestamps, or the type of action
                   12567: - log to look for Login or Logout events, check for Checkin or
                   12568: Checkout, role for role selection. The response is in the form
                   12569: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12570: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12571: 
1.243     albertel 12572: =back
                   12573: 
                   12574: =head2 User Roles
                   12575: 
                   12576: =over 4
                   12577: 
                   12578: =item *
                   12579: 
1.810     raeburn  12580: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12581:  F: full access
                   12582:  U,I,K: authentication modes (cxx only)
                   12583:  '': forbidden
                   12584:  1: user needs to choose course
                   12585:  2: browse allowed
1.766     albertel 12586:  A: passphrase authentication needed
1.243     albertel 12587: 
                   12588: =item *
                   12589: 
1.1192    raeburn  12590: constructaccess($url,$setpriv) : check for access to construction space URL
                   12591: 
                   12592: See if the owner domain and name in the URL match those in the
                   12593: expected environment.  If so, return three element list
                   12594: ($ownername,$ownerdomain,$ownerhome).
                   12595: 
                   12596: Otherwise return the null string.
                   12597: 
                   12598: If second argument 'setpriv' is true, it assigns the privileges,
                   12599: and returns the same three element list, unless the owner has
                   12600: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12601: in which case the null string is returned.
                   12602: 
                   12603: =item *
                   12604: 
1.243     albertel 12605: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12606: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12607: and course level
                   12608: 
                   12609: =item *
                   12610: 
1.988     raeburn  12611: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12612: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12613: $type is Course (default) or Community.
1.988     raeburn  12614: If $forcedefault evaluates to true, text returned will be default 
                   12615: text for $type. Otherwise, if this is a course, the text returned 
                   12616: will be a custom name for the role (if defined in the course's 
                   12617: environment).  If no custom name is defined the default is returned.
                   12618:    
1.832     raeburn  12619: =item *
                   12620: 
1.1219    raeburn  12621: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12622: All arguments are optional. Returns a hash of a roles, either for
                   12623: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12624: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12625: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12626: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12627: For each key, value is set to colon-separated start and end times for
                   12628: the role.  If no username and domain are specified, will default to
1.934     raeburn  12629: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12630: of role statuses (active, future or previous), roles 
                   12631: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12632: to restrict the list of roles reported. If no array ref is 
                   12633: provided for types, will default to return only active roles.
1.834     albertel 12634: 
1.1195    raeburn  12635: =item *
                   12636: 
                   12637: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12638: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12639: 
                   12640: Additional optional arguments are: $type (if role checking is to be restricted 
                   12641: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12642: available roles) or future (roles available in the future), and
                   12643: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  12644: have active Domain Coordinator role in course's domain or in additional
                   12645: domains (specified in 'Domains to check for privileged users' in course
                   12646: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12647: 
                   12648: =item *
                   12649: 
                   12650: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12651: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12652: $possdomains and $possroles are optional array refs -- to domains to check and
                   12653: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12654: users' roles.db to check for a dc or su role in any domain. This can be
                   12655: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12656: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12657: this then allows &privileged_by_domain() to be used, which caches the identity
                   12658: of privileged users, eliminating the need for repeated calls to &dump().
                   12659: 
                   12660: =item *
                   12661: 
                   12662: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12663: where the outer hash keys are domains specified in the $possdomains array ref,
                   12664: next inner hash keys are privileged roles specified in the $roles array ref,
                   12665: and the innermost hash contains key = value pairs for username:domain = end:start
                   12666: for active or future "privileged" users with that role in that domain. To avoid
                   12667: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12668: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  12669: 
1.243     albertel 12670: =back
                   12671: 
                   12672: =head2 User Modification
                   12673: 
                   12674: =over 4
                   12675: 
                   12676: =item *
                   12677: 
1.957     raeburn  12678: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12679: user for the level given by URL.  Optional start and end dates (leave empty
                   12680: string or zero for "no date")
1.191     harris41 12681: 
                   12682: =item *
                   12683: 
1.243     albertel 12684: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12685: change a users, password, possible return values are: ok,
                   12686: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12687: refused
1.191     harris41 12688: 
                   12689: =item *
                   12690: 
1.243     albertel 12691: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12692: 
                   12693: =item *
                   12694: 
1.1058    raeburn  12695: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12696:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12697: 
                   12698: will update user information (firstname,middlename,lastname,generation,
                   12699: permanentemail), and if forceid is true, student/employee ID also.
                   12700: A user's institutional affiliation(s) can also be updated.
                   12701: User information fields will not be overwritten with empty entries 
                   12702: unless the field is included in the $candelete array reference.
                   12703: This array is included when a single user is modified via "Manage Users",
                   12704: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12705: 
                   12706: =item *
                   12707: 
1.286     matthew  12708: modifystudent
                   12709: 
1.957     raeburn  12710: modify a student's enrollment and identification information.
1.1235    raeburn  12711: The course id is resolved based on the current user's environment.  
                   12712: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12713: associated with a course.
                   12714: 
1.297     matthew  12715: This call is essentially a wrapper for lonnet::modifyuser and
                   12716: lonnet::modify_student_enrollment
1.286     matthew  12717: 
                   12718: Inputs: 
                   12719: 
                   12720: =over 4
                   12721: 
1.957     raeburn  12722: =item B<$udom> Student's loncapa domain
1.286     matthew  12723: 
1.957     raeburn  12724: =item B<$uname> Student's loncapa login name
1.286     matthew  12725: 
1.964     bisitz   12726: =item B<$uid> Student/Employee ID
1.286     matthew  12727: 
1.957     raeburn  12728: =item B<$umode> Student's authentication mode
1.286     matthew  12729: 
1.957     raeburn  12730: =item B<$upass> Student's password
1.286     matthew  12731: 
1.957     raeburn  12732: =item B<$first> Student's first name
1.286     matthew  12733: 
1.957     raeburn  12734: =item B<$middle> Student's middle name
1.286     matthew  12735: 
1.957     raeburn  12736: =item B<$last> Student's last name
1.286     matthew  12737: 
1.957     raeburn  12738: =item B<$gene> Student's generation
1.286     matthew  12739: 
1.957     raeburn  12740: =item B<$usec> Student's section in course
1.286     matthew  12741: 
                   12742: =item B<$end> Unix time of the roles expiration
                   12743: 
                   12744: =item B<$start> Unix time of the roles start date
                   12745: 
                   12746: =item B<$forceid> If defined, allow $uid to be changed
                   12747: 
                   12748: =item B<$desiredhome> server to use as home server for student
                   12749: 
1.957     raeburn  12750: =item B<$email> Student's permanent e-mail address
                   12751: 
                   12752: =item B<$type> Type of enrollment (auto or manual)
                   12753: 
1.963     raeburn  12754: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12755: 
                   12756: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12757: 
1.963     raeburn  12758: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12759: 
1.963     raeburn  12760: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12761: 
1.1216    raeburn  12762: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12763: 
                   12764: =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  12765: 
1.286     matthew  12766: =back
1.297     matthew  12767: 
                   12768: =item *
                   12769: 
                   12770: modify_student_enrollment
                   12771: 
1.1235    raeburn  12772: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12773: 'role.request.course' must be defined for this function to proceed.
                   12774: 
                   12775: Inputs:
                   12776: 
                   12777: =over 4
                   12778: 
1.1235    raeburn  12779: =item $udom, student's domain
1.297     matthew  12780: 
1.1235    raeburn  12781: =item $uname, student's name
1.297     matthew  12782: 
1.1235    raeburn  12783: =item $uid, student's user id
1.297     matthew  12784: 
1.1235    raeburn  12785: =item $first, student's first name
1.297     matthew  12786: 
                   12787: =item $middle
                   12788: 
                   12789: =item $last
                   12790: 
                   12791: =item $gene
                   12792: 
                   12793: =item $usec
                   12794: 
                   12795: =item $end
                   12796: 
                   12797: =item $start
                   12798: 
1.957     raeburn  12799: =item $type
                   12800: 
                   12801: =item $locktype
                   12802: 
                   12803: =item $cid
                   12804: 
                   12805: =item $selfenroll
                   12806: 
                   12807: =item $context
                   12808: 
1.1216    raeburn  12809: =item $credits, number of credits student will earn from this class
                   12810: 
1.297     matthew  12811: =back
                   12812: 
1.191     harris41 12813: 
                   12814: =item *
                   12815: 
1.243     albertel 12816: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12817: custom role; give a custom role to a user for the level given by URL.  Specify
                   12818: name and domain of role author, and role name
1.191     harris41 12819: 
                   12820: =item *
                   12821: 
1.243     albertel 12822: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12823: 
                   12824: =item *
                   12825: 
1.243     albertel 12826: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12827: 
                   12828: =back
                   12829: 
                   12830: =head2 Course Infomation
                   12831: 
                   12832: =over 4
1.191     harris41 12833: 
                   12834: =item *
                   12835: 
1.1118    foxr     12836: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12837: specified course id, including all environment settings for the
                   12838: course, the description of the course will be in the hash under the
                   12839: key 'description'
1.191     harris41 12840: 
1.1118    foxr     12841: $options is an optional parameter that if supplied is a hash reference that controls
                   12842: what how this function works.  It has the following key/values:
                   12843: 
                   12844: =over 4
                   12845: 
                   12846: =item freshen_cache
                   12847: 
                   12848: If defined, and the environment cache for the course is valid, it is 
                   12849: returned in the returned hash.
                   12850: 
                   12851: =item one_time
                   12852: 
                   12853: If defined, the last cache time is set to _now_
                   12854: 
                   12855: =item user
                   12856: 
                   12857: If defined, the supplied username is used instead of the current user.
                   12858: 
                   12859: 
                   12860: =back
                   12861: 
1.191     harris41 12862: =item *
                   12863: 
1.624     albertel 12864: resdata($name,$domain,$type,@which) : request for current parameter
                   12865: setting for a specific $type, where $type is either 'course' or 'user',
                   12866: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  12867: answers for 10 minutes.
1.243     albertel 12868: 
1.877     foxr     12869: =item *
                   12870: 
                   12871: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12872: data base, returning a hash that is keyed by the resource name and has
                   12873: values that are the resource value.  I believe that the timestamps and
                   12874: versions are also returned.
                   12875: 
1.1236    raeburn  12876: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   12877: supplemental content area. This routine caches the number of files for 
                   12878: 10 minutes.
                   12879: 
1.243     albertel 12880: =back
                   12881: 
                   12882: =head2 Course Modification
                   12883: 
                   12884: =over 4
1.191     harris41 12885: 
                   12886: =item *
                   12887: 
1.243     albertel 12888: writecoursepref($courseid,%prefs) : write preferences (environment
                   12889: database) for a course
1.191     harris41 12890: 
                   12891: =item *
                   12892: 
1.1011    raeburn  12893: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12894: 
                   12895: =item *
                   12896: 
1.1038    raeburn  12897: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12898: 
1.1167    droeschl 12899: =item *
                   12900: 
                   12901: is_course($courseid), is_course($cdom, $cnum)
                   12902: 
                   12903: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12904: two component version $cdom, $cnum. It checks if the specified course exists.
                   12905: 
                   12906: Returns:
                   12907:     undef if the course doesn't exist, otherwise
                   12908:     in scalar context the combined courseid.
                   12909:     in list context the two components of the course identifier, domain and 
                   12910:     courseid.    
                   12911: 
1.243     albertel 12912: =back
                   12913: 
                   12914: =head2 Resource Subroutines
                   12915: 
                   12916: =over 4
1.191     harris41 12917: 
                   12918: =item *
                   12919: 
1.243     albertel 12920: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12921: 
                   12922: =item *
                   12923: 
1.243     albertel 12924: repcopy($filename) : subscribes to the requested file, and attempts to
                   12925: replicate from the owning library server, Might return
1.607     raeburn  12926: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12927: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12928: resource. Expects the local filesystem pathname
                   12929: (/home/httpd/html/res/....)
                   12930: 
                   12931: =back
                   12932: 
                   12933: =head2 Resource Information
                   12934: 
                   12935: =over 4
1.191     harris41 12936: 
                   12937: =item *
                   12938: 
1.1228    raeburn  12939: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   12940: and returns the value of a variety of different possible values,
                   12941: $varname should be a request string, and the other parameters can be
                   12942: used to specify who and what one is asking about. Ordinarily, $cid 
                   12943: does not need to be specified, as it is retrived from 
                   12944: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   12945: within lonuserstate::loadmap() when initializing a course, before
                   12946: $env{'request.course.id'} has been set, so it needs to be provided
                   12947: in that one case.
1.243     albertel 12948: 
                   12949: Possible values for $varname are environment.lastname (or other item
                   12950: from the envirnment hash), user.name (or someother aspect about the
                   12951: user), resource.0.maxtries (or some other part and parameter of a
                   12952: resource)
1.204     albertel 12953: 
                   12954: =item *
                   12955: 
1.243     albertel 12956: directcondval($number) : get current value of a condition; reads from a state
                   12957: string
1.204     albertel 12958: 
                   12959: =item *
                   12960: 
1.243     albertel 12961: condval($condidx) : value of condition index based on state
1.204     albertel 12962: 
                   12963: =item *
                   12964: 
1.243     albertel 12965: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12966: resource's metadata, $what should be either a specific key, or either
                   12967: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12968: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12969: 
                   12970: this function automatically caches all requests
1.191     harris41 12971: 
                   12972: =item *
                   12973: 
1.243     albertel 12974: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12975: network of library servers; returns file handle of where SQL and regex results
                   12976: will be stored for query
1.191     harris41 12977: 
                   12978: =item *
                   12979: 
1.243     albertel 12980: symbread($filename) : return symbolic list entry (filename argument optional);
                   12981: returns the data handle
1.191     harris41 12982: 
                   12983: =item *
                   12984: 
1.1190    raeburn  12985: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12986: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12987: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12988: on failure, user must be in a course, as it assumes the existence of
                   12989: the course initial hash, and uses $env('request.course.id'}.  The third
                   12990: arg is an optional reference to a scalar.  If this arg is passed in the 
                   12991: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12992: encrypted; otherwise it will be null.  
1.191     harris41 12993: 
                   12994: =item *
                   12995: 
1.243     albertel 12996: symbclean($symb) : removes versions numbers from a symb, returns the
                   12997: cleaned symb
1.191     harris41 12998: 
                   12999: =item *
                   13000: 
1.243     albertel 13001: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13002: course map, user must be in a course for it to work.
1.191     harris41 13003: 
                   13004: =item *
                   13005: 
1.243     albertel 13006: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13007: 
                   13008: =item *
                   13009: 
1.243     albertel 13010: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13011: a random seed, all arguments are optional, if they aren't sent it uses the
                   13012: environment to derive them. Note: if symb isn't sent and it can't get one
                   13013: from &symbread it will use the current time as its return value
1.191     harris41 13014: 
                   13015: =item *
                   13016: 
1.243     albertel 13017: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13018: unfakeable, receipt
1.191     harris41 13019: 
                   13020: =item *
                   13021: 
1.620     albertel 13022: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13023: 
                   13024: =item *
                   13025: 
1.243     albertel 13026: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13027: 
                   13028: =item *
                   13029: 
1.243     albertel 13030: 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 13031: 
                   13032: =item *
                   13033: 
1.243     albertel 13034: 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 13035: 
                   13036: =item *
                   13037: 
1.243     albertel 13038: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13039: 
                   13040: =item *
                   13041: 
1.243     albertel 13042: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13043: forcing spreadsheet to reevaluate the resource scores next time.
                   13044: 
1.1195    raeburn  13045: =item * 
                   13046: 
1.1196    raeburn  13047: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13048: when viewing in course context.
1.1195    raeburn  13049: 
1.1196    raeburn  13050:  input: six args -- filename (decluttered), course number, course domain,
                   13051:                     url, symb (if registered) and group (if this is a 
                   13052:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13053: 
1.1196    raeburn  13054:  output: array of five scalars --
1.1195    raeburn  13055:          $cfile -- url for file editing if editable on current server
                   13056:          $home -- homeserver of resource (i.e., for author if published,
                   13057:                                           or course if uploaded.).
                   13058:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13059:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13060:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13061: 
                   13062: =item *
                   13063: 
                   13064: is_course_upload($file,$cnum,$cdom)
                   13065: 
                   13066: Used in course context to determine if current file was uploaded to 
                   13067: the course (i.e., would be found in /userfiles/docs on the course's 
                   13068: homeserver.
                   13069: 
                   13070:   input: 3 args -- filename (decluttered), course number and course domain.
                   13071:   output: boolean -- 1 if file was uploaded.
                   13072: 
1.243     albertel 13073: =back
                   13074: 
                   13075: =head2 Storing/Retreiving Data
                   13076: 
                   13077: =over 4
1.191     harris41 13078: 
                   13079: =item *
                   13080: 
1.243     albertel 13081: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13082: for this url; hashref needs to be given and should be a \%hashname; the
                   13083: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13084: be derived from the env
1.191     harris41 13085: 
                   13086: =item *
                   13087: 
1.243     albertel 13088: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13089: uses critical subroutine
1.191     harris41 13090: 
                   13091: =item *
                   13092: 
1.243     albertel 13093: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13094: all args are optional
1.191     harris41 13095: 
                   13096: =item *
                   13097: 
1.717     albertel 13098: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13099: dumps the complete (or key matching regexp) namespace into a hash
                   13100: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13101: normally &store()ed into
                   13102: 
                   13103: $range should be either an integer '100' (give me the first 100
                   13104:                                            matching records)
                   13105:               or be  two integers sperated by a - with no spaces
                   13106:                  '30-50' (give me the 30th through the 50th matching
                   13107:                           records)
                   13108: 
                   13109: 
                   13110: =item *
                   13111: 
                   13112: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13113: replaces a &store() version of data with a replacement set of data
                   13114: for a particular resource in a namespace passed in the $storehash hash 
                   13115: reference
                   13116: 
                   13117: =item *
                   13118: 
1.243     albertel 13119: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13120: works very similar to store/cstore, but all data is stored in a
                   13121: temporary location and can be reset using tmpreset, $storehash should
                   13122: be a hash reference, returns nothing on success
1.191     harris41 13123: 
                   13124: =item *
                   13125: 
1.243     albertel 13126: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13127: similar to restore, but all data is stored in a temporary location and
                   13128: can be reset using tmpreset. Returns a hash of values on success,
                   13129: error string otherwise.
1.191     harris41 13130: 
                   13131: =item *
                   13132: 
1.243     albertel 13133: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13134: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13135: 
                   13136: =item *
                   13137: 
1.243     albertel 13138: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13139: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13140: 
                   13141: =item *
                   13142: 
1.243     albertel 13143: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13144: namesp ($udom and $uname are optional)
1.191     harris41 13145: 
                   13146: =item *
                   13147: 
1.702     albertel 13148: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13149: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13150: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13151: 
1.702     albertel 13152: $range should be either an integer '100' (give me the first 100
                   13153:                                            matching records)
                   13154:               or be  two integers sperated by a - with no spaces
                   13155:                  '30-50' (give me the 30th through the 50th matching
                   13156:                           records)
1.449     matthew  13157: =item *
                   13158: 
                   13159: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13160: $store can be a scalar, an array reference, or if the amount to be 
                   13161: incremented is > 1, a hash reference.
                   13162: 
                   13163: ($udom and $uname are optional)
1.191     harris41 13164: 
                   13165: =item *
                   13166: 
1.243     albertel 13167: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13168: ($udom and $uname are optional)
1.191     harris41 13169: 
                   13170: =item *
                   13171: 
1.243     albertel 13172: cput($namespace,$storehash,$udom,$uname) : critical put
                   13173: ($udom and $uname are optional)
1.191     harris41 13174: 
                   13175: =item *
                   13176: 
1.748     albertel 13177: newput($namespace,$storehash,$udom,$uname) :
                   13178: 
                   13179: Attempts to store the items in the $storehash, but only if they don't
                   13180: currently exist, if this succeeds you can be certain that you have 
                   13181: successfully created a new key value pair in the $namespace db.
                   13182: 
                   13183: 
                   13184: Args:
                   13185:  $namespace: name of database to store values to
                   13186:  $storehash: hashref to store to the db
                   13187:  $udom: (optional) domain of user containing the db
                   13188:  $uname: (optional) name of user caontaining the db
                   13189: 
                   13190: Returns:
                   13191:  'ok' -> succeeded in storing all keys of $storehash
                   13192:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13193:                         least <key> already existed in the db (other
                   13194:                         requested keys may also already exist)
1.967     bisitz   13195:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13196:  'con_lost' -> unable to contact request server
                   13197:  'refused' -> action was not allowed by remote machine
                   13198: 
                   13199: 
                   13200: =item *
                   13201: 
1.243     albertel 13202: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13203: reference filled in from namesp (encrypts the return communication)
                   13204: ($udom and $uname are optional)
1.191     harris41 13205: 
                   13206: =item *
                   13207: 
1.243     albertel 13208: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13209: critical subroutine
                   13210: 
1.806     raeburn  13211: =item *
                   13212: 
1.860     raeburn  13213: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13214: array reference filled in from namespace found in domain level on either
                   13215: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13216: 
                   13217: =item *
                   13218: 
1.860     raeburn  13219: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13220: domain level either on specified domain server ($uhome) or primary domain 
                   13221: server ($udom and $uhome are optional)
1.806     raeburn  13222: 
1.943     raeburn  13223: =item * 
                   13224: 
1.1240  ! raeburn  13225: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
        !          13226: for: authentication, language, quotas, timezone, date locale, and portal URL in
        !          13227: the target domain.
        !          13228: 
        !          13229: May also include additional key => value pairs for the following groups:
        !          13230: 
        !          13231: =over
        !          13232: 
        !          13233: =item
        !          13234: disk quotas (MB allocated by default to portfolios and authoring spaces).
        !          13235: 
        !          13236: =over
        !          13237: 
        !          13238: =item defaultquota, authorquota
        !          13239: 
        !          13240: =back
        !          13241: 
        !          13242: =item
        !          13243: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
        !          13244: portfolio for users).
        !          13245: 
        !          13246: =over
        !          13247: 
        !          13248: =item
        !          13249: aboutme, blog, webdav, portfolio
        !          13250: 
        !          13251: =back
        !          13252: 
        !          13253: =item
        !          13254: requestcourses: ability to request courses, and how requests are processed.
        !          13255: 
        !          13256: =over
        !          13257: 
        !          13258: =item
        !          13259: official, unofficial, community
        !          13260: 
        !          13261: =back
        !          13262: 
        !          13263: =item
        !          13264: inststatus: types of institutional affiliation, and order in which they are displayed.
        !          13265: 
        !          13266: =over
        !          13267: 
        !          13268: =item
        !          13269: inststatustypes, inststatusorder
        !          13270: 
        !          13271: =back
        !          13272: 
        !          13273: =item
        !          13274: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
        !          13275: for course's uploaded content.
        !          13276: 
        !          13277: =over
        !          13278: 
        !          13279: =item
        !          13280: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
        !          13281: 
        !          13282: =back
        !          13283: 
        !          13284: =item
        !          13285: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
        !          13286: on your servers.
        !          13287: 
        !          13288: =over
        !          13289: 
        !          13290: =item 
        !          13291: remotesessions, hostedsessions
        !          13292: 
        !          13293: =back
        !          13294: 
        !          13295: =back
        !          13296: 
        !          13297: In cases where a domain coordinator has never used the "Set Domain Configuration"
        !          13298: utility to create a configuration.db file on a domain's primary library server 
        !          13299: only the following domain defaults: auth_def, auth_arg_def, lang_def
        !          13300: -- corresponding values are authentication type (internal, krb4, krb5,
        !          13301: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
        !          13302: will be available. Values are retrieved from cache (if current), unless the
        !          13303: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
        !          13304: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
        !          13305: 
        !          13306: Typical usage:
1.943     raeburn  13307: 
1.1240  ! raeburn  13308: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13309: 
1.243     albertel 13310: =back
                   13311: 
                   13312: =head2 Network Status Functions
                   13313: 
                   13314: =over 4
1.191     harris41 13315: 
                   13316: =item *
                   13317: 
1.1137    raeburn  13318: dirlist() : return directory list based on URI (first arg).
                   13319: 
                   13320: Inputs: 1 required, 5 optional.
                   13321: 
                   13322: =over
                   13323: 
                   13324: =item 
                   13325: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13326: 
                   13327: =item
                   13328: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13329: 
                   13330: =item
                   13331: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13332: 
                   13333: =item
                   13334: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13335: 
                   13336: =item
                   13337: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13338: 
                   13339: =item 
                   13340: $alternateRoot - path to prepend in place of path from $uri.
                   13341: 
                   13342: =back
                   13343: 
                   13344: Returns: Array of up to two items.
                   13345: 
                   13346: =over
                   13347: 
                   13348: a reference to an array of files/subdirectories
                   13349: 
                   13350: =over
                   13351: 
                   13352: Each element in the array of files/subdirectories is a & separated list of
                   13353: item name and the result of running stat on the item.  If dirlist was requested
                   13354: for a file instead of a directory, the item name will be ''. For a directory 
                   13355: listing, if the item is a metadata file, the element will end &N&M 
                   13356: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13357: default copyright set (1).  
                   13358: 
                   13359: =back
                   13360: 
                   13361: a scalar containing error condition (if encountered).
                   13362: 
                   13363: =over
                   13364: 
                   13365: =item 
                   13366: no_host (no homeserver identified for $username:$domain).
                   13367: 
                   13368: =item 
                   13369: no_such_host (server contacted for listing not identified as valid host).
                   13370: 
                   13371: =item 
                   13372: con_lost (connection to remote server failed).
                   13373: 
                   13374: =item 
                   13375: refused (invalid $username:$domain received on lond side).
                   13376: 
                   13377: =item 
                   13378: no_such_dir (directory at specified path on lond side does not exist). 
                   13379: 
                   13380: =item 
                   13381: empty (directory at specified path on lond side is empty).
                   13382: 
                   13383: =over
                   13384: 
                   13385: This is currently not encountered because the &ls3, &ls2, 
                   13386: &ls (_handler) routines on the lond side do not filter out
                   13387: . and .. from a directory listing. 
                   13388: 
                   13389: =back
                   13390: 
                   13391: =back
                   13392: 
                   13393: =back
1.191     harris41 13394: 
                   13395: =item *
                   13396: 
1.243     albertel 13397: spareserver() : find server with least workload from spare.tab
                   13398: 
1.986     foxr     13399: 
                   13400: =item *
                   13401: 
                   13402: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13403: if there is no corresponding loncapa host.
                   13404: 
1.243     albertel 13405: =back
                   13406: 
1.986     foxr     13407: 
1.243     albertel 13408: =head2 Apache Request
                   13409: 
                   13410: =over 4
1.191     harris41 13411: 
                   13412: =item *
                   13413: 
1.243     albertel 13414: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13415: localhost, posts hash
                   13416: 
                   13417: =back
                   13418: 
                   13419: =head2 Data to String to Data
                   13420: 
                   13421: =over 4
1.191     harris41 13422: 
                   13423: =item *
                   13424: 
1.243     albertel 13425: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13426: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13427: 
                   13428: =item *
                   13429: 
1.243     albertel 13430: hashref2str($hashref) : convert a hashref into a string complete with
                   13431: escaping and '=' and '&' separators, supports elements that are
                   13432: arrayrefs and hashrefs
1.191     harris41 13433: 
                   13434: =item *
                   13435: 
1.243     albertel 13436: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13437: with escaping and '&' separators, supports elements that are arrayrefs
                   13438: and hashrefs
1.191     harris41 13439: 
                   13440: =item *
                   13441: 
1.243     albertel 13442: str2hash($string) : convert string to hash using unescaping and
                   13443: splitting on '=' and '&', supports elements that are arrayrefs and
                   13444: hashrefs
1.191     harris41 13445: 
                   13446: =item *
                   13447: 
1.243     albertel 13448: str2array($string) : convert string to hash using unescaping and
                   13449: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13450: 
                   13451: =back
                   13452: 
                   13453: =head2 Logging Routines
                   13454: 
                   13455: 
                   13456: These routines allow one to make log messages in the lonnet.log and
                   13457: lonnet.perm logfiles.
1.191     harris41 13458: 
1.1119    foxr     13459: =over 4
                   13460: 
1.191     harris41 13461: =item *
                   13462: 
1.243     albertel 13463: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13464: 
                   13465: =item *
                   13466: 
1.243     albertel 13467: logthis() : append message to the normal lonnet.log file, it gets
                   13468: preiodically rolled over and deleted.
1.191     harris41 13469: 
                   13470: =item *
                   13471: 
1.243     albertel 13472: logperm() : append a permanent message to lonnet.perm.log, this log
                   13473: file never gets deleted by any automated portion of the system, only
                   13474: messages of critical importance should go in here.
                   13475: 
1.1119    foxr     13476: 
1.243     albertel 13477: =back
                   13478: 
                   13479: =head2 General File Helper Routines
                   13480: 
                   13481: =over 4
1.191     harris41 13482: 
                   13483: =item *
                   13484: 
1.481     raeburn  13485: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13486: (a) files in /uploaded
                   13487:   (i) If a local copy of the file exists - 
                   13488:       compares modification date of local copy with last-modified date for 
                   13489:       definitive version stored on home server for course. If local copy is 
                   13490:       stale, requests a new version from the home server and stores it. 
                   13491:       If the original has been removed from the home server, then local copy 
                   13492:       is unlinked.
                   13493:   (ii) If local copy does not exist -
                   13494:       requests the file from the home server and stores it. 
                   13495:   
                   13496:   If $caller is 'uploadrep':  
                   13497:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13498:     for request for files originally uploaded via DOCS. 
                   13499:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13500:   
                   13501:   Otherwise:
                   13502:      This indicates a call from the content generation phase of the request.
                   13503:      -  returns the entire contents of the file or -1.
                   13504:      
                   13505: (b) files in /res
                   13506:    - returns the entire contents of a file or -1; 
                   13507:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13508: 
1.712     albertel 13509: 
                   13510: =item *
                   13511: 
                   13512: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13513:                   reference
                   13514: 
                   13515: returns either a stat() list of data about the file or an empty list
                   13516: if the file doesn't exist or couldn't find out about it (connection
                   13517: problems or user unknown)
                   13518: 
1.191     harris41 13519: =item *
                   13520: 
1.243     albertel 13521: filelocation($dir,$file) : returns file system location of a file
                   13522: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13523: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13524: and a file of ../bob will become /a/bob)
1.191     harris41 13525: 
                   13526: =item *
                   13527: 
                   13528: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13529: filelocation except for hrefs
                   13530: 
                   13531: =item *
                   13532: 
                   13533: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13534: 
1.243     albertel 13535: =back
                   13536: 
1.608     albertel 13537: =head2 Usererfile file routines (/uploaded*)
                   13538: 
                   13539: =over 4
                   13540: 
                   13541: =item *
                   13542: 
                   13543: userfileupload(): main rotine for putting a file in a user or course's
                   13544:                   filespace, arguments are,
                   13545: 
1.620     albertel 13546:  formname - required - this is the name of the element in $env where the
1.608     albertel 13547:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13548:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13549:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13550:  context - if coursedoc, store the file in the course of the active role
                   13551:              of the current user; 
                   13552:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13553:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13554:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13555:          if undefined, it will be placed in "unknown"
                   13556: 
                   13557:  (This routine calls clean_filename() to remove any dangerous
                   13558:  characters from the filename, and then calls finuserfileupload() to
                   13559:  complete the transaction)
                   13560: 
                   13561:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13562:  and /adm/notfound.html if unsuccessful
                   13563: 
                   13564: =item *
                   13565: 
                   13566: clean_filename(): routine for cleaing a filename up for storage in
                   13567:                  userfile space, argument is:
                   13568: 
                   13569:  filename - proposed filename
                   13570: 
                   13571: returns: the new clean filename
                   13572: 
                   13573: =item *
                   13574: 
1.1090    raeburn  13575: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13576: userspace, probably shouldn't be called directly
                   13577: 
                   13578:   docuname: username or courseid of destination for the file
                   13579:   docudom: domain of user/course of destination for the file
                   13580:   formname: same as for userfileupload()
1.1090    raeburn  13581:   fname: filename (including subdirectories) for the file
                   13582:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13583:   allfiles: reference to hash used to store objects found by parser
                   13584:   codebase: reference to hash used for codebases of java objects found by parser
                   13585:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13586:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13587:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13588:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13589:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13590:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13591:   mimetype: reference to scalar to accommodate mime type determined
                   13592:             from File::MMagic if $parser = parse.
1.608     albertel 13593: 
                   13594:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13595:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13596:  was 'overwrite').
                   13597:  
1.608     albertel 13598: 
                   13599: =item *
                   13600: 
                   13601: renameuserfile(): renames an existing userfile to a new name
                   13602: 
                   13603:   Args:
                   13604:    docuname: username or courseid of destination for the file
                   13605:    docudom: domain of user/course of destination for the file
                   13606:    old: current file name (including any subdirs under userfiles)
                   13607:    new: desired file name (including any subdirs under userfiles)
                   13608: 
                   13609: =item *
                   13610: 
                   13611: mkdiruserfile(): creates a directory is a userfiles dir
                   13612: 
                   13613:   Args:
                   13614:    docuname: username or courseid of destination for the file
                   13615:    docudom: domain of user/course of destination for the file
                   13616:    dir: dir to create (including any subdirs under userfiles)
                   13617: 
                   13618: =item *
                   13619: 
                   13620: removeuserfile(): removes a file that exists in userfiles
                   13621: 
                   13622:   Args:
                   13623:    docuname: username or courseid of destination for the file
                   13624:    docudom: domain of user/course of destination for the file
                   13625:    fname: filname to delete (including any subdirs under userfiles)
                   13626: 
                   13627: =item *
                   13628: 
                   13629: removeuploadedurl(): convience function for removeuserfile()
                   13630: 
                   13631:   Args:
                   13632:    url:  a full /uploaded/... url to delete
                   13633: 
1.747     albertel 13634: =item * 
                   13635: 
                   13636: get_portfile_permissions():
                   13637:   Args:
                   13638:     domain: domain of user or course contain the portfolio files
                   13639:     user: name of user or num of course contain the portfolio files
                   13640:   Returns:
                   13641:     hashref of a dump of the proper file_permissions.db
                   13642:    
                   13643: 
                   13644: =item * 
                   13645: 
                   13646: get_access_controls():
                   13647: 
                   13648: Args:
                   13649:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13650:   group: (optional) the group you want the files associated with
                   13651:   file: (optional) the file you want access info on
                   13652: 
                   13653: Returns:
1.749     raeburn  13654:     a hash (keys are file names) of hashes containing
                   13655:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13656:         values are XML containing access control settings (see below) 
1.747     albertel 13657: 
                   13658: Internal notes:
                   13659: 
1.749     raeburn  13660:  access controls are stored in file_permissions.db as key=value pairs.
                   13661:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13662:         where scope -> public,guest,course,group,domains or users.
                   13663:               end -> UNIX time for end of access (0 -> no end date)
                   13664:               start -> UNIX time for start of access
                   13665: 
                   13666:     value -> XML description of access control
                   13667:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13668:             <start></start>
                   13669:             <end></end>
                   13670: 
                   13671:             <password></password>  for scope type = guest
                   13672: 
                   13673:             <domain></domain>     for scope type = course or group
                   13674:             <number></number>
                   13675:             <roles id="">
                   13676:              <role></role>
                   13677:              <access></access>
                   13678:              <section></section>
                   13679:              <group></group>
                   13680:             </roles>
                   13681: 
                   13682:             <dom></dom>         for scope type = domains
                   13683: 
                   13684:             <users>             for scope type = users
                   13685:              <user>
                   13686:               <uname></uname>
                   13687:               <udom></udom>
                   13688:              </user>
                   13689:             </users>
                   13690:            </scope> 
                   13691:               
                   13692:  Access data is also aggregated for each file in an additional key=value pair:
                   13693:  key -> path to file/file_name\0accesscontrol 
                   13694:  value -> reference to hash
                   13695:           hash contains key = value pairs
                   13696:           where key = uniqueID:scope_end_start
                   13697:                 value = UNIX time record was last updated
                   13698: 
                   13699:           Used to improve speed of look-ups of access controls for each file.  
                   13700:  
                   13701:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13702: 
1.1198    raeburn  13703: =item *
                   13704: 
1.749     raeburn  13705: modify_access_controls():
                   13706: 
                   13707: Modifies access controls for a portfolio file
                   13708: Args
                   13709: 1. file name
                   13710: 2. reference to hash of required changes,
                   13711: 3. domain
                   13712: 4. username
                   13713:   where domain,username are the domain of the portfolio owner 
                   13714:   (either a user or a course) 
                   13715: 
                   13716: Returns:
                   13717: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13718: 2. result of deletions ('ok' or 'error', with error message).
                   13719: 3. reference to hash of any new or updated access controls.
                   13720: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13721:    key = integer (inbound ID)
1.1198    raeburn  13722:    value = uniqueID
                   13723: 
                   13724: =item *
                   13725: 
                   13726: get_timebased_id():
                   13727: 
                   13728: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13729: course via the Course Editor (e.g., folders, composite pages, 
                   13730: group bulletin boards).
                   13731: 
                   13732: Args: (first three required; six others optional)
                   13733: 
                   13734: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13735:    docssequence, or name of group
                   13736: 
                   13737: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13738:    e.g., num, boardids
                   13739: 
                   13740: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   13741:    file will be named nohist_namespace.db
                   13742: 
                   13743: 4. cdom: domain of course; default is current course domain from %env
                   13744: 
                   13745: 5. cnum: course number; default is current course number from %env
                   13746: 
                   13747: 6. idtype: set to concat if an additional digit is to be appended to the 
                   13748:    unix timestamp to form the suffix, if the plain timestamp is already
                   13749:    in use.  Default is to not do this, but simply increment the unix 
                   13750:    timestamp by 1 until a unique key is obtained.
                   13751: 
                   13752: 7. who: holder of locking key; defaults to user:domain for user.
                   13753: 
                   13754: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   13755:    retrying); default is 3.
                   13756: 
                   13757: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   13758: 
                   13759: Returns:
                   13760: 
                   13761: 1. suffix obtained (numeric)
                   13762: 
                   13763: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13764: 
                   13765: 3. error: contains (localized) error message if an error occurred.
                   13766: 
1.747     albertel 13767: 
1.608     albertel 13768: =back
                   13769: 
1.243     albertel 13770: =head2 HTTP Helper Routines
                   13771: 
                   13772: =over 4
                   13773: 
1.191     harris41 13774: =item *
                   13775: 
                   13776: escape() : unpack non-word characters into CGI-compatible hex codes
                   13777: 
                   13778: =item *
                   13779: 
                   13780: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13781: 
1.243     albertel 13782: =back
                   13783: 
                   13784: =head1 PRIVATE SUBROUTINES
                   13785: 
                   13786: =head2 Underlying communication routines (Shouldn't call)
                   13787: 
                   13788: =over 4
                   13789: 
                   13790: =item *
                   13791: 
                   13792: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13793: 
                   13794: =item *
                   13795: 
                   13796: reply() : uses subreply to send a message to remote machine, logs all failures
                   13797: 
                   13798: =item *
                   13799: 
                   13800: critical() : passes a critical message to another server; if cannot
                   13801: get through then place message in connection buffer directory and
                   13802: returns con_delayed, if incapable of saving message, returns
                   13803: con_failed
                   13804: 
                   13805: =item *
                   13806: 
                   13807: reconlonc() : tries to reconnect lonc client processes.
                   13808: 
                   13809: =back
                   13810: 
                   13811: =head2 Resource Access Logging
                   13812: 
                   13813: =over 4
                   13814: 
                   13815: =item *
                   13816: 
                   13817: flushcourselogs() : flush (save) buffer logs and access logs
                   13818: 
                   13819: =item *
                   13820: 
                   13821: courselog($what) : save message for course in hash
                   13822: 
                   13823: =item *
                   13824: 
                   13825: courseacclog($what) : save message for course using &courselog().  Perform
                   13826: special processing for specific resource types (problems, exams, quizzes, etc).
                   13827: 
1.191     harris41 13828: =item *
                   13829: 
                   13830: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13831: as a PerlChildExitHandler
1.243     albertel 13832: 
                   13833: =back
                   13834: 
                   13835: =head2 Other
                   13836: 
                   13837: =over 4
                   13838: 
                   13839: =item *
                   13840: 
                   13841: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13842: 
                   13843: =back
                   13844: 
                   13845: =cut
1.877     foxr     13846: 

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