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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1242  ! raeburn     4: # $Id: lonnet.pm,v 1.1241 2013/10/06 20:33:51 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 {
1.1241    raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364:     return $response;
                    365: }
                    366: 
1.1       albertel  367: # -------------------------------------------------- Non-critical communication
                    368: sub subreply {
                    369:     my ($cmd,$server)=@_;
1.838     albertel  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      371:     #
                    372:     #  With loncnew process trimming, there's a timing hole between lonc server
                    373:     #  process exit and the master server picking up the listen on the AF_UNIX
                    374:     #  socket.  In that time interval, a lock file will exist:
                    375: 
                    376:     my $lockfile=$peerfile.".lock";
                    377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    378: 	sleep(1);
                    379:     }
                    380:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      381:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      382:     #
1.550     foxr      383:     #   We'll give the connection a few tries before abandoning it.  If
                    384:     #   connection is not possible, we'll con_lost back to the client.
                    385:     #   
                    386:     my $client;
                    387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    389: 				      Type    => SOCK_STREAM,
                    390: 				      Timeout => 10);
1.869     albertel  391: 	if ($client) {
1.550     foxr      392: 	    last;		# Connected!
1.850     albertel  393: 	} else {
1.853     albertel  394: 	    &create_connection(&hostname($server),$server);
1.550     foxr      395: 	}
1.850     albertel  396:         sleep(1);		# Try again later if failed connection.
1.550     foxr      397:     }
                    398:     my $answer;
                    399:     if ($client) {
1.704     albertel  400: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      401: 	$answer=<$client>;
                    402: 	if (!$answer) { $answer="con_lost"; }
                    403: 	chomp($answer);
                    404:     } else {
                    405: 	$answer = 'con_lost';	# Failed connection.
                    406:     }
1.1       albertel  407:     return $answer;
                    408: }
                    409: 
                    410: sub reply {
                    411:     my ($cmd,$server)=@_;
1.838     albertel  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  413:     my $answer=subreply($cmd,$server);
1.65      www       414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  415:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       416:                 " $cmd to $server returned $answer</font>");
                    417:     }
1.1       albertel  418:     return $answer;
                    419: }
                    420: 
                    421: # ----------------------------------------------------------- Send USR1 to lonc
                    422: 
                    423: sub reconlonc {
1.891     albertel  424:     my ($lonid) = @_;
                    425:     my $hostname = &hostname($lonid);
                    426:     if ($lonid) {
                    427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    428: 	if ($hostname && -e $peerfile) {
                    429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    431: 					     Type    => SOCK_STREAM,
                    432: 					     Timeout => 10);
                    433: 	    if ($client) {
                    434: 		print $client ("reset_retries\n");
                    435: 		my $answer=<$client>;
                    436: 		#reset just this one.
                    437: 	    }
                    438: 	}
                    439: 	return;
                    440:     }
                    441: 
1.836     www       442:     &logthis("Trying to reconnect lonc");
1.1       albertel  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  444:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  445: 	my $loncpid=<$fh>;
                    446:         chomp($loncpid);
                    447:         if (kill 0 => $loncpid) {
                    448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    449:             kill USR1 => $loncpid;
                    450:             sleep 1;
1.836     www       451:          } else {
1.12      www       452: 	    &logthis(
1.672     albertel  453:                "<font color=\"blue\">WARNING:".
1.12      www       454:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  455:         }
                    456:     } else {
1.836     www       457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  458:     }
                    459: }
                    460: 
                    461: # ------------------------------------------------------ Critical communication
1.12      www       462: 
1.1       albertel  463: sub critical {
                    464:     my ($cmd,$server)=@_;
1.838     albertel  465:     unless (&hostname($server)) {
1.672     albertel  466:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       467:                " Critical message to unknown server ($server)</font>");
                    468:         return 'no_such_host';
                    469:     }
1.1       albertel  470:     my $answer=reply($cmd,$server);
                    471:     if ($answer eq 'con_lost') {
                    472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  473: 	my $answer=reply($cmd,$server);
1.1       albertel  474:         if ($answer eq 'con_lost') {
                    475:             my $now=time;
                    476:             my $middlename=$cmd;
1.5       www       477:             $middlename=substr($middlename,0,16);
1.1       albertel  478:             $middlename=~s/\W//g;
                    479:             my $dfilename=
1.305     www       480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    481:             $dumpcount++;
1.1       albertel  482:             {
1.448     albertel  483: 		my $dfh;
                    484: 		if (open($dfh,">$dfilename")) {
                    485: 		    print $dfh "$cmd\n"; 
                    486: 		    close($dfh);
                    487: 		}
1.1       albertel  488:             }
                    489:             sleep 2;
                    490:             my $wcmd='';
                    491:             {
1.448     albertel  492: 		my $dfh;
                    493: 		if (open($dfh,"<$dfilename")) {
                    494: 		    $wcmd=<$dfh>; 
                    495: 		    close($dfh);
                    496: 		}
1.1       albertel  497:             }
                    498:             chomp($wcmd);
1.7       www       499:             if ($wcmd eq $cmd) {
1.672     albertel  500: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       501:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  502:                 &logperm("D:$server:$cmd");
                    503: 	        return 'con_delayed';
                    504:             } else {
1.672     albertel  505:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       506:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  507:                 &logperm("F:$server:$cmd");
                    508:                 return 'con_failed';
                    509:             }
                    510:         }
                    511:     }
                    512:     return $answer;
1.405     albertel  513: }
                    514: 
1.755     albertel  515: # ------------------------------------------- check if return value is an error
                    516: 
                    517: sub error {
                    518:     my ($result) = @_;
1.756     albertel  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  520: 	if ($2 == 2) { return undef; }
                    521: 	return $1;
                    522:     }
                    523:     return undef;
                    524: }
                    525: 
1.783     albertel  526: sub convert_and_load_session_env {
                    527:     my ($lonidsdir,$handle)=@_;
                    528:     my @profile;
                    529:     {
1.917     albertel  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    531: 	if (!$opened) {
1.915     albertel  532: 	    return 0;
                    533: 	}
1.783     albertel  534: 	flock($idf,LOCK_SH);
                    535: 	@profile=<$idf>;
                    536: 	close($idf);
                    537:     }
                    538:     my %temp_env;
                    539:     foreach my $line (@profile) {
1.786     albertel  540: 	if ($line !~ m/=/) {
                    541: 	    return 0;
                    542: 	}
1.783     albertel  543: 	chomp($line);
                    544: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    546:     }
                    547:     unlink("$lonidsdir/$handle.id");
                    548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    549: 	    0640)) {
                    550: 	%disk_env = %temp_env;
                    551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    552: 	untie(%disk_env);
                    553:     }
1.786     albertel  554:     return 1;
1.783     albertel  555: }
                    556: 
1.374     www       557: # ------------------------------------------- Transfer profile into environment
1.780     albertel  558: my $env_loaded;
                    559: sub transfer_profile_to_env {
1.788     albertel  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    561:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       562: 
1.720     albertel  563:     if (!defined($lonidsdir)) {
                    564: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    565:     }
                    566:     if (!defined($handle)) {
                    567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    568:     }
                    569: 
1.786     albertel  570:     my $convert;
                    571:     {
1.917     albertel  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    573: 	if (!$opened) {
1.915     albertel  574: 	    return;
                    575: 	}
1.786     albertel  576: 	flock($idf,LOCK_SH);
                    577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    578: 		&GDBM_READER(),0640)) {
                    579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    580: 	    untie(%disk_env);
                    581: 	} else {
                    582: 	    $convert = 1;
                    583: 	}
                    584:     }
                    585:     if ($convert) {
                    586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    587: 	    &logthis("Failed to load session, or convert session.");
                    588: 	}
1.374     www       589:     }
1.783     albertel  590: 
1.786     albertel  591:     my %remove;
1.783     albertel  592:     while ( my $envname = each(%env) ) {
1.433     matthew   593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    594:             if ($time < time-300) {
1.783     albertel  595:                 $remove{$key}++;
1.433     matthew   596:             }
                    597:         }
                    598:     }
1.783     albertel  599: 
1.619     albertel  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  601:     $env_loaded=1;
1.783     albertel  602:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   603:         &delenv($expired_key);
1.374     www       604:     }
1.1       albertel  605: }
                    606: 
1.916     albertel  607: # ---------------------------------------------------- Check for valid session 
                    608: sub check_for_valid_session {
1.1155    raeburn   609:     my ($r,$name) = @_;
1.916     albertel  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   611:     if ($name eq '') {
                    612:         $name = 'lonID';
                    613:     }
                    614:     my $lonid=$cookies{$name};
1.916     albertel  615:     return undef if (!$lonid);
                    616: 
                    617:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   618:     my $lonidsdir;
                    619:     if ($name eq 'lonDAV') {
                    620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    621:     } else {
                    622:         $lonidsdir=$r->dir_config('lonIDsDir');
                    623:     }
1.916     albertel  624:     return undef if (!-e "$lonidsdir/$handle.id");
                    625: 
1.917     albertel  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    627:     return undef if (!$opened);
1.916     albertel  628: 
                    629:     flock($idf,LOCK_SH);
                    630:     my %disk_env;
                    631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    632: 	    &GDBM_READER(),0640)) {
                    633: 	return undef;	
                    634:     }
                    635: 
                    636:     if (!defined($disk_env{'user.name'})
                    637: 	|| !defined($disk_env{'user.domain'})) {
                    638: 	return undef;
                    639:     }
1.1213    raeburn   640:     if (($r->user() eq '') && ($apache >= 2.4)) {
1.1212    raeburn   641:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    642:             $r->user($disk_env{'user.name'});
                    643:         } else {
                    644:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    645:         }
                    646:     }
1.916     albertel  647:     return $handle;
                    648: }
                    649: 
1.830     albertel  650: sub timed_flock {
                    651:     my ($file,$lock_type) = @_;
                    652:     my $failed=0;
                    653:     eval {
                    654: 	local $SIG{__DIE__}='DEFAULT';
                    655: 	local $SIG{ALRM}=sub {
                    656: 	    $failed=1;
                    657: 	    die("failed lock");
                    658: 	};
                    659: 	alarm(13);
                    660: 	flock($file,$lock_type);
                    661: 	alarm(0);
                    662:     };
                    663:     if ($failed) {
                    664: 	return undef;
                    665:     } else {
                    666: 	return 1;
                    667:     }
                    668: }
                    669: 
1.5       www       670: # ---------------------------------------------------------- Append Environment
                    671: 
                    672: sub appenv {
1.949     raeburn   673:     my ($newenv,$roles) = @_;
                    674:     if (ref($newenv) eq 'HASH') {
                    675:         foreach my $key (keys(%{$newenv})) {
                    676:             my $refused = 0;
                    677: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    678:                 $refused = 1;
                    679:                 if (ref($roles) eq 'ARRAY') {
                    680:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    681:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    682:                         $refused = 0;
                    683:                     }
                    684:                 }
                    685:             }
                    686:             if ($refused) {
                    687:                 &logthis("<font color=\"blue\">WARNING: ".
                    688:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    689:                          .'</font>');
                    690: 	        delete($newenv->{$key});
                    691:             } else {
                    692:                 $env{$key}=$newenv->{$key};
                    693:             }
                    694:         }
                    695:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    696:         if ($opened
                    697: 	    && &timed_flock($env_file,LOCK_EX)
                    698: 	    &&
                    699: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    700: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    701: 	    while (my ($key,$value) = each(%{$newenv})) {
                    702: 	        $disk_env{$key} = $value;
                    703: 	    }
                    704: 	    untie(%disk_env);
1.35      www       705:         }
1.191     harris41  706:     }
1.56      www       707:     return 'ok';
                    708: }
                    709: # ----------------------------------------------------- Delete from Environment
                    710: 
                    711: sub delenv {
1.1104    raeburn   712:     my ($delthis,$regexp,$roles) = @_;
                    713:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    714:         my $refused = 1;
                    715:         if (ref($roles) eq 'ARRAY') {
                    716:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    717:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    718:                 $refused = 0;
                    719:             }
                    720:         }
                    721:         if ($refused) {
                    722:             &logthis("<font color=\"blue\">WARNING: ".
                    723:                      "Attempt to delete from environment ".$delthis);
                    724:             return 'error';
                    725:         }
1.56      www       726:     }
1.917     albertel  727:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    728:     if ($opened
1.915     albertel  729: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  730: 	&&
                    731: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    732: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  733: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   734: 	    if ($regexp) {
                    735:                 if ($key=~/^$delthis/) {
                    736:                     delete($env{$key});
                    737:                     delete($disk_env{$key});
                    738:                 } 
                    739:             } else {
                    740:                 if ($key=~/^\Q$delthis\E/) {
                    741: 		    delete($env{$key});
                    742: 		    delete($disk_env{$key});
                    743: 	        }
                    744:             }
1.448     albertel  745: 	}
1.783     albertel  746: 	untie(%disk_env);
1.5       www       747:     }
                    748:     return 'ok';
1.369     albertel  749: }
                    750: 
1.790     albertel  751: sub get_env_multiple {
                    752:     my ($name) = @_;
                    753:     my @values;
                    754:     if (defined($env{$name})) {
                    755:         # exists is it an array
                    756:         if (ref($env{$name})) {
                    757:             @values=@{ $env{$name} };
                    758:         } else {
                    759:             $values[0]=$env{$name};
                    760:         }
                    761:     }
                    762:     return(@values);
                    763: }
                    764: 
1.958     www       765: # ------------------------------------------------------------------- Locking
                    766: 
                    767: sub set_lock {
                    768:     my ($text)=@_;
                    769:     $locknum++;
                    770:     my $id=$$.'-'.$locknum;
                    771:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    772:              'session.lock.'.$id => $text});
                    773:     return $id;
                    774: }
                    775: 
                    776: sub get_locks {
                    777:     my $num=0;
                    778:     my %texts=();
                    779:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    780:        if ($lock=~/\w/) {
                    781:           $num++;
                    782:           $texts{$lock}=$env{'session.lock.'.$lock};
                    783:        }
                    784:    }
                    785:    return ($num,%texts);
                    786: }
                    787: 
                    788: sub remove_lock {
                    789:     my ($id)=@_;
                    790:     my $newlocks='';
                    791:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    792:        if (($lock=~/\w/) && ($lock ne $id)) {
                    793:           $newlocks.=','.$lock;
                    794:        }
                    795:     }
                    796:     &appenv({'session.locks' => $newlocks});
                    797:     &delenv('session.lock.'.$id);
                    798: }
                    799: 
                    800: sub remove_all_locks {
                    801:     my $activelocks=$env{'session.locks'};
                    802:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    803:        if ($lock=~/\w/) {
                    804:           &remove_lock($lock);
                    805:        }
                    806:     }
                    807: }
                    808: 
                    809: 
1.369     albertel  810: # ------------------------------------------ Find out current server userload
                    811: sub userload {
                    812:     my $numusers=0;
                    813:     {
                    814: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    815: 	my $filename;
                    816: 	my $curtime=time;
                    817: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  818: 	    next if ($filename eq '.' || $filename eq '..');
                    819: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  820: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  821: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  822: 	}
                    823: 	closedir(LONIDS);
                    824:     }
                    825:     my $userloadpercent=0;
                    826:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    827:     if ($maxuserload) {
1.371     albertel  828: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  829:     }
1.372     albertel  830:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  831:     return $userloadpercent;
1.283     www       832: }
                    833: 
1.1       albertel  834: # ------------------------------ Find server with least workload from spare.tab
1.11      www       835: 
1.1       albertel  836: sub spareserver {
1.1083    raeburn   837:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  838:     my $spare_server;
1.370     albertel  839:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  840:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    841:                                                      :  $userloadpercent;
1.1083    raeburn   842:     my ($uint_dom,$remotesessions);
                    843:     if (($udom ne '') && (&domain($udom) ne '')) {
                    844:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    845:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    846:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    847:         $remotesessions = $udomdefaults{'remotesessions'};
                    848:     }
1.1123    raeburn   849:     my $spareshash = &this_host_spares($udom);
                    850:     if (ref($spareshash) eq 'HASH') {
                    851:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    852:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    853:                 if ($uint_dom) {
                    854:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    855:                                                  $try_server));
                    856:                 }
                    857: 	        ($spare_server, $lowest_load) =
                    858: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    859:             }
1.1083    raeburn   860:         }
1.784     albertel  861: 
1.1123    raeburn   862:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    863: 
                    864:         if (!$found_server) {
                    865:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    866: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    867:                     if ($uint_dom) {
                    868:                         next unless (&spare_can_host($udom,$uint_dom,
                    869:                                                      $remotesessions,$try_server));
                    870:                     }
                    871: 	            ($spare_server, $lowest_load) =
                    872: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    873:                 }
                    874: 	    }
                    875:         }
1.784     albertel  876:     }
                    877: 
                    878:     if (!$want_server_name) {
1.968     raeburn   879:         my $protocol = 'http';
                    880:         if ($protocol{$spare_server} eq 'https') {
                    881:             $protocol = $protocol{$spare_server};
                    882:         }
1.1001    raeburn   883:         if (defined($spare_server)) {
                    884:             my $hostname = &hostname($spare_server);
1.1083    raeburn   885:             if (defined($hostname)) {
1.1001    raeburn   886: 	        $spare_server = $protocol.'://'.$hostname;
                    887:             }
                    888:         }
1.784     albertel  889:     }
                    890:     return $spare_server;
                    891: }
                    892: 
                    893: sub compare_server_load {
                    894:     my ($try_server, $spare_server, $lowest_load) = @_;
                    895: 
                    896:     my $loadans     = &reply('load',    $try_server);
                    897:     my $userloadans = &reply('userload',$try_server);
                    898: 
                    899:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   900: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  901:     }
                    902: 
                    903:     my $load;
                    904:     if ($loadans =~ /\d/) {
                    905: 	if ($userloadans =~ /\d/) {
                    906: 	    #both are numbers, pick the bigger one
                    907: 	    $load = ($loadans > $userloadans) ? $loadans 
                    908: 		                              : $userloadans;
1.411     albertel  909: 	} else {
1.784     albertel  910: 	    $load = $loadans;
1.411     albertel  911: 	}
1.784     albertel  912:     } else {
                    913: 	$load = $userloadans;
                    914:     }
                    915: 
                    916:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    917: 	$spare_server = $try_server;
                    918: 	$lowest_load  = $load;
1.370     albertel  919:     }
1.784     albertel  920:     return ($spare_server,$lowest_load);
1.202     matthew   921: }
1.914     albertel  922: 
                    923: # --------------------------- ask offload servers if user already has a session
                    924: sub find_existing_session {
                    925:     my ($udom,$uname) = @_;
1.1123    raeburn   926:     my $spareshash = &this_host_spares($udom);
                    927:     if (ref($spareshash) eq 'HASH') {
                    928:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    929:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    931:             }
                    932:         }
                    933:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
1.914     albertel  938:     }
                    939:     return;
                    940: }
                    941: 
                    942: # -------------------------------- ask if server already has a session for user
                    943: sub has_user_session {
                    944:     my ($lonid,$udom,$uname) = @_;
                    945:     my $result = &reply(join(':','userhassession',
                    946: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    947:     return 1 if ($result eq 'ok');
                    948: 
                    949:     return 0;
                    950: }
                    951: 
1.1076    raeburn   952: # --------- determine least loaded server in a user's domain which allows login
                    953: 
                    954: sub choose_server {
1.1115    raeburn   955:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   956:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   957:     my %servers = &get_servers($udom);
1.1076    raeburn   958:     my $lowest_load = 30000;
1.1151    raeburn   959:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   960:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   961:         my $loginvia;
                    962:         if ($checkloginvia) {
                    963:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   964:             if ($loginvia) {
                    965:                 my ($server,$path) = split(/:/,$loginvia);
                    966:                 ($login_host, $lowest_load) =
                    967:                     &compare_server_load($server, $login_host, $lowest_load);
                    968:                 if ($login_host eq $server) {
                    969:                     $portal_path = $path;
1.1151    raeburn   970:                     $isredirect = 1;
1.1116    raeburn   971:                 }
                    972:             } else {
                    973:                 ($login_host, $lowest_load) =
                    974:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    975:                 if ($login_host eq $lonhost) {
                    976:                     $portal_path = '';
1.1151    raeburn   977:                     $isredirect = ''; 
1.1116    raeburn   978:                 }
                    979:             }
                    980:         } else {
1.1076    raeburn   981:             ($login_host, $lowest_load) =
1.1116    raeburn   982:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   983:         }
                    984:     }
                    985:     if ($login_host ne '') {
1.1116    raeburn   986:         $hostname = &hostname($login_host);
1.1076    raeburn   987:     }
1.1151    raeburn   988:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   989: }
                    990: 
1.202     matthew   991: # --------------------------------------------- Try to change a user's password
                    992: 
                    993: sub changepass {
1.799     raeburn   994:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   995:     $currentpass = &escape($currentpass);
                    996:     $newpass     = &escape($newpass);
1.1030    raeburn   997:     my $lonhost = $perlvar{'lonHostID'};
                    998:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   999: 		       $server);
                   1000:     if (! $answer) {
                   1001: 	&logthis("No reply on password change request to $server ".
                   1002: 		 "by $uname in domain $udom.");
                   1003:     } elsif ($answer =~ "^ok") {
                   1004:         &logthis("$uname in $udom successfully changed their password ".
                   1005: 		 "on $server.");
                   1006:     } elsif ($answer =~ "^pwchange_failure") {
                   1007: 	&logthis("$uname in $udom was unable to change their password ".
                   1008: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1009: 		 "or pwchange");
                   1010:     } elsif ($answer =~ "^non_authorized") {
                   1011:         &logthis("$uname in $udom did not get their password correct when ".
                   1012: 		 "attempting to change it on $server.");
                   1013:     } elsif ($answer =~ "^auth_mode_error") {
                   1014:         &logthis("$uname in $udom attempted to change their password despite ".
                   1015: 		 "not being locally or internally authenticated on $server.");
                   1016:     } elsif ($answer =~ "^unknown_user") {
                   1017:         &logthis("$uname in $udom attempted to change their password ".
                   1018: 		 "on $server but were unable to because $server is not ".
                   1019: 		 "their home server.");
                   1020:     } elsif ($answer =~ "^refused") {
                   1021: 	&logthis("$server refused to change $uname in $udom password because ".
                   1022: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1023:     } elsif ($answer =~ "invalid_client") {
                   1024:         &logthis("$server refused to change $uname in $udom password because ".
                   1025:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1026:     }
                   1027:     return $answer;
1.1       albertel 1028: }
                   1029: 
1.169     harris41 1030: # ----------------------- Try to determine user's current authentication scheme
                   1031: 
                   1032: sub queryauthenticate {
                   1033:     my ($uname,$udom)=@_;
1.456     albertel 1034:     my $uhome=&homeserver($uname,$udom);
                   1035:     if (!$uhome) {
                   1036: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1037: 	return 'no_host';
                   1038:     }
                   1039:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1040:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1041: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1042:     }
1.456     albertel 1043:     return $answer;
1.169     harris41 1044: }
                   1045: 
1.1       albertel 1046: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1047: 
1.1       albertel 1048: sub authenticate {
1.1073    raeburn  1049:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1050:     $upass=&escape($upass);
                   1051:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1052:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1053:     my $newhome;
1.836     www      1054:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1055: # Maybe the machine was offline and only re-appeared again recently?
                   1056:         &reconlonc();
                   1057: # One more
1.952     raeburn  1058: 	$uhome=&homeserver($uname,$udom,1);
                   1059:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1060:             if (defined(&domain($udom,'primary'))) {
                   1061:                 $newhome=&domain($udom,'primary');
                   1062:             }
                   1063:             if ($newhome ne '') {
                   1064:                 $uhome = $newhome;
                   1065:             }
                   1066:         }
1.836     www      1067: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1068: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1069: 	    return 'no_host';
                   1070:         }
1.1       albertel 1071:     }
1.1073    raeburn  1072:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1073:     if ($answer eq 'authorized') {
1.952     raeburn  1074:         if ($newhome) {
                   1075:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1076:             return 'no_account_on_host'; 
                   1077:         } else {
                   1078:             &logthis("User $uname at $udom authorized by $uhome");
                   1079:             return $uhome;
                   1080:         }
1.471     albertel 1081:     }
                   1082:     if ($answer eq 'non_authorized') {
                   1083: 	&logthis("User $uname at $udom rejected by $uhome");
                   1084: 	return 'no_host'; 
1.9       www      1085:     }
1.471     albertel 1086:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1087:     return 'no_host';
                   1088: }
                   1089: 
1.1073    raeburn  1090: sub can_host_session {
1.1074    raeburn  1091:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1092:     my $canhost = 1;
1.1074    raeburn  1093:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1094:     if (ref($remotesessions) eq 'HASH') {
                   1095:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1096:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1097:                 $canhost = 0;
                   1098:             } else {
                   1099:                 $canhost = 1;
                   1100:             }
                   1101:         }
                   1102:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1103:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1104:                 $canhost = 1;
                   1105:             } else {
                   1106:                 $canhost = 0;
                   1107:             }
                   1108:         }
                   1109:         if ($canhost) {
                   1110:             if ($remotesessions->{'version'} ne '') {
                   1111:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1112:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1113:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1114:                         my $major = $1;
                   1115:                         my $minor = $2;
                   1116:                         if (($major < $reqmajor ) ||
                   1117:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1118:                             $canhost = 0;
                   1119:                         }
                   1120:                     } else {
                   1121:                         $canhost = 0;
                   1122:                     }
                   1123:                 }
                   1124:             }
                   1125:         }
                   1126:     }
                   1127:     if ($canhost) {
                   1128:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1129:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1130:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1131:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1132:                 if (($uint_dom ne '') && 
                   1133:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1134:                     $canhost = 0;
                   1135:                 } else {
                   1136:                     $canhost = 1;
                   1137:                 }
                   1138:             }
                   1139:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1140:                 if (($uint_dom ne '') && 
                   1141:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1142:                     $canhost = 1;
                   1143:                 } else {
                   1144:                     $canhost = 0;
                   1145:                 }
                   1146:             }
                   1147:         }
                   1148:     }
                   1149:     return $canhost;
                   1150: }
                   1151: 
1.1083    raeburn  1152: sub spare_can_host {
                   1153:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1154:     my $canhost=1;
                   1155:     my @intdoms;
                   1156:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1157:     if (ref($internet_names) eq 'ARRAY') {
                   1158:         @intdoms = @{$internet_names};
                   1159:     }
                   1160:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1161:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1162:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1163:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1164:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1165:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1166:                                      $remotesessions,
                   1167:                                      $defdomdefaults{'hostedsessions'});
                   1168:     }
                   1169:     return $canhost;
                   1170: }
                   1171: 
1.1123    raeburn  1172: sub this_host_spares {
                   1173:     my ($dom) = @_;
1.1126    raeburn  1174:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1175:     my @hosts = &current_machine_ids();
                   1176:     foreach my $lonhost (@hosts) {
                   1177:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1178:             $dom_in_use = $dom;
                   1179:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1180:             last;
                   1181:         }
                   1182:     }
1.1126    raeburn  1183:     if ($dom_in_use ne '') {
                   1184:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1185:     }
                   1186:     if (ref($result) ne 'HASH') {
                   1187:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1188:         $dom_in_use = &host_domain($lonhost_in_use);
                   1189:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1190:         if (ref($result) ne 'HASH') {
                   1191:             $result = \%spareid;
                   1192:         }
                   1193:     }
                   1194:     return $result;
                   1195: }
                   1196: 
                   1197: sub spares_for_offload  {
                   1198:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1199:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1200:     if (defined($cached)) {
                   1201:         return $result;
                   1202:     } else {
1.1126    raeburn  1203:         my $cachetime = 60*60*24;
                   1204:         my %domconfig =
                   1205:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1206:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1207:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1208:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1209:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1210:                 }
                   1211:             }
                   1212:         }
                   1213:     }
1.1126    raeburn  1214:     return;
1.1123    raeburn  1215: }
                   1216: 
1.1129    raeburn  1217: sub get_lonbalancer_config {
                   1218:     my ($servers) = @_;
                   1219:     my ($currbalancer,$currtargets);
                   1220:     if (ref($servers) eq 'HASH') {
                   1221:         foreach my $server (keys(%{$servers})) {
                   1222:             my %what = (
                   1223:                          spareid => 1,
                   1224:                          perlvar => 1,
                   1225:                        );
                   1226:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1227:             if ($result eq 'ok') {
                   1228:                 if (ref($returnhash) eq 'HASH') {
                   1229:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1230:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1231:                             $currbalancer = $server;
                   1232:                             $currtargets = {};
                   1233:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1234:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1235:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1236:                                 }
                   1237:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1238:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1239:                                 }
                   1240:                             }
                   1241:                             last;
                   1242:                         }
                   1243:                     }
                   1244:                 }
                   1245:             }
                   1246:         }
                   1247:     }
                   1248:     return ($currbalancer,$currtargets);
                   1249: }
                   1250: 
                   1251: sub check_loadbalancing {
                   1252:     my ($uname,$udom) = @_;
1.1191    raeburn  1253:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1254:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1255:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1256:     my @hosts = &current_machine_ids();
1.1129    raeburn  1257:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1258:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1259:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1260:     my $serverhomedom = &host_domain($lonhost);
                   1261: 
                   1262:     my $cachetime = 60*60*24;
                   1263: 
                   1264:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1265:         $dom_in_use = $udom;
                   1266:         $homeintdom = 1;
                   1267:     } else {
                   1268:         $dom_in_use = $serverhomedom;
                   1269:     }
                   1270:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1271:     unless (defined($cached)) {
                   1272:         my %domconfig =
                   1273:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1274:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1275:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1276:         }
                   1277:     }
                   1278:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1279:         ($is_balancer,$currtargets,$currrules) = 
                   1280:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1281:         if ($is_balancer) {
                   1282:             if (ref($currrules) eq 'HASH') {
                   1283:                 if ($homeintdom) {
                   1284:                     if ($uname ne '') {
                   1285:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1286:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1287:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1288:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1289:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1290:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1291:                             }
                   1292:                         }
                   1293:                         if ($rule_in_effect eq '') {
                   1294:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1295:                             if ($userenv{'inststatus'} ne '') {
                   1296:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1297:                                 my ($othertitle,$usertypes,$types) =
                   1298:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1299:                                 if (ref($types) eq 'ARRAY') {
                   1300:                                     foreach my $type (@{$types}) {
                   1301:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1302:                                             if (exists($currrules->{$type})) {
                   1303:                                                 $rule_in_effect = $currrules->{$type};
                   1304:                                             }
                   1305:                                         }
                   1306:                                     }
                   1307:                                 }
                   1308:                             } else {
                   1309:                                 if (exists($currrules->{'default'})) {
                   1310:                                     $rule_in_effect = $currrules->{'default'};
                   1311:                                 }
                   1312:                             }
                   1313:                         }
                   1314:                     } else {
                   1315:                         if (exists($currrules->{'default'})) {
                   1316:                             $rule_in_effect = $currrules->{'default'};
                   1317:                         }
                   1318:                     }
                   1319:                 } else {
                   1320:                     if ($currrules->{'_LC_external'} ne '') {
                   1321:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1322:                     }
                   1323:                 }
                   1324:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1325:                                                        $uname,$udom);
                   1326:             }
                   1327:         }
                   1328:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1329:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1330:         unless (defined($cached)) {
                   1331:             my %domconfig =
                   1332:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1333:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1334:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1335:             }
                   1336:         }
                   1337:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1338:             ($is_balancer,$currtargets,$currrules) = 
                   1339:                 &check_balancer_result($result,@hosts);
                   1340:             if ($is_balancer) {
1.1129    raeburn  1341:                 if (ref($currrules) eq 'HASH') {
                   1342:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1343:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1344:                     }
                   1345:                 }
                   1346:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1347:                                                        $uname,$udom);
                   1348:             }
                   1349:         } else {
                   1350:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1351:                 $is_balancer = 1;
                   1352:                 $offloadto = &this_host_spares($dom_in_use);
                   1353:             }
                   1354:         }
                   1355:     } else {
                   1356:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1357:             $is_balancer = 1;
                   1358:             $offloadto = &this_host_spares($dom_in_use);
                   1359:         }
                   1360:     }
1.1176    raeburn  1361:     if ($is_balancer) {
                   1362:         my $lowest_load = 30000;
                   1363:         if (ref($offloadto) eq 'HASH') {
                   1364:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1365:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1366:                     ($otherserver,$lowest_load) =
                   1367:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1368:                 }
1.1129    raeburn  1369:             }
1.1176    raeburn  1370:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1371: 
1.1176    raeburn  1372:             if (!$found_server) {
                   1373:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1374:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1375:                         ($otherserver,$lowest_load) =
                   1376:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1377:                     }
                   1378:                 }
                   1379:             }
                   1380:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1381:             if (@{$offloadto} == 1) {
                   1382:                 $otherserver = $offloadto->[0];
                   1383:             } elsif (@{$offloadto} > 1) {
                   1384:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1385:                     ($otherserver,$lowest_load) =
                   1386:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1387:                 }
                   1388:             }
                   1389:         }
1.1176    raeburn  1390:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1391:             $is_balancer = 0;
                   1392:             if ($uname ne '' && $udom ne '') {
                   1393:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1394:                     
                   1395:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1396:                              'user.loadbalcheck.time' => time});
                   1397:                 }
1.1129    raeburn  1398:             }
                   1399:         }
                   1400:     }
                   1401:     return ($is_balancer,$otherserver);
                   1402: }
                   1403: 
1.1191    raeburn  1404: sub check_balancer_result {
                   1405:     my ($result,@hosts) = @_;
                   1406:     my ($is_balancer,$currtargets,$currrules);
                   1407:     if (ref($result) eq 'HASH') {
                   1408:         if ($result->{'lonhost'} ne '') {
                   1409:             my $currbalancer = $result->{'lonhost'};
                   1410:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1411:                 $is_balancer = 1;
                   1412:                 $currtargets = $result->{'targets'};
                   1413:                 $currrules = $result->{'rules'};
                   1414:             }
                   1415:         } else {
                   1416:             foreach my $key (keys(%{$result})) {
                   1417:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1418:                     (ref($result->{$key}) eq 'HASH')) {
                   1419:                     $is_balancer = 1;
                   1420:                     $currrules = $result->{$key}{'rules'};
                   1421:                     $currtargets = $result->{$key}{'targets'};
                   1422:                     last;
                   1423:                 }
                   1424:             }
                   1425:         }
                   1426:     }
                   1427:     return ($is_balancer,$currtargets,$currrules);
                   1428: }
                   1429: 
1.1129    raeburn  1430: sub get_loadbalancer_targets {
                   1431:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1432:     my $offloadto;
1.1175    raeburn  1433:     if ($rule_in_effect eq 'none') {
                   1434:         return [$perlvar{'lonHostID'}];
                   1435:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1436:         $offloadto = $currtargets;
                   1437:     } else {
                   1438:         if ($rule_in_effect eq 'homeserver') {
                   1439:             my $homeserver = &homeserver($uname,$udom);
                   1440:             if ($homeserver ne 'no_host') {
                   1441:                 $offloadto = [$homeserver];
                   1442:             }
                   1443:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1444:             my %domconfig =
                   1445:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1446:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1447:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1448:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1449:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1450:                     }
                   1451:                 }
                   1452:             } else {
1.1178    raeburn  1453:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1454:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1455:                 if (&hostname($remotebalancer) ne '') {
                   1456:                     $offloadto = [$remotebalancer];
                   1457:                 }
                   1458:             }
                   1459:         } elsif (&hostname($rule_in_effect) ne '') {
                   1460:             $offloadto = [$rule_in_effect];
                   1461:         }
                   1462:     }
                   1463:     return $offloadto;
                   1464: }
                   1465: 
1.1127    raeburn  1466: sub internet_dom_servers {
                   1467:     my ($dom) = @_;
                   1468:     my (%uniqservers,%servers);
                   1469:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1470:     my @machinedoms = &machine_domains($primaryserver);
                   1471:     foreach my $mdom (@machinedoms) {
                   1472:         my %currservers = %servers;
                   1473:         my %server = &get_servers($mdom);
                   1474:         %servers = (%currservers,%server);
                   1475:     }
                   1476:     my %by_hostname;
                   1477:     foreach my $id (keys(%servers)) {
                   1478:         push(@{$by_hostname{$servers{$id}}},$id);
                   1479:     }
                   1480:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1481:         if (@{$by_hostname{$hostname}} > 1) {
                   1482:             my $match = 0;
                   1483:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1484:                 if (&host_domain($id) eq $dom) {
                   1485:                     $uniqservers{$id} = $hostname;
                   1486:                     $match = 1;
                   1487:                 }
                   1488:             }
                   1489:             unless ($match) {
                   1490:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1491:             }
                   1492:         } else {
                   1493:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1494:         }
                   1495:     }
                   1496:     return %uniqservers;
                   1497: }
                   1498: 
1.1       albertel 1499: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1500: 
1.599     albertel 1501: my %homecache;
1.1       albertel 1502: sub homeserver {
1.230     stredwic 1503:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1504:     my $index="$uname:$udom";
1.426     albertel 1505: 
1.599     albertel 1506:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1507: 
                   1508:     my %servers = &get_servers($udom,'library');
                   1509:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1510:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1511: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1512: 
                   1513: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1514: 	if ($answer eq 'found') {
                   1515: 	    delete($badServerCache{$tryserver}); 
                   1516: 	    return $homecache{$index}=$tryserver;
                   1517: 	} elsif ($answer eq 'no_host') {
                   1518: 	    $badServerCache{$tryserver}=1;
                   1519: 	}
1.1       albertel 1520:     }    
                   1521:     return 'no_host';
1.70      www      1522: }
                   1523: 
                   1524: # ------------------------------------- Find the usernames behind a list of IDs
                   1525: 
                   1526: sub idget {
                   1527:     my ($udom,@ids)=@_;
                   1528:     my %returnhash=();
                   1529:     
1.841     albertel 1530:     my %servers = &get_servers($udom,'library');
                   1531:     foreach my $tryserver (keys(%servers)) {
                   1532: 	my $idlist=join('&',@ids);
                   1533: 	$idlist=~tr/A-Z/a-z/; 
                   1534: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1535: 	my @answer=();
                   1536: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1537: 	    @answer=split(/\&/,$reply);
                   1538: 	}                    ;
                   1539: 	my $i;
                   1540: 	for ($i=0;$i<=$#ids;$i++) {
                   1541: 	    if ($answer[$i]) {
                   1542: 		$returnhash{$ids[$i]}=$answer[$i];
                   1543: 	    } 
                   1544: 	}
                   1545:     } 
1.70      www      1546:     return %returnhash;
                   1547: }
                   1548: 
                   1549: # ------------------------------------- Find the IDs behind a list of usernames
                   1550: 
                   1551: sub idrget {
                   1552:     my ($udom,@unames)=@_;
                   1553:     my %returnhash=();
1.800     albertel 1554:     foreach my $uname (@unames) {
                   1555:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1556:     }
1.70      www      1557:     return %returnhash;
                   1558: }
                   1559: 
                   1560: # ------------------------------- Store away a list of names and associated IDs
                   1561: 
                   1562: sub idput {
                   1563:     my ($udom,%ids)=@_;
                   1564:     my %servers=();
1.800     albertel 1565:     foreach my $uname (keys(%ids)) {
                   1566: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1567:         my $uhom=&homeserver($uname,$udom);
1.70      www      1568:         if ($uhom ne 'no_host') {
1.800     albertel 1569:             my $id=&escape($ids{$uname});
1.70      www      1570:             $id=~tr/A-Z/a-z/;
1.800     albertel 1571:             my $esc_unam=&escape($uname);
1.70      www      1572: 	    if ($servers{$uhom}) {
1.800     albertel 1573: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1574:             } else {
1.800     albertel 1575:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1576:             }
                   1577:         }
1.191     harris41 1578:     }
1.800     albertel 1579:     foreach my $server (keys(%servers)) {
                   1580:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1581:     }
1.344     www      1582: }
                   1583: 
1.1231    raeburn  1584: # ---------------------------------------- Delete unwanted IDs from ids.db file 
                   1585: 
                   1586: sub iddel {
                   1587:     my ($udom,$idshashref,$uhome)=@_;
                   1588:     my %result=();
                   1589:     unless (ref($idshashref) eq 'HASH') {
                   1590:         return %result;
                   1591:     }
                   1592:     my %servers=();
                   1593:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1594:         my $uhom;
                   1595:         if ($uhome) {
                   1596:             $uhom = $uhome;
                   1597:         } else {
                   1598:             $uhom=&homeserver($uname,$udom);
                   1599:         }
                   1600:         if ($uhom ne 'no_host') {
                   1601:             if ($servers{$uhom}) {
                   1602:                 $servers{$uhom}.='&'.&escape($id);
                   1603:             } else {
                   1604:                 $servers{$uhom}=&escape($id);
                   1605:             }
                   1606:         }
                   1607:     }
                   1608:     foreach my $server (keys(%servers)) {
                   1609:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1610:     }
                   1611:     return %result;
                   1612: }
                   1613: 
1.1023    raeburn  1614: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1615: sub dump_dom {
1.1165    droeschl 1616:     my ($namespace, $udom, $regexp) = @_;
                   1617: 
                   1618:     $udom ||= $env{'user.domain'};
                   1619: 
                   1620:     return () unless $udom;
                   1621: 
                   1622:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1623: }
                   1624: 
1.1023    raeburn  1625: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1626: 
                   1627: sub get_dom {
1.860     raeburn  1628:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1629:     my $items='';
                   1630:     foreach my $item (@$storearr) {
                   1631:         $items.=&escape($item).'&';
                   1632:     }
                   1633:     $items=~s/\&$//;
1.860     raeburn  1634:     if (!$udom) {
                   1635:         $udom=$env{'user.domain'};
                   1636:         if (defined(&domain($udom,'primary'))) {
                   1637:             $uhome=&domain($udom,'primary');
                   1638:         } else {
1.874     albertel 1639:             undef($uhome);
1.860     raeburn  1640:         }
                   1641:     } else {
                   1642:         if (!$uhome) {
                   1643:             if (defined(&domain($udom,'primary'))) {
                   1644:                 $uhome=&domain($udom,'primary');
                   1645:             }
                   1646:         }
                   1647:     }
                   1648:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1649:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1650:         my %returnhash;
1.875     albertel 1651:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1652:             return %returnhash;
                   1653:         }
1.806     raeburn  1654:         my @pairs=split(/\&/,$rep);
                   1655:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1656:             return @pairs;
                   1657:         }
                   1658:         my $i=0;
                   1659:         foreach my $item (@$storearr) {
                   1660:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1661:             $i++;
                   1662:         }
                   1663:         return %returnhash;
                   1664:     } else {
1.880     banghart 1665:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1666:     }
                   1667: }
                   1668: 
                   1669: # -------------------------------------------- put items in domain db files 
                   1670: 
                   1671: sub put_dom {
1.860     raeburn  1672:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1673:     if (!$udom) {
                   1674:         $udom=$env{'user.domain'};
                   1675:         if (defined(&domain($udom,'primary'))) {
                   1676:             $uhome=&domain($udom,'primary');
                   1677:         } else {
1.874     albertel 1678:             undef($uhome);
1.860     raeburn  1679:         }
                   1680:     } else {
                   1681:         if (!$uhome) {
                   1682:             if (defined(&domain($udom,'primary'))) {
                   1683:                 $uhome=&domain($udom,'primary');
                   1684:             }
                   1685:         }
                   1686:     } 
                   1687:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1688:         my $items='';
                   1689:         foreach my $item (keys(%$storehash)) {
                   1690:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1691:         }
                   1692:         $items=~s/\&$//;
                   1693:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1694:     } else {
1.860     raeburn  1695:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1696:     }
                   1697: }
                   1698: 
1.1023    raeburn  1699: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1700: sub newput_dom {
1.1023    raeburn  1701:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1702:     my $result;
                   1703:     if (!$udom) {
                   1704:         $udom=$env{'user.domain'};
                   1705:     }
1.1023    raeburn  1706:     if ($udom) {
                   1707:         my $uname = &get_domainconfiguser($udom);
                   1708:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1709:     }
                   1710:     return $result;
                   1711: }
                   1712: 
1.1023    raeburn  1713: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1714: sub del_dom {
1.1023    raeburn  1715:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1716:     if (ref($storearr) eq 'ARRAY') {
                   1717:         if (!$udom) {
                   1718:             $udom=$env{'user.domain'};
                   1719:         }
1.1023    raeburn  1720:         if ($udom) {
                   1721:             my $uname = &get_domainconfiguser($udom); 
                   1722:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1723:         }
                   1724:     }
                   1725: }
                   1726: 
1.1023    raeburn  1727: # ----------------------------------construct domainconfig user for a domain 
                   1728: sub get_domainconfiguser {
                   1729:     my ($udom) = @_;
                   1730:     return $udom.'-domainconfig';
                   1731: }
                   1732: 
1.837     raeburn  1733: sub retrieve_inst_usertypes {
                   1734:     my ($udom) = @_;
                   1735:     my (%returnhash,@order);
1.989     raeburn  1736:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1737:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1738:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1739:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1740:         @order = @{$domdefs{'inststatusorder'}};
                   1741:     } else {
                   1742:         if (defined(&domain($udom,'primary'))) {
                   1743:             my $uhome=&domain($udom,'primary');
                   1744:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1745:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1746:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1747:                 return (\%returnhash,\@order);
                   1748:             }
                   1749:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1750:             my @pairs=split(/\&/,$hashitems);
                   1751:             foreach my $item (@pairs) {
                   1752:                 my ($key,$value)=split(/=/,$item,2);
                   1753:                 $key = &unescape($key);
                   1754:                 next if ($key =~ /^error: 2 /);
                   1755:                 $returnhash{$key}=&thaw_unescape($value);
                   1756:             }
                   1757:             my @esc_order = split(/\&/,$orderitems);
                   1758:             foreach my $item (@esc_order) {
                   1759:                 push(@order,&unescape($item));
                   1760:             }
                   1761:         } else {
                   1762:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1763:         }
                   1764:     }
                   1765:     return (\%returnhash,\@order);
                   1766: }
                   1767: 
1.868     raeburn  1768: sub is_domainimage {
                   1769:     my ($url) = @_;
                   1770:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1771:         if (&domain($1) ne '') {
                   1772:             return '1';
                   1773:         }
                   1774:     }
                   1775:     return;
                   1776: }
                   1777: 
1.899     raeburn  1778: sub inst_directory_query {
                   1779:     my ($srch) = @_;
                   1780:     my $udom = $srch->{'srchdomain'};
                   1781:     my %results;
                   1782:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1783:     my $outcome;
1.899     raeburn  1784:     if ($homeserver ne '') {
1.904     albertel 1785: 	my $queryid=&reply("querysend:instdirsearch:".
                   1786: 			   &escape($srch->{'srchby'}).':'.
                   1787: 			   &escape($srch->{'srchterm'}).':'.
                   1788: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1789: 	my $host=&hostname($homeserver);
                   1790: 	if ($queryid !~/^\Q$host\E\_/) {
                   1791: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1792: 	    return;
                   1793: 	}
                   1794: 	my $response = &get_query_reply($queryid);
                   1795: 	my $maxtries = 5;
                   1796: 	my $tries = 1;
                   1797: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1798: 	    $response = &get_query_reply($queryid);
                   1799: 	    $tries ++;
                   1800: 	}
                   1801: 
                   1802:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1803:             if ($response eq 'unavailable') {
                   1804:                 $outcome = $response;
                   1805:             } else {
                   1806:                 $outcome = 'ok';
                   1807:                 my @matches = split(/\n/,$response);
                   1808:                 foreach my $match (@matches) {
                   1809:                     my ($key,$value) = split(/=/,$match);
                   1810:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1811:                 }
1.899     raeburn  1812:             }
                   1813:         }
                   1814:     }
1.909     raeburn  1815:     return ($outcome,%results);
1.899     raeburn  1816: }
                   1817: 
                   1818: sub usersearch {
                   1819:     my ($srch) = @_;
                   1820:     my $dom = $srch->{'srchdomain'};
                   1821:     my %results;
                   1822:     my %libserv = &all_library();
                   1823:     my $query = 'usersearch';
                   1824:     foreach my $tryserver (keys(%libserv)) {
                   1825:         if (&host_domain($tryserver) eq $dom) {
                   1826:             my $host=&hostname($tryserver);
                   1827:             my $queryid=
1.911     raeburn  1828:                 &reply("querysend:".&escape($query).':'.
                   1829:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1830:                        &escape($srch->{'srchtype'}).':'.
                   1831:                        &escape($srch->{'srchterm'}),$tryserver);
                   1832:             if ($queryid !~/^\Q$host\E\_/) {
                   1833:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1834:                 next;
1.899     raeburn  1835:             }
                   1836:             my $reply = &get_query_reply($queryid);
                   1837:             my $maxtries = 1;
                   1838:             my $tries = 1;
                   1839:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1840:                 $reply = &get_query_reply($queryid);
                   1841:                 $tries ++;
                   1842:             }
                   1843:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1844:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1845:             } else {
1.911     raeburn  1846:                 my @matches;
                   1847:                 if ($reply =~ /\n/) {
                   1848:                     @matches = split(/\n/,$reply);
                   1849:                 } else {
                   1850:                     @matches = split(/\&/,$reply);
                   1851:                 }
1.899     raeburn  1852:                 foreach my $match (@matches) {
                   1853:                     my ($uname,$udom,%userhash);
1.911     raeburn  1854:                     foreach my $entry (split(/:/,$match)) {
                   1855:                         my ($key,$value) =
                   1856:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1857:                         $userhash{$key} = $value;
                   1858:                         if ($key eq 'username') {
                   1859:                             $uname = $value;
                   1860:                         } elsif ($key eq 'domain') {
                   1861:                             $udom = $value;
1.911     raeburn  1862:                         }
1.899     raeburn  1863:                     }
                   1864:                     $results{$uname.':'.$udom} = \%userhash;
                   1865:                 }
                   1866:             }
                   1867:         }
                   1868:     }
                   1869:     return %results;
                   1870: }
                   1871: 
1.912     raeburn  1872: sub get_instuser {
                   1873:     my ($udom,$uname,$id) = @_;
                   1874:     my $homeserver = &domain($udom,'primary');
                   1875:     my ($outcome,%results);
                   1876:     if ($homeserver ne '') {
                   1877:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1878:                            &escape($id).':'.&escape($udom),$homeserver);
                   1879:         my $host=&hostname($homeserver);
                   1880:         if ($queryid !~/^\Q$host\E\_/) {
                   1881:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1882:             return;
                   1883:         }
                   1884:         my $response = &get_query_reply($queryid);
                   1885:         my $maxtries = 5;
                   1886:         my $tries = 1;
                   1887:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1888:             $response = &get_query_reply($queryid);
                   1889:             $tries ++;
                   1890:         }
                   1891:         if (!&error($response) && $response ne 'refused') {
                   1892:             if ($response eq 'unavailable') {
                   1893:                 $outcome = $response;
                   1894:             } else {
                   1895:                 $outcome = 'ok';
                   1896:                 my @matches = split(/\n/,$response);
                   1897:                 foreach my $match (@matches) {
                   1898:                     my ($key,$value) = split(/=/,$match);
                   1899:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1900:                 }
                   1901:             }
                   1902:         }
                   1903:     }
                   1904:     my %userinfo;
                   1905:     if (ref($results{$uname}) eq 'HASH') {
                   1906:         %userinfo = %{$results{$uname}};
                   1907:     } 
                   1908:     return ($outcome,%userinfo);
                   1909: }
                   1910: 
                   1911: sub inst_rulecheck {
1.923     raeburn  1912:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1913:     my %returnhash;
                   1914:     if ($udom ne '') {
                   1915:         if (ref($rules) eq 'ARRAY') {
                   1916:             @{$rules} = map {&escape($_);} (@{$rules});
                   1917:             my $rulestr = join(':',@{$rules});
                   1918:             my $homeserver=&domain($udom,'primary');
                   1919:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1920:                 my $response;
                   1921:                 if ($item eq 'username') {                
                   1922:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1923:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1924:                                               $homeserver));
1.923     raeburn  1925:                 } elsif ($item eq 'id') {
                   1926:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1927:                                               ':'.&escape($id).':'.$rulestr,
                   1928:                                               $homeserver));
1.945     raeburn  1929:                 } elsif ($item eq 'selfcreate') {
                   1930:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1931:                                                &escape($udom).':'.&escape($uname).
                   1932:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1933:                 }
1.912     raeburn  1934:                 if ($response ne 'refused') {
                   1935:                     my @pairs=split(/\&/,$response);
                   1936:                     foreach my $item (@pairs) {
                   1937:                         my ($key,$value)=split(/=/,$item,2);
                   1938:                         $key = &unescape($key);
                   1939:                         next if ($key =~ /^error: 2 /);
                   1940:                         $returnhash{$key}=&thaw_unescape($value);
                   1941:                     }
                   1942:                 }
                   1943:             }
                   1944:         }
                   1945:     }
                   1946:     return %returnhash;
                   1947: }
                   1948: 
                   1949: sub inst_userrules {
1.923     raeburn  1950:     my ($udom,$check) = @_;
1.912     raeburn  1951:     my (%ruleshash,@ruleorder);
                   1952:     if ($udom ne '') {
                   1953:         my $homeserver=&domain($udom,'primary');
                   1954:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1955:             my $response;
                   1956:             if ($check eq 'id') {
                   1957:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1958:                                  $homeserver);
1.943     raeburn  1959:             } elsif ($check eq 'email') {
                   1960:                 $response=&reply('instemailrules:'.&escape($udom),
                   1961:                                  $homeserver);
1.923     raeburn  1962:             } else {
                   1963:                 $response=&reply('instuserrules:'.&escape($udom),
                   1964:                                  $homeserver);
                   1965:             }
1.912     raeburn  1966:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1967:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1968:                 ($response ne 'no_such_host')) {
                   1969:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1970:                 my @pairs=split(/\&/,$hashitems);
                   1971:                 foreach my $item (@pairs) {
                   1972:                     my ($key,$value)=split(/=/,$item,2);
                   1973:                     $key = &unescape($key);
                   1974:                     next if ($key =~ /^error: 2 /);
                   1975:                     $ruleshash{$key}=&thaw_unescape($value);
                   1976:                 }
                   1977:                 my @esc_order = split(/\&/,$orderitems);
                   1978:                 foreach my $item (@esc_order) {
                   1979:                     push(@ruleorder,&unescape($item));
                   1980:                 }
                   1981:             }
                   1982:         }
                   1983:     }
                   1984:     return (\%ruleshash,\@ruleorder);
                   1985: }
                   1986: 
1.976     raeburn  1987: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1988: 
                   1989: sub get_domain_defaults {
1.1240    raeburn  1990:     my ($domain,$ignore_cache) = @_;
1.1242  ! raeburn  1991:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  1992:     my $cachetime = 60*60*24;
1.1240    raeburn  1993:     unless ($ignore_cache) {
                   1994:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1995:         if (defined($cached)) {
                   1996:             if (ref($result) eq 'HASH') {
                   1997:                 return %{$result};
                   1998:             }
1.943     raeburn  1999:         }
                   2000:     }
                   2001:     my %domdefaults;
                   2002:     my %domconfig =
1.989     raeburn  2003:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2004:                                   'requestcourses','inststatus',
1.1183    raeburn  2005:                                   'coursedefaults','usersessions',
                   2006:                                   'requestauthor'],$domain);
1.943     raeburn  2007:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2008:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2009:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2010:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2011:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2012:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2013:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2014:     } else {
                   2015:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2016:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2017:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2018:     }
1.976     raeburn  2019:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2020:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2021:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2022:         } else {
                   2023:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2024:         }
1.1177    raeburn  2025:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2026:         foreach my $item (@usertools) {
                   2027:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2028:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2029:             }
                   2030:         }
1.1229    raeburn  2031:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2032:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2033:         }
1.976     raeburn  2034:     }
1.985     raeburn  2035:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  2036:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  2037:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2038:         }
                   2039:     }
1.1183    raeburn  2040:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2041:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2042:     }
1.989     raeburn  2043:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2044:         foreach my $item ('inststatustypes','inststatusorder') {
                   2045:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2046:         }
                   2047:     }
1.1047    raeburn  2048:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2049:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216    raeburn  2050:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2051:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2052:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
                   2053:         }
1.1230    raeburn  2054:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2055:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
                   2056:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
                   2057:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
                   2058:         }
1.1047    raeburn  2059:     }
1.1073    raeburn  2060:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2061:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2062:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2063:         }
                   2064:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2065:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2066:         }
                   2067:     }
1.1219    raeburn  2068:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2069:     return %domdefaults;
                   2070: }
                   2071: 
1.344     www      2072: # --------------------------------------------------- Assign a key to a student
                   2073: 
                   2074: sub assign_access_key {
1.364     www      2075: #
                   2076: # a valid key looks like uname:udom#comments
                   2077: # comments are being appended
                   2078: #
1.498     www      2079:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2080:     $kdom=
1.620     albertel 2081:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2082:     $knum=
1.620     albertel 2083:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2084:     $cdom=
1.620     albertel 2085:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2086:     $cnum=
1.620     albertel 2087:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2088:     $udom=$env{'user.name'} unless (defined($udom));
                   2089:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2090:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2091:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2092:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2093:                                                   # assigned to this person
                   2094:                                                   # - this should not happen,
1.345     www      2095:                                                   # unless something went wrong
                   2096:                                                   # the first time around
                   2097: # ready to assign
1.364     www      2098:         $logentry=$1.'; '.$logentry;
1.496     www      2099:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2100:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2101: # key now belongs to user
1.346     www      2102: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2103:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2104:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2105:                 return 'ok';
                   2106:             } else {
                   2107:                 return 
                   2108:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2109: 	    }
                   2110:         } else {
                   2111:             return 'error: Could not assign key, try again later.';
                   2112:         }
1.364     www      2113:     } elsif (!$existing{$ckey}) {
1.345     www      2114: # the key does not exist
                   2115: 	return 'error: The key does not exist';
                   2116:     } else {
                   2117: # the key is somebody else's
                   2118: 	return 'error: The key is already in use';
                   2119:     }
1.344     www      2120: }
                   2121: 
1.364     www      2122: # ------------------------------------------ put an additional comment on a key
                   2123: 
                   2124: sub comment_access_key {
                   2125: #
                   2126: # a valid key looks like uname:udom#comments
                   2127: # comments are being appended
                   2128: #
                   2129:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2130:     $cdom=
1.620     albertel 2131:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2132:     $cnum=
1.620     albertel 2133:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2134:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2135:     if ($existing{$ckey}) {
                   2136:         $existing{$ckey}.='; '.$logentry;
                   2137: # ready to assign
1.367     www      2138:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2139:                                                  $cdom,$cnum) eq 'ok') {
                   2140: 	    return 'ok';
                   2141:         } else {
                   2142: 	    return 'error: Count not store comment.';
                   2143:         }
                   2144:     } else {
                   2145: # the key does not exist
                   2146: 	return 'error: The key does not exist';
                   2147:     }
                   2148: }
                   2149: 
1.344     www      2150: # ------------------------------------------------------ Generate a set of keys
                   2151: 
                   2152: sub generate_access_keys {
1.364     www      2153:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2154:     $cdom=
1.620     albertel 2155:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2156:     $cnum=
1.620     albertel 2157:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2158:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2159:     unless (($cdom) && ($cnum)) { return 0; }
                   2160:     if ($number>10000) { return 0; }
                   2161:     sleep(2); # make sure don't get same seed twice
                   2162:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2163:     my $total=0;
                   2164:     for (my $i=1;$i<=$number;$i++) {
                   2165:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2166:                   sprintf("%lx",int(100000*rand)).'-'.
                   2167:                   sprintf("%lx",int(100000*rand));
                   2168:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2169:        $newkey=~s/0/h/g; # and also 0 and O
                   2170:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2171:        if ($existing{$newkey}) {
                   2172:            $i--;
                   2173:        } else {
1.364     www      2174: 	  if (&put('accesskeys',
                   2175:               { $newkey => '# generated '.localtime().
1.620     albertel 2176:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2177:                            '; '.$logentry },
                   2178: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2179:               $total++;
                   2180: 	  }
                   2181:        }
                   2182:     }
1.620     albertel 2183:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2184:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2185:     return $total;
                   2186: }
                   2187: 
                   2188: # ------------------------------------------------------- Validate an accesskey
                   2189: 
                   2190: sub validate_access_key {
                   2191:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2192:     $cdom=
1.620     albertel 2193:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2194:     $cnum=
1.620     albertel 2195:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2196:     $udom=$env{'user.domain'} unless (defined($udom));
                   2197:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2198:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2199:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2200: }
                   2201: 
                   2202: # ------------------------------------- Find the section of student in a course
1.652     albertel 2203: sub devalidate_getsection_cache {
                   2204:     my ($udom,$unam,$courseid)=@_;
                   2205:     my $hashid="$udom:$unam:$courseid";
                   2206:     &devalidate_cache_new('getsection',$hashid);
                   2207: }
1.298     matthew  2208: 
1.815     albertel 2209: sub courseid_to_courseurl {
                   2210:     my ($courseid) = @_;
                   2211:     #already url style courseid
                   2212:     return $courseid if ($courseid =~ m{^/});
                   2213: 
                   2214:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2215: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2216: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2217: 	return "/$cdom/$cnum";
                   2218:     }
                   2219: 
                   2220:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2221:     if (exists($courseinfo{'num'})) {
                   2222: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2223:     }
                   2224: 
                   2225:     return undef;
                   2226: }
                   2227: 
1.298     matthew  2228: sub getsection {
                   2229:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2230:     my $cachetime=1800;
1.551     albertel 2231: 
                   2232:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2233:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2234:     if (defined($cached)) { return $result; }
                   2235: 
1.298     matthew  2236:     my %Pending; 
                   2237:     my %Expired;
                   2238:     #
                   2239:     # Each role can either have not started yet (pending), be active, 
                   2240:     #    or have expired.
                   2241:     #
                   2242:     # If there is an active role, we are done.
                   2243:     #
                   2244:     # If there is more than one role which has not started yet, 
                   2245:     #     choose the one which will start sooner
                   2246:     # If there is one role which has not started yet, return it.
                   2247:     #
                   2248:     # If there is more than one expired role, choose the one which ended last.
                   2249:     # If there is a role which has expired, return it.
                   2250:     #
1.815     albertel 2251:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2252:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2253:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2254:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2255:         my $section=$1;
                   2256:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2257:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2258:         my $now=time;
1.548     albertel 2259:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2260:             $Expired{$end}=$section;
                   2261:             next;
                   2262:         }
1.548     albertel 2263:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2264:             $Pending{$start}=$section;
                   2265:             next;
                   2266:         }
1.599     albertel 2267:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2268:     }
                   2269:     #
                   2270:     # Presumedly there will be few matching roles from the above
                   2271:     # loop and the sorting time will be negligible.
                   2272:     if (scalar(keys(%Pending))) {
                   2273:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2274:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2275:     } 
                   2276:     if (scalar(keys(%Expired))) {
                   2277:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2278:         my $time = pop(@sorted);
1.599     albertel 2279:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2280:     }
1.599     albertel 2281:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2282: }
1.70      www      2283: 
1.599     albertel 2284: sub save_cache {
                   2285:     &purge_remembered();
1.722     albertel 2286:     #&Apache::loncommon::validate_page();
1.620     albertel 2287:     undef(%env);
1.780     albertel 2288:     undef($env_loaded);
1.599     albertel 2289: }
1.452     albertel 2290: 
1.599     albertel 2291: my $to_remember=-1;
                   2292: my %remembered;
                   2293: my %accessed;
                   2294: my $kicks=0;
                   2295: my $hits=0;
1.849     albertel 2296: sub make_key {
                   2297:     my ($name,$id) = @_;
1.872     albertel 2298:     if (length($id) > 65 
                   2299: 	&& length(&escape($id)) > 200) {
                   2300: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2301:     }
1.849     albertel 2302:     return &escape($name.':'.$id);
                   2303: }
                   2304: 
1.599     albertel 2305: sub devalidate_cache_new {
                   2306:     my ($name,$id,$debug) = @_;
                   2307:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2308:     $id=&make_key($name,$id);
1.599     albertel 2309:     $memcache->delete($id);
                   2310:     delete($remembered{$id});
                   2311:     delete($accessed{$id});
                   2312: }
                   2313: 
                   2314: sub is_cached_new {
                   2315:     my ($name,$id,$debug) = @_;
1.849     albertel 2316:     $id=&make_key($name,$id);
1.599     albertel 2317:     if (exists($remembered{$id})) {
1.1133    foxr     2318: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2319: 	$accessed{$id}=[&gettimeofday()];
                   2320: 	$hits++;
                   2321: 	return ($remembered{$id},1);
                   2322:     }
                   2323:     my $value = $memcache->get($id);
                   2324:     if (!(defined($value))) {
                   2325: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2326: 	return (undef,undef);
1.416     albertel 2327:     }
1.599     albertel 2328:     if ($value eq '__undef__') {
                   2329: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2330: 	$value=undef;
                   2331:     }
                   2332:     &make_room($id,$value,$debug);
                   2333:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2334:     return ($value,1);
                   2335: }
                   2336: 
                   2337: sub do_cache_new {
                   2338:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2339:     $id=&make_key($name,$id);
1.599     albertel 2340:     my $setvalue=$value;
                   2341:     if (!defined($setvalue)) {
                   2342: 	$setvalue='__undef__';
                   2343:     }
1.623     albertel 2344:     if (!defined($time) ) {
                   2345: 	$time=600;
                   2346:     }
1.599     albertel 2347:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2348:     my $result = $memcache->set($id,$setvalue,$time);
                   2349:     if (! $result) {
1.872     albertel 2350: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2351: 	$memcache->disconnect_all();
1.872     albertel 2352:     }
1.600     albertel 2353:     # need to make a copy of $value
1.919     albertel 2354:     &make_room($id,$value,$debug);
1.599     albertel 2355:     return $value;
                   2356: }
                   2357: 
                   2358: sub make_room {
                   2359:     my ($id,$value,$debug)=@_;
1.919     albertel 2360: 
                   2361:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2362:                                     : $value;
1.599     albertel 2363:     if ($to_remember<0) { return; }
                   2364:     $accessed{$id}=[&gettimeofday()];
                   2365:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2366:     my $to_kick;
                   2367:     my $max_time=0;
                   2368:     foreach my $other (keys(%accessed)) {
                   2369: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2370: 	    $to_kick=$other;
                   2371: 	    $max_time=&tv_interval($accessed{$other});
                   2372: 	}
                   2373:     }
                   2374:     delete($remembered{$to_kick});
                   2375:     delete($accessed{$to_kick});
                   2376:     $kicks++;
                   2377:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2378:     return;
                   2379: }
                   2380: 
1.599     albertel 2381: sub purge_remembered {
1.604     albertel 2382:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2383:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2384:     undef(%remembered);
                   2385:     undef(%accessed);
1.428     albertel 2386: }
1.70      www      2387: # ------------------------------------- Read an entry from a user's environment
                   2388: 
                   2389: sub userenvironment {
                   2390:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2391:     my $items;
                   2392:     foreach my $item (@what) {
                   2393:         $items.=&escape($item).'&';
                   2394:     }
                   2395:     $items=~s/\&$//;
1.70      www      2396:     my %returnhash=();
1.1009    raeburn  2397:     my $uhome = &homeserver($unam,$udom);
                   2398:     unless ($uhome eq 'no_host') {
                   2399:         my @answer=split(/\&/, 
                   2400:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2401:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2402:             return %returnhash;
                   2403:         }
1.1009    raeburn  2404:         my $i;
                   2405:         for ($i=0;$i<=$#what;$i++) {
                   2406: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2407:         }
1.70      www      2408:     }
                   2409:     return %returnhash;
1.1       albertel 2410: }
                   2411: 
1.617     albertel 2412: # ---------------------------------------------------------- Get a studentphoto
                   2413: sub studentphoto {
                   2414:     my ($udom,$unam,$ext) = @_;
                   2415:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2416:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2417:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2418:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2419:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2420:             } else {
                   2421:                 my ($result,$perm_reqd)=
1.707     albertel 2422: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2423:                 if ($result eq 'ok') {
                   2424:                     if (!($perm_reqd eq 'yes')) {
                   2425:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2426:                     }
                   2427:                 }
                   2428:             }
                   2429:         }
                   2430:     } else {
                   2431:         my ($result,$perm_reqd) = 
1.707     albertel 2432: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2433:         if ($result eq 'ok') {
                   2434:             if (!($perm_reqd eq 'yes')) {
                   2435:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2436:             }
                   2437:         }
                   2438:     }
                   2439:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2440: }
                   2441: 
                   2442: sub retrievestudentphoto {
                   2443:     my ($udom,$unam,$ext,$type) = @_;
                   2444:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2445:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2446:     if ($ret eq 'ok') {
                   2447:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2448:         if ($type eq 'thumbnail') {
                   2449:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2450:         }
                   2451:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2452:         return $tokenurl;
                   2453:     } else {
                   2454:         if ($type eq 'thumbnail') {
                   2455:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2456:         } else { 
                   2457:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2458:         }
1.617     albertel 2459:     }
                   2460: }
                   2461: 
1.263     www      2462: # -------------------------------------------------------------------- New chat
                   2463: 
                   2464: sub chatsend {
1.724     raeburn  2465:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2466:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2467:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2468:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2469:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2470: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2471: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2472: }
                   2473: 
                   2474: # ------------------------------------------ Find current version of a resource
                   2475: 
                   2476: sub getversion {
                   2477:     my $fname=&clutter(shift);
1.1189    raeburn  2478:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2479:     return &currentversion(&filelocation('',$fname));
                   2480: }
                   2481: 
                   2482: sub currentversion {
                   2483:     my $fname=shift;
                   2484:     my $author=$fname;
                   2485:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2486:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2487:     my $home=&homeserver($uname,$udom);
1.292     www      2488:     if ($home eq 'no_host') { 
                   2489:         return -1; 
                   2490:     }
1.1112    www      2491:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2492:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2493: 	return -1;
                   2494:     }
1.1112    www      2495:     return $answer;
1.263     www      2496: }
                   2497: 
1.1111    www      2498: #
                   2499: # Return special version number of resource if set by override, empty otherwise
                   2500: #
                   2501: sub usedversion {
                   2502:     my $fname=shift;
                   2503:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2504:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2505:     if ($urlversion) { return $urlversion; }
                   2506:     return '';
                   2507: }
                   2508: 
1.1       albertel 2509: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2510: 
1.1       albertel 2511: sub subscribe {
                   2512:     my $fname=shift;
1.761     raeburn  2513:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2514:     $fname=~s/[\n\r]//g;
1.1       albertel 2515:     my $author=$fname;
                   2516:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2517:     my ($udom,$uname)=split(/\//,$author);
                   2518:     my $home=homeserver($uname,$udom);
1.335     albertel 2519:     if ($home eq 'no_host') {
                   2520:         return 'not_found';
1.1       albertel 2521:     }
                   2522:     my $answer=reply("sub:$fname",$home);
1.64      www      2523:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2524: 	$answer.=' by '.$home;
                   2525:     }
1.1       albertel 2526:     return $answer;
                   2527: }
                   2528:     
1.8       www      2529: # -------------------------------------------------------------- Replicate file
                   2530: 
                   2531: sub repcopy {
                   2532:     my $filename=shift;
1.23      www      2533:     $filename=~s/\/+/\//g;
1.1142    raeburn  2534:     my $londocroot = $perlvar{'lonDocRoot'};
                   2535:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2536:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2537:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2538: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2539: 	return &repcopy_userfile($filename);
                   2540:     }
1.532     albertel 2541:     $filename=~s/[\n\r]//g;
1.8       www      2542:     my $transname="$filename.in.transfer";
1.828     www      2543: # FIXME: this should flock
1.607     raeburn  2544:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2545:     my $remoteurl=subscribe($filename);
1.64      www      2546:     if ($remoteurl =~ /^con_lost by/) {
                   2547: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2548:            return 'unavailable';
1.8       www      2549:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2550: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2551: 	   return 'not_found';
1.64      www      2552:     } elsif ($remoteurl =~ /^rejected by/) {
                   2553: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2554:            return 'forbidden';
1.20      www      2555:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2556:            return 'ok';
1.8       www      2557:     } else {
1.290     www      2558:         my $author=$filename;
                   2559:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2560:         my ($udom,$uname)=split(/\//,$author);
                   2561:         my $home=homeserver($uname,$udom);
                   2562:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2563:            my @parts=split(/\//,$filename);
                   2564:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2565:            if ($path ne "$londocroot/res") {
1.8       www      2566:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2567: 	       return 'bad_request';
1.8       www      2568:            }
                   2569:            my $count;
                   2570:            for ($count=5;$count<$#parts;$count++) {
                   2571:                $path.="/$parts[$count]";
                   2572:                if ((-e $path)!=1) {
                   2573: 		   mkdir($path,0777);
                   2574:                }
                   2575:            }
                   2576:            my $ua=new LWP::UserAgent;
                   2577:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2578:            my $response=$ua->request($request,$transname);
                   2579:            if ($response->is_error()) {
                   2580: 	       unlink($transname);
                   2581:                my $message=$response->status_line;
1.672     albertel 2582:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2583:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2584:                return 'unavailable';
1.8       www      2585:            } else {
1.16      www      2586: 	       if ($remoteurl!~/\.meta$/) {
                   2587:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2588:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2589:                   if ($mresponse->is_error()) {
                   2590: 		      unlink($filename.'.meta');
                   2591:                       &logthis(
1.672     albertel 2592:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2593:                   }
                   2594: 	       }
1.8       www      2595:                rename($transname,$filename);
1.607     raeburn  2596:                return 'ok';
1.8       www      2597:            }
1.290     www      2598:        }
1.8       www      2599:     }
1.330     www      2600: }
                   2601: 
                   2602: # ------------------------------------------------ Get server side include body
                   2603: sub ssi_body {
1.381     albertel 2604:     my ($filelink,%form)=@_;
1.606     matthew  2605:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2606:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2607:     }
1.953     www      2608:     my $output='';
                   2609:     my $response;
1.980     raeburn  2610:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2611:        ($output,$response)=&externalssi($filelink);
1.953     www      2612:     } else {
1.1004    droeschl 2613:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2614:        $filelink .= 'inhibitmenu=yes';
1.953     www      2615:        ($output,$response)=&ssi($filelink,%form);
                   2616:     }
1.778     albertel 2617:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2618:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2619:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2620:     if (wantarray) {
                   2621:         return ($output, $response);
                   2622:     } else {
                   2623:         return $output;
                   2624:     }
1.8       www      2625: }
                   2626: 
1.15      www      2627: # --------------------------------------------------------- Server Side Include
                   2628: 
1.782     albertel 2629: sub absolute_url {
                   2630:     my ($host_name) = @_;
                   2631:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2632:     if ($host_name eq '') {
                   2633: 	$host_name = $ENV{'SERVER_NAME'};
                   2634:     }
                   2635:     return $protocol.$host_name;
                   2636: }
                   2637: 
1.942     foxr     2638: #
                   2639: #   Server side include.
                   2640: # Parameters:
                   2641: #  fn     Possibly encrypted resource name/id.
                   2642: #  form   Hash that describes how the rendering should be done
                   2643: #         and other things.
1.944     foxr     2644: # Returns:
1.950     raeburn  2645: #   Scalar context: The content of the response.
                   2646: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2647: #     
1.15      www      2648: sub ssi {
                   2649: 
1.944     foxr     2650:     my ($fn,%form)=@_;
1.15      www      2651:     my $ua=new LWP::UserAgent;
1.23      www      2652:     my $request;
1.711     albertel 2653: 
                   2654:     $form{'no_update_last_known'}=1;
1.895     albertel 2655:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2656:     if (%form) {
1.782     albertel 2657:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2658:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2659:     } else {
1.782     albertel 2660:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2661:     }
                   2662: 
1.15      www      2663:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2664:     my $response= $ua->request($request);
1.1182    foxr     2665:     my $content = $response->content;
                   2666: 
                   2667: 
1.944     foxr     2668:     if (wantarray) {
1.1173    foxr     2669: 	return ($content, $response);
1.944     foxr     2670:     } else {
1.1173    foxr     2671: 	return $content;
1.942     foxr     2672:     }
1.324     www      2673: }
                   2674: 
                   2675: sub externalssi {
                   2676:     my ($url)=@_;
                   2677:     my $ua=new LWP::UserAgent;
                   2678:     my $request=new HTTP::Request('GET',$url);
                   2679:     my $response=$ua->request($request);
1.954     raeburn  2680:     if (wantarray) {
                   2681:         return ($response->content, $response);
                   2682:     } else {
                   2683:         return $response->content;
                   2684:     }
1.15      www      2685: }
1.254     www      2686: 
1.492     albertel 2687: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2688: 
                   2689: sub allowuploaded {
                   2690:     my ($srcurl,$url)=@_;
                   2691:     $url=&clutter(&declutter($url));
                   2692:     my $dir=$url;
                   2693:     $dir=~s/\/[^\/]+$//;
                   2694:     my %httpref=();
                   2695:     my $httpurl=&hreflocation('',$url);
                   2696:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2697:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2698: }
1.477     raeburn  2699: 
1.1193    raeburn  2700: #
                   2701: # Determine if the current user should be able to edit a particular resource,
                   2702: # when viewing in course context.
                   2703: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2704: #     Functions.
                   2705: # (b) When displaying folder contents in course editor, used to determine if
                   2706: #     "Edit" link will be displayed alongside resource.
                   2707: #
1.1196    raeburn  2708: #  input: six args -- filename (decluttered), course number, course domain,
                   2709: #                   url, symb (if registered) and group (if this is a group
                   2710: #                   item -- e.g., bulletin board, group page etc.).
                   2711: #  output: array of five scalars -- 
1.1193    raeburn  2712: #          $cfile -- url for file editing if editable on current server
                   2713: #          $home -- homeserver of resource (i.e., for author if published,
                   2714: #                                           or course if uploaded.).
                   2715: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2716: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2717: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2718: #
                   2719: 
                   2720: sub can_edit_resource {
1.1194    raeburn  2721:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2722:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2723: #
                   2724: # For aboutme pages user can only edit his/her own.
                   2725: #
1.1199    raeburn  2726:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2727:         my ($sdom,$sname) = ($1,$2);
                   2728:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2729:             $home = $env{'user.home'};
                   2730:             $cfile = $resurl;
                   2731:             if ($env{'form.forceedit'}) {
                   2732:                 $forceview = 1;
                   2733:             } else {
                   2734:                 $forceedit = 1;
                   2735:             }
                   2736:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2737:         } else {
                   2738:             return;
                   2739:         }
                   2740:     }
                   2741: 
                   2742:     if ($env{'request.course.id'}) {
                   2743:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2744:         if ($group ne '') {
                   2745: # if this is a group homepage or group bulletin board, check group privs
                   2746:             my $allowed = 0;
1.1197    raeburn  2747:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2748:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2749:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2750:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2751:                     $allowed = 1;
                   2752:                 }
1.1197    raeburn  2753:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2754:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2755:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2756:                     $allowed = 1;
                   2757:                 }
                   2758:             }
                   2759:             if ($allowed) {
                   2760:                 $home=&homeserver($cnum,$cdom);
                   2761:                 if ($env{'form.forceedit'}) {
                   2762:                     $forceview = 1;
                   2763:                 } else {
                   2764:                     $forceedit = 1;
                   2765:                 }
                   2766:                 $cfile = $resurl;
                   2767:             } else {
                   2768:                 return;
                   2769:             }
                   2770:         } else {
1.1208    raeburn  2771:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2772:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2773:                     return;
                   2774:                 }
                   2775:             } elsif (!$crsedit) {
1.1194    raeburn  2776: #
                   2777: # No edit allowed where CC has switched to student role.
                   2778: #
                   2779:                 return;
                   2780:             }
                   2781:         }
                   2782:     }
                   2783: 
1.1193    raeburn  2784:     if ($file ne '') {
                   2785:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2786:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2787:                 $uploaded = 1;
                   2788:                 $incourse = 1;
1.1193    raeburn  2789:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2790:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2791:                     if ($env{'form.forceedit'}) {
                   2792:                         $forceview = 1;
                   2793:                     } else {
                   2794:                         $forceedit = 1;
                   2795:                     }
1.1194    raeburn  2796:                 }
                   2797:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2798:                 $incourse = 1;
                   2799:                 if ($env{'form.forceedit'}) {
                   2800:                     $forceview = 1;
                   2801:                 } else {
                   2802:                     $forceedit = 1;
                   2803:                 }
                   2804:                 $cfile = $resurl;
                   2805:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2806:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2807:                     $incourse = 1;
                   2808:                     if ($env{'form.forceedit'}) {
                   2809:                         $forceview = 1;
                   2810:                     } else {
                   2811:                         $forceedit = 1;
                   2812:                     }
                   2813:                     $cfile = $resurl;
1.1199    raeburn  2814:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2815:                     $incourse = 1;
                   2816:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2817:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2818:                     $incourse = 1;
1.1199    raeburn  2819:                     if ($env{'form.forceedit'}) {
                   2820:                         $forceview = 1;
                   2821:                     } else {
                   2822:                         $forceedit = 1;
                   2823:                     }
                   2824:                     $cfile = $resurl;
1.1208    raeburn  2825:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2826:                     $incourse = 1;
                   2827:                     if ($env{'form.forceedit'}) {
                   2828:                         $forceview = 1;
                   2829:                     } else {
                   2830:                         $forceedit = 1;
                   2831:                     }
                   2832:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2833:                 }
                   2834:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2835:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2836:                 if (&is_on_map($template)) { 
                   2837:                     $incourse = 1;
                   2838:                     $forceview = 1;
                   2839:                     $cfile = $template;
1.1193    raeburn  2840:                 }
1.1199    raeburn  2841:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2842:                     $incourse = 1;
                   2843:                     if ($env{'form.forceedit'}) {
                   2844:                         $forceview = 1;
                   2845:                     } else {
                   2846:                         $forceedit = 1;
                   2847:                     }
                   2848:                     $cfile = $resurl;
                   2849:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2850:                 $incourse = 1;
                   2851:                 $forceview = 1;
                   2852:                 if ($symb) {
                   2853:                     my ($map,$id,$res)=&decode_symb($symb);
                   2854:                     $env{'request.symb'} = $symb;
                   2855:                     $cfile = &clutter($res);
                   2856:                 } else {
                   2857:                     $cfile = $env{'form.suppurl'};
                   2858:                     $cfile =~ s{^http://}{};
                   2859:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2860:                 }
1.1234    raeburn  2861:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2862:                 if ($env{'form.forceedit'}) {
                   2863:                     $forceview = 1;
                   2864:                 } else {
                   2865:                     $forceedit = 1;
                   2866:                 }
                   2867:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  2868:             }
                   2869:         }
1.1194    raeburn  2870:         if ($uploaded || $incourse) {
                   2871:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2872:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2873:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2874:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2875:             # Check that the user has permission to edit this resource
                   2876:             my $setpriv = 1;
                   2877:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2878:             if (defined($cfudom)) {
                   2879:                 $home=&homeserver($cfuname,$cfudom);
                   2880:                 $cfile=$file;
                   2881:             }
                   2882:         }
1.1194    raeburn  2883:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2884:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2885:             my @ids=&current_machine_ids();
                   2886:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2887:                 $switchserver=1;
                   2888:             }
                   2889:         }
                   2890:     }
1.1194    raeburn  2891:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2892: }
                   2893: 
                   2894: sub is_course_upload {
                   2895:     my ($file,$cnum,$cdom) = @_;
                   2896:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2897:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2898:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2899:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2900:         return 1;
                   2901:     }
                   2902:     return;
                   2903: }
                   2904: 
1.1194    raeburn  2905: sub in_course {
1.1195    raeburn  2906:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2907:     if ($hideprivileged) {
                   2908:         my $skipuser;
1.1219    raeburn  2909:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2910:         my @possdoms = ($cdom);  
                   2911:         if ($coursehash{'checkforpriv'}) { 
                   2912:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   2913:         }
                   2914:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  2915:             $skipuser = 1;
                   2916:             if ($coursehash{'nothideprivileged'}) {
                   2917:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2918:                     my $user;
                   2919:                     if ($item =~ /:/) {
                   2920:                         $user = $item;
                   2921:                     } else {
                   2922:                         $user = join(':',split(/[\@]/,$item));
                   2923:                     }
                   2924:                     if ($user eq $uname.':'.$udom) {
                   2925:                         undef($skipuser);
                   2926:                         last;
                   2927:                     }
                   2928:                 }
                   2929:             }
                   2930:             if ($skipuser) {
                   2931:                 return 0;
                   2932:             }
                   2933:         }
                   2934:     }
1.1194    raeburn  2935:     $type ||= 'any';
                   2936:     if (!defined($cdom) || !defined($cnum)) {
                   2937:         my $cid  = $env{'request.course.id'};
                   2938:         $cdom = $env{'course.'.$cid.'.domain'};
                   2939:         $cnum = $env{'course.'.$cid.'.num'};
                   2940:     }
                   2941:     my $typesref;
1.1195    raeburn  2942:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  2943:         $typesref = ['active','previous','future'];
                   2944:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2945:         $typesref = [$type];
                   2946:     }
                   2947:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2948:                               $typesref,undef,[$cdom]);
                   2949:     my ($tmp) = keys(%roles);
                   2950:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2951:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2952:     if (@course_roles > 0) {
                   2953:         return 1;
                   2954:     }
                   2955:     return 0;
                   2956: }
                   2957: 
1.478     albertel 2958: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2959: # input: action, courseID, current domain, intended
1.637     raeburn  2960: #        path to file, source of file, instruction to parse file for objects,
                   2961: #        ref to hash for embedded objects,
                   2962: #        ref to hash for codebase of java objects.
1.1095    raeburn  2963: #        reference to scalar to accommodate mime type determined
                   2964: #          from File::MMagic if $parser = parse.
1.637     raeburn  2965: #
1.485     raeburn  2966: # output: url to file (if action was uploaddoc), 
                   2967: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2968: #
1.478     albertel 2969: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2970: # course.
1.477     raeburn  2971: #
1.478     albertel 2972: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2973: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2974: #          course's home server.
1.477     raeburn  2975: #
1.478     albertel 2976: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2977: #          be copied from $source (current location) to 
                   2978: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2979: #         and will then be copied to
                   2980: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2981: #         course's home server.
1.485     raeburn  2982: #
1.481     raeburn  2983: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2984: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2985: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2986: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2987: #         in course's home server.
1.637     raeburn  2988: #
1.477     raeburn  2989: 
                   2990: sub process_coursefile {
1.1095    raeburn  2991:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2992:         $mimetype)=@_;
1.477     raeburn  2993:     my $fetchresult;
1.638     albertel 2994:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2995:     if ($action eq 'propagate') {
1.638     albertel 2996:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2997: 			     $home);
1.481     raeburn  2998:     } else {
1.477     raeburn  2999:         my $fpath = '';
                   3000:         my $fname = $file;
1.478     albertel 3001:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3002:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3003:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3004:         if ($action eq 'copy') {
                   3005:             if ($source eq '') {
                   3006:                 $fetchresult = 'no source file';
                   3007:                 return $fetchresult;
                   3008:             } else {
                   3009:                 my $destination = $filepath.'/'.$fname;
                   3010:                 rename($source,$destination);
                   3011:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3012:                                  $home);
1.481     raeburn  3013:             }
                   3014:         } elsif ($action eq 'uploaddoc') {
                   3015:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3016:             print $fh $env{'form.'.$source};
1.481     raeburn  3017:             close($fh);
1.637     raeburn  3018:             if ($parser eq 'parse') {
1.1024    raeburn  3019:                 my $mm = new File::MMagic;
1.1095    raeburn  3020:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3021:                 if ($type eq 'text/html') {
1.1024    raeburn  3022:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3023:                     unless ($parse_result eq 'ok') {
                   3024:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3025:                     }
1.637     raeburn  3026:                 }
1.1095    raeburn  3027:                 if (ref($mimetype)) {
                   3028:                     $$mimetype = $type;
                   3029:                 } 
1.637     raeburn  3030:             }
1.477     raeburn  3031:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3032:                                  $home);
1.481     raeburn  3033:             if ($fetchresult eq 'ok') {
                   3034:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3035:             } else {
                   3036:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3037:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3038:                 return '/adm/notfound.html';
                   3039:             }
1.477     raeburn  3040:         }
                   3041:     }
1.485     raeburn  3042:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3043:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3044:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3045:     }
                   3046:     return $fetchresult;
                   3047: }
                   3048: 
1.637     raeburn  3049: sub build_filepath {
                   3050:     my ($fpath) = @_;
                   3051:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3052:     unless ($fpath eq '') {
                   3053:         my @parts=split('/',$fpath);
                   3054:         foreach my $part (@parts) {
                   3055:             $filepath.= '/'.$part;
                   3056:             if ((-e $filepath)!=1) {
                   3057:                 mkdir($filepath,0777);
                   3058:             }
                   3059:         }
                   3060:     }
                   3061:     return $filepath;
                   3062: }
                   3063: 
                   3064: sub store_edited_file {
1.638     albertel 3065:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3066:     my $file = $primary_url;
                   3067:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3068:     my $fpath = '';
                   3069:     my $fname = $file;
                   3070:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3071:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3072:     my $filepath = &build_filepath($fpath);
                   3073:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3074:     print $fh $content;
                   3075:     close($fh);
1.638     albertel 3076:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3077:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3078: 			  $home);
1.637     raeburn  3079:     if ($$fetchresult eq 'ok') {
                   3080:         return '/uploaded/'.$fpath.'/'.$fname;
                   3081:     } else {
1.638     albertel 3082:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3083: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3084:         return '/adm/notfound.html';
                   3085:     }
                   3086: }
                   3087: 
1.531     albertel 3088: sub clean_filename {
1.831     albertel 3089:     my ($fname,$args)=@_;
1.315     www      3090: # Replace Windows backslashes by forward slashes
1.257     www      3091:     $fname=~s/\\/\//g;
1.831     albertel 3092:     if (!$args->{'keep_path'}) {
                   3093:         # Get rid of everything but the actual filename
                   3094: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3095:     }
1.315     www      3096: # Replace spaces by underscores
                   3097:     $fname=~s/\s+/\_/g;
                   3098: # Replace all other weird characters by nothing
1.831     albertel 3099:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3100: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3101: # numbers
                   3102:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3103:     return $fname;
                   3104: }
1.1051    raeburn  3105: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3106: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3107: # image with the same aspect ratio as the original, but with dimensions which do 
                   3108: # not exceed $resizewidth and $resizeheight.
                   3109:  
1.984     neumanie 3110: sub resizeImage {
1.1051    raeburn  3111:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3112:     my $ima = Image::Magick->new;
                   3113:     my $resized;
                   3114:     if (-e $img_path) {
                   3115:         $ima->Read($img_path);
                   3116:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3117:             my $width = $ima->Get('width');
                   3118:             my $height = $ima->Get('height');
                   3119:             if ($width > $resizewidth) {
                   3120: 	        my $factor = $width/$resizewidth;
                   3121:                 my $newheight = $height/$factor;
                   3122:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3123:                 $resized = 1;
                   3124:             }
                   3125:         }
                   3126:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3127:             my $width = $ima->Get('width');
                   3128:             my $height = $ima->Get('height');
                   3129:             if ($height > $resizeheight) {
                   3130:                 my $factor = $height/$resizeheight;
                   3131:                 my $newwidth = $width/$factor;
                   3132:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3133:                 $resized = 1;
                   3134:             }
                   3135:         }
                   3136:         if ($resized) {
                   3137:             $ima->Write($img_path);
                   3138:         }
                   3139:     }
                   3140:     return;
1.977     amueller 3141: }
                   3142: 
1.608     albertel 3143: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3144: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3145: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3146: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3147: #                                    canceloverwrite, or ''. 
                   3148: #                   if 'coursedoc': upload to the current course
                   3149: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3150: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3151: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3152: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3153: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3154: #        $allfiles - reference to hash for embedded objects
                   3155: #        $codebase - reference to hash for codebase of java objects
                   3156: #        $desuname - username for permanent storage of uploaded file
                   3157: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3158: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3159: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3160: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3161: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3162: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3163: #                    from File::MMagic.
1.858     raeburn  3164: # 
1.686     albertel 3165: # output: url of file in userspace, or error: <message> 
                   3166: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3167: 
1.531     albertel 3168: sub userfileupload {
1.1090    raeburn  3169:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3170:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3171:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3172:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3173:     $fname=&clean_filename($fname);
1.1090    raeburn  3174:     # See if there is anything left
1.257     www      3175:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3176:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3177:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3178:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3179:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3180:         my $now = time;
1.1090    raeburn  3181:         my $filepath;
1.1095    raeburn  3182:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3183:              $filepath = 'tmp/helprequests/'.$now;
                   3184:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3185:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3186:                          '_'.$env{'user.domain'}.'/pending';
                   3187:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3188:             my ($docuname,$docudom);
                   3189:             if ($destudom) {
                   3190:                 $docudom = $destudom;
                   3191:             } else {
                   3192:                 $docudom = $env{'user.domain'};
                   3193:             }
                   3194:             if ($destuname) {
                   3195:                 $docuname = $destuname;
                   3196:             } else {
                   3197:                 $docuname = $env{'user.name'};
                   3198:             }
                   3199:             if (exists($env{'form.group'})) {
                   3200:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3201:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3202:             }
                   3203:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3204:             if ($context eq 'canceloverwrite') {
                   3205:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3206:                 if (-e  $tempfile) {
                   3207:                     my @info = stat($tempfile);
                   3208:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3209:                         unlink($tempfile);
                   3210:                     }
                   3211:                 }
                   3212:                 return;
1.523     raeburn  3213:             }
                   3214:         }
1.1090    raeburn  3215:         # Create the directory if not present
1.741     raeburn  3216:         my @parts=split(/\//,$filepath);
                   3217:         my $fullpath = $perlvar{'lonDaemons'};
                   3218:         for (my $i=0;$i<@parts;$i++) {
                   3219:             $fullpath .= '/'.$parts[$i];
                   3220:             if ((-e $fullpath)!=1) {
                   3221:                 mkdir($fullpath,0777);
                   3222:             }
                   3223:         }
                   3224:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3225:         print $fh $env{'form.'.$formname};
                   3226:         close($fh);
1.1090    raeburn  3227:         if ($context eq 'existingfile') {
                   3228:             my @info = stat($fullpath.'/'.$fname);
                   3229:             return ($fullpath.'/'.$fname,$info[9]);
                   3230:         } else {
                   3231:             return $fullpath.'/'.$fname;
                   3232:         }
1.523     raeburn  3233:     }
1.995     raeburn  3234:     if ($subdir eq 'scantron') {
                   3235:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3236:     } else {
1.995     raeburn  3237:         $fname="$subdir/$fname";
                   3238:     }
1.1090    raeburn  3239:     if ($context eq 'coursedoc') {
1.638     albertel 3240: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3241: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3242:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3243:             return &finishuserfileupload($docuname,$docudom,
                   3244: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3245: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3246:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3247:         } else {
1.1218    raeburn  3248:             if ($env{'form.folder'}) {
                   3249:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3250:             }
1.638     albertel 3251:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3252: 				       $fname,$formname,$parser,
1.1095    raeburn  3253: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3254:         }
1.719     banghart 3255:     } elsif (defined($destuname)) {
                   3256:         my $docuname=$destuname;
                   3257:         my $docudom=$destudom;
1.860     raeburn  3258: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3259: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3260:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3261:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3262:     } else {
1.638     albertel 3263:         my $docuname=$env{'user.name'};
                   3264:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3265:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3266:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3267:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3268:         }
1.860     raeburn  3269: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3270: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3271:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3272:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3273:     }
1.271     www      3274: }
                   3275: 
                   3276: sub finishuserfileupload {
1.860     raeburn  3277:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3278:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3279:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3280:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3281:   
1.860     raeburn  3282:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3283:     $file=$fname;
                   3284:     if ($fname=~m|/|) {
                   3285:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3286: 	$path.=$fnamepath.'/';
                   3287:     }
1.259     www      3288:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3289:     my $count;
                   3290:     for ($count=4;$count<=$#parts;$count++) {
                   3291:         $filepath.="/$parts[$count]";
                   3292:         if ((-e $filepath)!=1) {
                   3293: 	    mkdir($filepath,0777);
                   3294:         }
                   3295:     }
1.984     neumanie 3296: 
1.258     www      3297: # Save the file
                   3298:     {
1.701     albertel 3299: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3300: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3301: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3302: 	    return '/adm/notfound.html';
                   3303: 	}
1.1090    raeburn  3304:         if ($context eq 'overwrite') {
1.1117    foxr     3305:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3306:             my $target = $filepath.'/'.$file;
                   3307:             if (-e $source) {
                   3308:                 my @info = stat($source);
                   3309:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3310:                     unless (&File::Copy::move($source,$target)) {
                   3311:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3312:                         return "Moving from $source failed";
                   3313:                     }
                   3314:                 } else {
                   3315:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3316:                 }
                   3317:             } else {
                   3318:                 return "Temporary file: $source missing";
                   3319:             }
                   3320:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3321: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3322: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3323: 	    return '/adm/notfound.html';
                   3324: 	}
1.570     albertel 3325: 	close(FH);
1.1051    raeburn  3326:         if ($resizewidth && $resizeheight) {
                   3327:             my $mm = new File::MMagic;
                   3328:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3329:             if ($mime_type =~ m{^image/}) {
                   3330: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3331:             }  
1.977     amueller 3332: 	}
1.258     www      3333:     }
1.1152    raeburn  3334:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3335:         if (ref($mimetype)) {
                   3336:             if ($$mimetype eq '') {
                   3337:                 my $mm = new File::MMagic;
                   3338:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3339:                 $$mimetype = $type;
                   3340:             }
                   3341:         }
                   3342:     }
1.637     raeburn  3343:     if ($parser eq 'parse') {
1.1152    raeburn  3344:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3345:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3346:                                                        $allfiles,$codebase);
                   3347:             unless ($parse_result eq 'ok') {
                   3348:                 &logthis('Failed to parse '.$filepath.$file.
                   3349: 	   	         ' for embedded media: '.$parse_result); 
                   3350:             }
1.637     raeburn  3351:         }
                   3352:     }
1.860     raeburn  3353:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3354:         my $input = $filepath.'/'.$file;
                   3355:         my $output = $filepath.'/'.'tn-'.$file;
                   3356:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3357:         system("convert -sample $thumbsize $input $output");
                   3358:         if (-e $filepath.'/'.'tn-'.$file) {
                   3359:             $fetchthumb  = 1; 
                   3360:         }
                   3361:     }
1.858     raeburn  3362:  
1.259     www      3363: # Notify homeserver to grep it
                   3364: #
1.984     neumanie 3365:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3366:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3367:     if ($fetchresult eq 'ok') {
1.860     raeburn  3368:         if ($fetchthumb) {
                   3369:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3370:             if ($thumbresult ne 'ok') {
                   3371:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3372:                          $docuhome.': '.$thumbresult);
                   3373:             }
                   3374:         }
1.259     www      3375: #
1.258     www      3376: # Return the URL to it
1.494     albertel 3377:         return '/uploaded/'.$path.$file;
1.263     www      3378:     } else {
1.494     albertel 3379:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3380: 		 ': '.$fetchresult);
1.263     www      3381:         return '/adm/notfound.html';
1.858     raeburn  3382:     }
1.493     albertel 3383: }
                   3384: 
1.637     raeburn  3385: sub extract_embedded_items {
1.961     raeburn  3386:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3387:     my @state = ();
1.1164    raeburn  3388:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3389:     my %javafiles = (
                   3390:                       codebase => '',
                   3391:                       code => '',
                   3392:                       archive => ''
                   3393:                     );
                   3394:     my %mediafiles = (
                   3395:                       src => '',
                   3396:                       movie => '',
                   3397:                      );
1.648     raeburn  3398:     my $p;
                   3399:     if ($content) {
                   3400:         $p = HTML::LCParser->new($content);
                   3401:     } else {
1.961     raeburn  3402:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3403:     }
1.641     albertel 3404:     while (my $t=$p->get_token()) {
1.640     albertel 3405: 	if ($t->[0] eq 'S') {
                   3406: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3407: 	    push(@state, $tagname);
1.648     raeburn  3408:             if (lc($tagname) eq 'allow') {
                   3409:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3410:             }
1.640     albertel 3411: 	    if (lc($tagname) eq 'img') {
                   3412: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3413: 	    }
1.886     albertel 3414: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3415:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3416:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3417:                 }
1.886     albertel 3418: 	    }
1.645     raeburn  3419:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3420:                 my $src;
1.645     raeburn  3421:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3422:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3423:                 } else {
1.1164    raeburn  3424:                     if ($attr->{'src'} ne '') {
                   3425:                         $src = $attr->{'src'};
                   3426:                         &add_filetype($allfiles,$src,'src');
                   3427:                     }
                   3428:                 }
                   3429:                 my $text = $p->get_trimmed_text();
                   3430:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3431:                     my @swfargs = split(/,/,$1);
                   3432:                     foreach my $item (@swfargs) {
                   3433:                         $item =~ s/["']//g;
                   3434:                         $item =~ s/^\s+//;
                   3435:                         $item =~ s/\s+$//;
                   3436:                     }
                   3437:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3438:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3439:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3440:                         } else {
                   3441:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3442:                         }
                   3443:                     }
1.645     raeburn  3444:                 }
                   3445:             }
                   3446:             if (lc($tagname) eq 'link') {
                   3447:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3448:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3449:                 }
                   3450:             }
1.640     albertel 3451: 	    if (lc($tagname) eq 'object' ||
                   3452: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3453: 		foreach my $item (keys(%javafiles)) {
                   3454: 		    $javafiles{$item} = '';
                   3455: 		}
1.1164    raeburn  3456:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3457:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3458:                 }
1.640     albertel 3459: 	    }
                   3460: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3461: 		my $name = lc($attr->{'name'});
                   3462: 		foreach my $item (keys(%javafiles)) {
                   3463: 		    if ($name eq $item) {
                   3464: 			$javafiles{$item} = $attr->{'value'};
                   3465: 			last;
                   3466: 		    }
                   3467: 		}
1.1164    raeburn  3468:                 my $pathfrom;
1.640     albertel 3469: 		foreach my $item (keys(%mediafiles)) {
                   3470: 		    if ($name eq $item) {
1.1164    raeburn  3471:                         $pathfrom = $attr->{'value'};
                   3472:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3473: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3474: 			last;
                   3475: 		    }
                   3476: 		}
1.1164    raeburn  3477:                 if ($name eq 'flashvars') {
                   3478:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3479:                 }
                   3480:                 if ($pathfrom ne '') {
                   3481:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3482:                                          $pathfrom);
                   3483:                 }
1.640     albertel 3484: 	    }
                   3485: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3486: 		foreach my $item (keys(%javafiles)) {
                   3487: 		    if ($attr->{$item}) {
                   3488: 			$javafiles{$item} = $attr->{$item};
                   3489: 			last;
                   3490: 		    }
                   3491: 		}
                   3492: 		foreach my $item (keys(%mediafiles)) {
                   3493: 		    if ($attr->{$item}) {
                   3494: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3495: 			last;
                   3496: 		    }
                   3497: 		}
1.1164    raeburn  3498:                 if (lc($tagname) eq 'embed') {
                   3499:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3500:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3501:                                              $attr->{'src'});
                   3502:                     }
                   3503:                 }
1.640     albertel 3504: 	    }
1.1164    raeburn  3505:             if ($t->[4] =~ m{/>$}) {
                   3506:                 pop(@state);  
                   3507:             }
1.640     albertel 3508: 	} elsif ($t->[0] eq 'E') {
                   3509: 	    my ($tagname) = ($t->[1]);
                   3510: 	    if ($javafiles{'codebase'} ne '') {
                   3511: 		$javafiles{'codebase'} .= '/';
                   3512: 	    }  
                   3513: 	    if (lc($tagname) eq 'applet' ||
                   3514: 		lc($tagname) eq 'object' ||
                   3515: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3516: 		) {
                   3517: 		foreach my $item (keys(%javafiles)) {
                   3518: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3519: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3520: 			&add_filetype($allfiles,$file,$item);
                   3521: 		    }
                   3522: 		}
                   3523: 	    } 
                   3524: 	    pop @state;
                   3525: 	}
                   3526:     }
1.1164    raeburn  3527:     foreach my $id (sort(keys(%flashvars))) {
                   3528:         if ($shockwave{$id} ne '') {
                   3529:             my @pairs = split(/\&/,$flashvars{$id});
                   3530:             foreach my $pair (@pairs) {
                   3531:                 my ($key,$value) = split(/\=/,$pair);
                   3532:                 if ($key eq 'thumb') {
                   3533:                     &add_filetype($allfiles,$value,$key);
                   3534:                 } elsif ($key eq 'content') {
                   3535:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3536:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3537:                     if ($ext ne '') {
                   3538:                         &add_filetype($allfiles,$path.$value,$ext);
                   3539:                     }
                   3540:                 }
                   3541:             }
                   3542:         }
                   3543:     }
1.637     raeburn  3544:     return 'ok';
                   3545: }
                   3546: 
1.639     albertel 3547: sub add_filetype {
                   3548:     my ($allfiles,$file,$type)=@_;
                   3549:     if (exists($allfiles->{$file})) {
                   3550: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3551: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3552: 	}
                   3553:     } else {
                   3554: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3555:     }
                   3556: }
                   3557: 
1.1164    raeburn  3558: sub embedded_dependency {
                   3559:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3560:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3561:         if (($identifier ne '') &&
                   3562:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3563:             ($pathfrom ne '')) {
                   3564:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3565:             foreach my $dep (@{$related->{$identifier}}) {
                   3566:                 &add_filetype($allfiles,$path.$dep,'object');
                   3567:             }
                   3568:         }
                   3569:     }
                   3570:     return;
                   3571: }
                   3572: 
1.493     albertel 3573: sub removeuploadedurl {
1.984     neumanie 3574:     my ($url)=@_;	
                   3575:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3576:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3577: }
                   3578: 
                   3579: sub removeuserfile {
                   3580:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3581:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3582:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3583:     if ($result eq 'ok') {	
1.798     raeburn  3584:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3585:             my $metafile = $fname.'.meta';
                   3586:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3587: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3588:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3589:             my $sqlresult = 
1.823     albertel 3590:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3591:                                         'portfolio_metadata',$group,
                   3592:                                         'delete');
1.798     raeburn  3593:         }
                   3594:     }
                   3595:     return $result;
1.257     www      3596: }
1.15      www      3597: 
1.530     albertel 3598: sub mkdiruserfile {
                   3599:     my ($docuname,$docudom,$dir)=@_;
                   3600:     my $home=&homeserver($docuname,$docudom);
                   3601:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3602: }
                   3603: 
1.531     albertel 3604: sub renameuserfile {
                   3605:     my ($docuname,$docudom,$old,$new)=@_;
                   3606:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3607:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3608:                         &escape("$old").':'.&escape("$new"),$home);
                   3609:     if ($result eq 'ok') {
                   3610:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3611:             my $oldmeta = $old.'.meta';
                   3612:             my $newmeta = $new.'.meta';
                   3613:             my $metaresult = 
                   3614:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3615: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3616:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3617:             my $sqlresult = 
1.823     albertel 3618:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3619:                                         'portfolio_metadata',$group,
                   3620:                                         'delete');
1.798     raeburn  3621:         }
                   3622:     }
                   3623:     return $result;
1.531     albertel 3624: }
                   3625: 
1.14      www      3626: # ------------------------------------------------------------------------- Log
                   3627: 
                   3628: sub log {
                   3629:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3630:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3631: }
                   3632: 
                   3633: # ------------------------------------------------------------------ Course Log
1.352     www      3634: #
                   3635: # This routine flushes several buffers of non-mission-critical nature
                   3636: #
1.157     www      3637: 
                   3638: sub flushcourselogs {
1.352     www      3639:     &logthis('Flushing log buffers');
                   3640: #
                   3641: # course logs
                   3642: # This is a log of all transactions in a course, which can be used
                   3643: # for data mining purposes
                   3644: #
                   3645: # It also collects the courseid database, which lists last transaction
                   3646: # times and course titles for all courseids
                   3647: #
                   3648:     my %courseidbuffer=();
1.921     raeburn  3649:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3650:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3651: 		          &escape($courselogs{$crsid}),
                   3652: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3653: 	    delete $courselogs{$crsid};
                   3654:         } else {
                   3655:             &logthis('Failed to flush log buffer for '.$crsid);
                   3656:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3657:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3658:                         " exceeded maximum size, deleting.</font>");
                   3659:                delete $courselogs{$crsid};
                   3660:             }
1.352     www      3661:         }
1.920     raeburn  3662:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3663:             'description' => $coursedescrbuf{$crsid},
                   3664:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3665:             'type'        => $coursetypebuf{$crsid},
                   3666:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3667:         };
1.191     harris41 3668:     }
1.352     www      3669: #
                   3670: # Write course id database (reverse lookup) to homeserver of courses 
                   3671: # Is used in pickcourse
                   3672: #
1.840     albertel 3673:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3674:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3675:                                     $courseidbuffer{$crs_home},
                   3676:                                     $crs_home,'timeonly');
1.352     www      3677:     }
                   3678: #
                   3679: # File accesses
                   3680: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3681: #
1.449     matthew  3682:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3683:         if ($entry =~ /___count$/) {
                   3684:             my ($dom,$name);
1.807     albertel 3685:             ($dom,$name,undef)=
1.811     albertel 3686: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3687:             if (! defined($dom) || $dom eq '' || 
                   3688:                 ! defined($name) || $name eq '') {
1.620     albertel 3689:                 my $cid = $env{'request.course.id'};
                   3690:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3691:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3692:             }
1.450     matthew  3693:             my $value = $accesshash{$entry};
                   3694:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3695:             my %temphash=($url => $value);
1.449     matthew  3696:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3697:             if ($result eq 'ok') {
                   3698:                 delete $accesshash{$entry};
                   3699:             }
                   3700:         } else {
1.811     albertel 3701:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3702:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3703:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3704:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3705:                 delete $accesshash{$entry};
                   3706:             }
1.185     www      3707:         }
1.191     harris41 3708:     }
1.352     www      3709: #
                   3710: # Roles
                   3711: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3712: #
1.800     albertel 3713:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3714:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3715: 	    split(/\:/,$entry);
                   3716:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3717:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3718:                 $rudom,$runame) eq 'ok') {
                   3719: 	    delete $userrolehash{$entry};
                   3720:         }
                   3721:     }
1.662     raeburn  3722: #
                   3723: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3724: #
                   3725:     my %domrolebuffer = ();
1.1000    raeburn  3726:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3727:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3728:         if ($domrolebuffer{$rudom}) {
                   3729:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3730:                       '='.&escape($domainrolehash{$entry});
                   3731:         } else {
                   3732:             $domrolebuffer{$rudom}.=&escape($entry).
                   3733:                       '='.&escape($domainrolehash{$entry});
                   3734:         }
                   3735:         delete $domainrolehash{$entry};
                   3736:     }
                   3737:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3738: 	my %servers = &get_servers($dom,'library');
                   3739: 	foreach my $tryserver (keys(%servers)) {
                   3740: 	    unless (&reply('domroleput:'.$dom.':'.
                   3741: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3742: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3743: 	    }
1.662     raeburn  3744:         }
                   3745:     }
1.186     www      3746:     $dumpcount++;
1.157     www      3747: }
                   3748: 
                   3749: sub courselog {
                   3750:     my $what=shift;
1.158     www      3751:     $what=time.':'.$what;
1.620     albertel 3752:     unless ($env{'request.course.id'}) { return ''; }
                   3753:     $coursedombuf{$env{'request.course.id'}}=
                   3754:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3755:     $coursenumbuf{$env{'request.course.id'}}=
                   3756:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3757:     $coursehombuf{$env{'request.course.id'}}=
                   3758:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3759:     $coursedescrbuf{$env{'request.course.id'}}=
                   3760:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3761:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3762:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3763:     $courseownerbuf{$env{'request.course.id'}}=
                   3764:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3765:     $coursetypebuf{$env{'request.course.id'}}=
                   3766:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3767:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3768: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3769:     } else {
1.620     albertel 3770: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3771:     }
1.620     albertel 3772:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3773: 	&flushcourselogs();
                   3774:     }
1.158     www      3775: }
                   3776: 
                   3777: sub courseacclog {
                   3778:     my $fnsymb=shift;
1.620     albertel 3779:     unless ($env{'request.course.id'}) { return ''; }
                   3780:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3781:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3782:         $what.=':POST';
1.583     matthew  3783:         # FIXME: Probably ought to escape things....
1.800     albertel 3784: 	foreach my $key (keys(%env)) {
                   3785:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3786:                 my $formitem = $1;
                   3787:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3788:                     $what.=':'.$formitem.'='.$env{$key};
                   3789:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3790:                     $what.=':'.$formitem.'='.$env{$key};
                   3791:                 }
1.158     www      3792:             }
1.191     harris41 3793:         }
1.583     matthew  3794:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3795:         # FIXME: We should not be depending on a form parameter that someone
                   3796:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3797:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3798:             $what.= ':POST';
                   3799:             # FIXME: Probably ought to escape things....
                   3800:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3801:                                  'crsdiscuss') {
1.620     albertel 3802:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3803:             }
                   3804:         }
1.158     www      3805:     }
                   3806:     &courselog($what);
1.149     www      3807: }
                   3808: 
1.185     www      3809: sub countacc {
                   3810:     my $url=&declutter(shift);
1.458     matthew  3811:     return if (! defined($url) || $url eq '');
1.620     albertel 3812:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3813: #
                   3814: # Mark that this url was used in this course
                   3815: #
1.620     albertel 3816:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3817: #
                   3818: # Increase the access count for this resource in this child process
                   3819: #
1.281     www      3820:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3821:     $accesshash{$key}++;
1.185     www      3822: }
1.349     www      3823: 
1.361     www      3824: sub linklog {
                   3825:     my ($from,$to)=@_;
                   3826:     $from=&declutter($from);
                   3827:     $to=&declutter($to);
                   3828:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3829:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3830: }
1.1160    www      3831: 
                   3832: sub statslog {
                   3833:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3834:     if ($users<2) { return; }
                   3835:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3836:             'course'       => $env{'request.course.id'},
                   3837:             'sections'     => '"all"',
                   3838:             'num_students' => $users,
                   3839:             'part'         => $part,
                   3840:             'symb'         => $symb,
                   3841:             'mean_tries'   => $av_attempts,
                   3842:             'deg_of_diff'  => $degdiff});
                   3843:     foreach my $key (keys(%dynstore)) {
                   3844:         $accesshash{$key}=$dynstore{$key};
                   3845:     }
                   3846: }
1.361     www      3847:   
1.349     www      3848: sub userrolelog {
                   3849:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3850:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3851:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3852:        $userrolehash
                   3853:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3854:                     =$tend.':'.$tstart;
1.662     raeburn  3855:     }
1.1169    droeschl 3856:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3857:        $userrolehash
                   3858:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3859:                     =$tend.':'.$tstart;
                   3860:     }
1.1169    droeschl 3861:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3862:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3863:        $domainrolehash
                   3864:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3865:                     = $tend.':'.$tstart;
                   3866:     }
1.351     www      3867: }
                   3868: 
1.957     raeburn  3869: sub courserolelog {
                   3870:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3871:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3872:         my $cdom = $1;
                   3873:         my $cnum = $2;
                   3874:         my $sec = $3;
                   3875:         my $namespace = 'rolelog';
                   3876:         my %storehash = (
                   3877:                            role    => $trole,
                   3878:                            start   => $tstart,
                   3879:                            end     => $tend,
                   3880:                            selfenroll => $selfenroll,
                   3881:                            context    => $context,
                   3882:                         );
                   3883:         if ($trole eq 'gr') {
                   3884:             $namespace = 'groupslog';
                   3885:             $storehash{'group'} = $sec;
                   3886:         } else {
                   3887:             $storehash{'section'} = $sec;
                   3888:         }
1.1188    raeburn  3889:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3890:                    $domain,$cnum,$cdom);
1.1184    raeburn  3891:         if (($trole ne 'st') || ($sec ne '')) {
                   3892:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3893:         }
                   3894:     }
                   3895:     return;
                   3896: }
                   3897: 
1.1184    raeburn  3898: sub domainrolelog {
                   3899:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3900:     if ($area =~ m{^/($match_domain)/$}) {
                   3901:         my $cdom = $1;
                   3902:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3903:         my $namespace = 'rolelog';
                   3904:         my %storehash = (
                   3905:                            role    => $trole,
                   3906:                            start   => $tstart,
                   3907:                            end     => $tend,
                   3908:                            context => $context,
                   3909:                         );
1.1188    raeburn  3910:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3911:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3912:     }
                   3913:     return;
                   3914: 
                   3915: }
                   3916: 
                   3917: sub coauthorrolelog {
                   3918:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3919:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3920:         my $audom = $1;
                   3921:         my $auname = $2;
                   3922:         my $namespace = 'rolelog';
                   3923:         my %storehash = (
                   3924:                            role    => $trole,
                   3925:                            start   => $tstart,
                   3926:                            end     => $tend,
                   3927:                            context => $context,
                   3928:                         );
1.1188    raeburn  3929:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3930:                    $domain,$auname,$audom);
1.1184    raeburn  3931:     }
                   3932:     return;
                   3933: }
                   3934: 
1.351     www      3935: sub get_course_adv_roles {
1.948     raeburn  3936:     my ($cid,$codes) = @_;
1.620     albertel 3937:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3938:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3939:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3940:     my %nothide=();
1.800     albertel 3941:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3942:         if ($user !~ /:/) {
                   3943: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3944:         } else {
                   3945:             $nothide{$user}=1;
                   3946:         }
1.470     www      3947:     }
1.1219    raeburn  3948:     my @possdoms = ($coursehash{'domain'});
                   3949:     if ($coursehash{'checkforpriv'}) {
                   3950:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3951:     }
1.351     www      3952:     my %returnhash=();
                   3953:     my %dumphash=
                   3954:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3955:     my $now=time;
1.997     raeburn  3956:     my %privileged;
1.1000    raeburn  3957:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3958: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3959:         if (($tstart) && ($tstart<0)) { next; }
                   3960:         if (($tend) && ($tend<$now)) { next; }
                   3961:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3962:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3963: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  3964:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3965:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3966: 	if ($role eq 'cr') { next; }
1.948     raeburn  3967:         if ($codes) {
                   3968:             if ($section) { $role .= ':'.$section; }
                   3969:             if ($returnhash{$role}) {
                   3970:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3971:             } else {
                   3972:                 $returnhash{$role}=$username.':'.$domain;
                   3973:             }
1.351     www      3974:         } else {
1.988     raeburn  3975:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3976:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3977:             if ($returnhash{$key}) {
                   3978: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3979:             } else {
                   3980:                 $returnhash{$key}=$username.':'.$domain;
                   3981:             }
1.351     www      3982:         }
1.948     raeburn  3983:     }
1.400     www      3984:     return %returnhash;
                   3985: }
                   3986: 
                   3987: sub get_my_roles {
1.937     raeburn  3988:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3989:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3990:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3991:     my (%dumphash,%nothide);
1.1086    raeburn  3992:     if ($context eq 'userroles') {
1.1166    raeburn  3993:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3994:     } else {
1.1219    raeburn  3995:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3996:         if ($hidepriv) {
                   3997:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3998:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3999:                 if ($user !~ /:/) {
                   4000:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4001:                 } else {
                   4002:                     $nothide{$user} = 1;
                   4003:                 }
                   4004:             }
                   4005:         }
1.858     raeburn  4006:     }
1.400     www      4007:     my %returnhash=();
                   4008:     my $now=time;
1.999     raeburn  4009:     my %privileged;
1.800     albertel 4010:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4011:         my ($role,$tend,$tstart);
                   4012:         if ($context eq 'userroles') {
1.1149    raeburn  4013:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4014: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4015:         } else {
                   4016:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4017:         }
1.400     www      4018:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4019:         my $status = 'active';
1.939     raeburn  4020:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4021:             $status = 'previous';
                   4022:         } 
                   4023:         if (($tstart) && ($now<$tstart)) {
                   4024:             $status = 'future';
                   4025:         }
                   4026:         if (ref($types) eq 'ARRAY') {
                   4027:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4028:                 next;
                   4029:             } 
                   4030:         } else {
                   4031:             if ($status ne 'active') {
                   4032:                 next;
                   4033:             }
                   4034:         }
1.867     raeburn  4035:         my ($rolecode,$username,$domain,$section,$area);
                   4036:         if ($context eq 'userroles') {
1.1186    raeburn  4037:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4038:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4039:         } else {
                   4040:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4041:         }
1.832     raeburn  4042:         if (ref($roledoms) eq 'ARRAY') {
                   4043:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4044:                 next;
                   4045:             }
                   4046:         }
                   4047:         if (ref($roles) eq 'ARRAY') {
                   4048:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4049:                 if ($role =~ /^cr\//) {
                   4050:                     if (!grep(/^cr$/,@{$roles})) {
                   4051:                         next;
                   4052:                     }
1.1104    raeburn  4053:                 } elsif ($role =~ /^gr\//) {
                   4054:                     if (!grep(/^gr$/,@{$roles})) {
                   4055:                         next;
                   4056:                     }
1.922     raeburn  4057:                 } else {
                   4058:                     next;
                   4059:                 }
1.832     raeburn  4060:             }
1.867     raeburn  4061:         }
1.937     raeburn  4062:         if ($hidepriv) {
1.1219    raeburn  4063:             my @privroles = ('dc','su');
1.999     raeburn  4064:             if ($context eq 'userroles') {
1.1219    raeburn  4065:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4066:             } else {
1.1219    raeburn  4067:                 my $possdoms = [$domain];
                   4068:                 if (ref($roledoms) eq 'ARRAY') {
                   4069:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4070:                 }
1.1219    raeburn  4071:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4072:                     if (!$nothide{$username.':'.$domain}) {
                   4073:                         next;
                   4074:                     }
                   4075:                 }
1.937     raeburn  4076:             }
                   4077:         }
1.933     raeburn  4078:         if ($withsec) {
                   4079:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4080:                 $tstart.':'.$tend;
                   4081:         } else {
                   4082:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4083:         }
1.832     raeburn  4084:     }
1.373     www      4085:     return %returnhash;
1.399     www      4086: }
                   4087: 
                   4088: # ----------------------------------------------------- Frontpage Announcements
                   4089: #
                   4090: #
                   4091: 
                   4092: sub postannounce {
                   4093:     my ($server,$text)=@_;
1.844     albertel 4094:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4095:     unless ($text=~/\w/) { $text=''; }
                   4096:     return &reply('setannounce:'.&escape($text),$server);
                   4097: }
                   4098: 
                   4099: sub getannounce {
1.448     albertel 4100: 
                   4101:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4102: 	my $announcement='';
1.800     albertel 4103: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4104: 	close($fh);
1.399     www      4105: 	if ($announcement=~/\w/) { 
                   4106: 	    return 
                   4107:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4108:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4109: 	} else {
                   4110: 	    return '';
                   4111: 	}
                   4112:     } else {
                   4113: 	return '';
                   4114:     }
1.351     www      4115: }
1.353     www      4116: 
                   4117: # ---------------------------------------------------------- Course ID routines
                   4118: # Deal with domain's nohist_courseid.db files
                   4119: #
                   4120: 
                   4121: sub courseidput {
1.921     raeburn  4122:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4123:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4124:     my $outcome;
                   4125:     if ($caller eq 'timeonly') {
                   4126:         my $cids = '';
                   4127:         foreach my $item (keys(%$storehash)) {
                   4128:             $cids.=&escape($item).'&';
                   4129:         }
                   4130:         $cids=~s/\&$//;
                   4131:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4132:                           $coursehome);       
                   4133:     } else {
                   4134:         my $items = '';
                   4135:         foreach my $item (keys(%$storehash)) {
                   4136:             $items.= &escape($item).'='.
                   4137:                      &freeze_escape($$storehash{$item}).'&';
                   4138:         }
                   4139:         $items=~s/\&$//;
                   4140:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4141:                           $coursehome);
1.918     raeburn  4142:     }
                   4143:     if ($outcome eq 'unknown_cmd') {
                   4144:         my $what;
                   4145:         foreach my $cid (keys(%$storehash)) {
                   4146:             $what .= &escape($cid).'=';
1.921     raeburn  4147:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4148:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4149:             }
                   4150:             $what =~ s/\:$/&/;
                   4151:         }
                   4152:         $what =~ s/\&$//;  
                   4153:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4154:     } else {
                   4155:         return $outcome;
                   4156:     }
1.353     www      4157: }
                   4158: 
                   4159: sub courseiddump {
1.921     raeburn  4160:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4161:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4162:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4163:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4164:     my $as_hash = 1;
                   4165:     my %returnhash;
                   4166:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4167:     my %libserv = &all_library();
                   4168:     foreach my $tryserver (keys(%libserv)) {
                   4169:         if ( (  $hostidflag == 1 
                   4170: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4171: 	     || (!defined($hostidflag)) ) {
                   4172: 
1.918     raeburn  4173: 	    if (($domfilter eq '') ||
                   4174: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4175:                 my $rep;
                   4176:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4177:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4178:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4179:                                 &escape($descfilter), &escape($instcodefilter), 
                   4180:                                 &escape($ownerfilter), &escape($coursefilter),
                   4181:                                 &escape($typefilter), &escape($regexp_ok), 
                   4182:                                 $as_hash, &escape($selfenrollonly), 
                   4183:                                 &escape($catfilter), $showhidden, $caller, 
                   4184:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4185:                                 &escape($createdbefore), &escape($createdafter), 
                   4186:                                 &escape($creationcontext), $domcloner)));
                   4187:                 } else {
                   4188:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4189:                              $sincefilter.':'.&escape($descfilter).':'.
                   4190:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4191:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4192:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4193:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4194:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4195:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4196:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4197:                              &escape($creationcontext).':'.$domcloner,
                   4198:                              $tryserver);
                   4199:                 }
                   4200:                      
1.918     raeburn  4201:                 my @pairs=split(/\&/,$rep);
                   4202:                 foreach my $item (@pairs) {
                   4203:                     my ($key,$value)=split(/\=/,$item,2);
                   4204:                     $key = &unescape($key);
                   4205:                     next if ($key =~ /^error: 2 /);
                   4206:                     my $result = &thaw_unescape($value);
                   4207:                     if (ref($result) eq 'HASH') {
                   4208:                         $returnhash{$key}=$result;
                   4209:                     } else {
1.921     raeburn  4210:                         my @responses = split(/:/,$value);
                   4211:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4212:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4213:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4214:                         }
1.1008    raeburn  4215:                     }
1.353     www      4216:                 }
                   4217:             }
                   4218:         }
                   4219:     }
                   4220:     return %returnhash;
                   4221: }
                   4222: 
1.1055    raeburn  4223: sub courselastaccess {
                   4224:     my ($cdom,$cnum,$hostidref) = @_;
                   4225:     my %returnhash;
                   4226:     if ($cdom && $cnum) {
                   4227:         my $chome = &homeserver($cnum,$cdom);
                   4228:         if ($chome ne 'no_host') {
                   4229:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4230:             &extract_lastaccess(\%returnhash,$rep);
                   4231:         }
                   4232:     } else {
                   4233:         if (!$cdom) { $cdom=''; }
                   4234:         my %libserv = &all_library();
                   4235:         foreach my $tryserver (keys(%libserv)) {
                   4236:             if (ref($hostidref) eq 'ARRAY') {
                   4237:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4238:             } 
                   4239:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4240:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4241:                 &extract_lastaccess(\%returnhash,$rep);
                   4242:             }
                   4243:         }
                   4244:     }
                   4245:     return %returnhash;
                   4246: }
                   4247: 
                   4248: sub extract_lastaccess {
                   4249:     my ($returnhash,$rep) = @_;
                   4250:     if (ref($returnhash) eq 'HASH') {
                   4251:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4252:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4253:                  $rep eq '') {
                   4254:             my @pairs=split(/\&/,$rep);
                   4255:             foreach my $item (@pairs) {
                   4256:                 my ($key,$value)=split(/\=/,$item,2);
                   4257:                 $key = &unescape($key);
                   4258:                 next if ($key =~ /^error: 2 /);
                   4259:                 $returnhash->{$key} = &thaw_unescape($value);
                   4260:             }
                   4261:         }
                   4262:     }
                   4263:     return;
                   4264: }
                   4265: 
1.658     raeburn  4266: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4267: 
                   4268: sub dcmailput {
1.685     raeburn  4269:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4270:     my $status = &Apache::lonnet::critical(
1.740     www      4271:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4272:        &escape($message),$server);
1.662     raeburn  4273:     return $status;
                   4274: }
                   4275: 
1.658     raeburn  4276: sub dcmaildump {
                   4277:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4278:     my %returnhash=();
1.846     albertel 4279: 
                   4280:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4281:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4282:                                                          &escape($enddate).':';
                   4283: 	my @esc_senders=map { &escape($_)} @$senders;
                   4284: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4285: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4286:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4287:             if (($key) && ($value)) {
                   4288:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4289:             }
                   4290:         }
                   4291:     }
                   4292:     return %returnhash;
                   4293: }
1.662     raeburn  4294: # ---------------------------------------------------------- Domain roles
                   4295: 
                   4296: sub get_domain_roles {
                   4297:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4298:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4299:         $startdate = '.';
                   4300:     }
1.1018    raeburn  4301:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4302:         $enddate = '.';
                   4303:     }
1.922     raeburn  4304:     my $rolelist;
                   4305:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4306:         $rolelist = join('&',@{$roles});
1.922     raeburn  4307:     }
1.662     raeburn  4308:     my %personnel = ();
1.841     albertel 4309: 
                   4310:     my %servers = &get_servers($dom,'library');
                   4311:     foreach my $tryserver (keys(%servers)) {
                   4312: 	%{$personnel{$tryserver}}=();
                   4313: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4314: 					    &escape($startdate).':'.
                   4315: 					    &escape($enddate).':'.
                   4316: 					    &escape($rolelist), $tryserver))) {
                   4317: 	    my ($key,$value) = split(/\=/,$line,2);
                   4318: 	    if (($key) && ($value)) {
                   4319: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4320: 	    }
                   4321: 	}
1.662     raeburn  4322:     }
                   4323:     return %personnel;
                   4324: }
1.658     raeburn  4325: 
1.1057    www      4326: # ----------------------------------------------------------- Interval timing 
1.149     www      4327: 
1.1153    www      4328: {
                   4329: # Caches needed for speedup of navmaps
                   4330: # We don't want to cache this for very long at all (5 seconds at most)
                   4331: # 
                   4332: # The user for whom we cache
                   4333: my $cachedkey='';
                   4334: # The cached times for this user
                   4335: my %cachedtimes=();
                   4336: # When this was last done
                   4337: my $cachedtime=();
                   4338: 
                   4339: sub load_all_first_access {
1.1154    raeburn  4340:     my ($uname,$udom)=@_;
1.1156    www      4341:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4342:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4343:         return;
                   4344:     }
                   4345:     $cachedtime=time;
                   4346:     $cachedkey=$uname.':'.$udom;
                   4347:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4348: }
                   4349: 
1.504     albertel 4350: sub get_first_access {
1.1162    raeburn  4351:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4352:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4353:     if ($argsymb) { $symb=$argsymb; }
                   4354:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4355:     if ($argmap) { $map = $argmap; }
1.926     albertel 4356:     if ($type eq 'course') {
                   4357: 	$res='course';
                   4358:     } elsif ($type eq 'map') {
1.588     albertel 4359: 	$res=&symbread($map);
                   4360:     } else {
                   4361: 	$res=$symb;
                   4362:     }
1.1153    www      4363:     &load_all_first_access($uname,$udom);
                   4364:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4365: }
                   4366: 
                   4367: sub set_first_access {
1.1162    raeburn  4368:     my ($type,$interval)=@_;
1.790     albertel 4369:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4370:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4371:     if ($type eq 'course') {
                   4372: 	$res='course';
                   4373:     } elsif ($type eq 'map') {
1.588     albertel 4374: 	$res=&symbread($map);
                   4375:     } else {
                   4376: 	$res=$symb;
                   4377:     }
1.1153    www      4378:     $cachedkey='';
1.1162    raeburn  4379:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4380:     if (!$firstaccess) {
1.1162    raeburn  4381:         my $start = time;
                   4382: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4383:                           $udom,$uname);
                   4384:         if ($putres eq 'ok') {
                   4385:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4386:                  $udom,$uname); 
                   4387:             &appenv(
                   4388:                      {
                   4389:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4390:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4391:                      }
                   4392:                   );
                   4393:         }
                   4394:         return $putres;
1.505     albertel 4395:     }
                   4396:     return 'already_set';
1.504     albertel 4397: }
1.1153    www      4398: }
1.110     www      4399: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4400: 
                   4401: sub expirespread {
                   4402:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4403:     my $cid=$env{'request.course.id'}; 
1.110     www      4404:     if ($cid) {
                   4405:        my $now=time;
                   4406:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4407:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4408:                             $env{'course.'.$cid.'.num'}.
1.110     www      4409: 	        	    ':nohist_expirationdates:'.
                   4410:                             &escape($key).'='.$now,
1.620     albertel 4411:                             $env{'course.'.$cid.'.home'})
1.110     www      4412:     }
                   4413:     return 'ok';
1.14      www      4414: }
                   4415: 
1.109     www      4416: # ----------------------------------------------------- Devalidate Spreadsheets
                   4417: 
                   4418: sub devalidate {
1.325     www      4419:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4420:     my $cid=$env{'request.course.id'}; 
1.109     www      4421:     if ($cid) {
1.391     matthew  4422:         # delete the stored spreadsheets for
                   4423:         # - the student level sheet of this user in course's homespace
                   4424:         # - the assessment level sheet for this resource 
                   4425:         #   for this user in user's homespace
1.553     albertel 4426: 	# - current conditional state info
1.325     www      4427: 	my $key=$uname.':'.$udom.':';
1.109     www      4428:         my $status=
1.299     matthew  4429: 	    &del('nohist_calculatedsheets',
1.391     matthew  4430: 		 [$key.'studentcalc:'],
1.620     albertel 4431: 		 $env{'course.'.$cid.'.domain'},
                   4432: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4433: 		.' '.
                   4434: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4435: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4436:         unless ($status eq 'ok ok') {
                   4437:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4438:                     $uname.' at '.$udom.' for '.
1.109     www      4439: 		    $symb.': '.$status);
1.133     albertel 4440:         }
1.553     albertel 4441: 	&delenv('user.state.'.$cid);
1.109     www      4442:     }
                   4443: }
                   4444: 
1.265     albertel 4445: sub get_scalar {
                   4446:     my ($string,$end) = @_;
                   4447:     my $value;
                   4448:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4449: 	$value = $1;
                   4450:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4451: 	$value = $1;
                   4452:     }
                   4453:     return &unescape($value);
                   4454: }
                   4455: 
                   4456: sub array2str {
                   4457:   my (@array) = @_;
                   4458:   my $result=&arrayref2str(\@array);
                   4459:   $result=~s/^__ARRAY_REF__//;
                   4460:   $result=~s/__END_ARRAY_REF__$//;
                   4461:   return $result;
                   4462: }
                   4463: 
1.204     albertel 4464: sub arrayref2str {
                   4465:   my ($arrayref) = @_;
1.265     albertel 4466:   my $result='__ARRAY_REF__';
1.204     albertel 4467:   foreach my $elem (@$arrayref) {
1.265     albertel 4468:     if(ref($elem) eq 'ARRAY') {
                   4469:       $result.=&arrayref2str($elem).'&';
                   4470:     } elsif(ref($elem) eq 'HASH') {
                   4471:       $result.=&hashref2str($elem).'&';
                   4472:     } elsif(ref($elem)) {
                   4473:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4474:     } else {
                   4475:       $result.=&escape($elem).'&';
                   4476:     }
                   4477:   }
                   4478:   $result=~s/\&$//;
1.265     albertel 4479:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4480:   return $result;
                   4481: }
                   4482: 
1.168     albertel 4483: sub hash2str {
1.204     albertel 4484:   my (%hash) = @_;
                   4485:   my $result=&hashref2str(\%hash);
1.265     albertel 4486:   $result=~s/^__HASH_REF__//;
                   4487:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4488:   return $result;
                   4489: }
                   4490: 
                   4491: sub hashref2str {
                   4492:   my ($hashref)=@_;
1.265     albertel 4493:   my $result='__HASH_REF__';
1.800     albertel 4494:   foreach my $key (sort(keys(%$hashref))) {
                   4495:     if (ref($key) eq 'ARRAY') {
                   4496:       $result.=&arrayref2str($key).'=';
                   4497:     } elsif (ref($key) eq 'HASH') {
                   4498:       $result.=&hashref2str($key).'=';
                   4499:     } elsif (ref($key)) {
1.265     albertel 4500:       $result.='=';
1.800     albertel 4501:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4502:     } else {
1.1132    raeburn  4503: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4504:     }
                   4505: 
1.800     albertel 4506:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4507:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4508:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4509:       $result.=&hashref2str($hashref->{$key}).'&';
                   4510:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4511:        $result.='&';
1.800     albertel 4512:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4513:     } else {
1.800     albertel 4514:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4515:     }
                   4516:   }
1.168     albertel 4517:   $result=~s/\&$//;
1.265     albertel 4518:   $result .= '__END_HASH_REF__';
1.168     albertel 4519:   return $result;
                   4520: }
                   4521: 
                   4522: sub str2hash {
1.265     albertel 4523:     my ($string)=@_;
                   4524:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4525:     return %$hash;
                   4526: }
                   4527: 
                   4528: sub str2hashref {
1.168     albertel 4529:   my ($string) = @_;
1.265     albertel 4530: 
                   4531:   my %hash;
                   4532: 
                   4533:   if($string !~ /^__HASH_REF__/) {
                   4534:       if (! ($string eq '' || !defined($string))) {
                   4535: 	  $hash{'error'}='Not hash reference';
                   4536:       }
                   4537:       return (\%hash, $string);
                   4538:   }
                   4539: 
                   4540:   $string =~ s/^__HASH_REF__//;
                   4541: 
                   4542:   while($string !~ /^__END_HASH_REF__/) {
                   4543:       #key
                   4544:       my $key='';
                   4545:       if($string =~ /^__HASH_REF__/) {
                   4546:           ($key, $string)=&str2hashref($string);
                   4547:           if(defined($key->{'error'})) {
                   4548:               $hash{'error'}='Bad data';
                   4549:               return (\%hash, $string);
                   4550:           }
                   4551:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4552:           ($key, $string)=&str2arrayref($string);
                   4553:           if($key->[0] eq 'Array reference error') {
                   4554:               $hash{'error'}='Bad data';
                   4555:               return (\%hash, $string);
                   4556:           }
                   4557:       } else {
                   4558:           $string =~ s/^(.*?)=//;
1.267     albertel 4559: 	  $key=&unescape($1);
1.265     albertel 4560:       }
                   4561:       $string =~ s/^=//;
                   4562: 
                   4563:       #value
                   4564:       my $value='';
                   4565:       if($string =~ /^__HASH_REF__/) {
                   4566:           ($value, $string)=&str2hashref($string);
                   4567:           if(defined($value->{'error'})) {
                   4568:               $hash{'error'}='Bad data';
                   4569:               return (\%hash, $string);
                   4570:           }
                   4571:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4572:           ($value, $string)=&str2arrayref($string);
                   4573:           if($value->[0] eq 'Array reference error') {
                   4574:               $hash{'error'}='Bad data';
                   4575:               return (\%hash, $string);
                   4576:           }
                   4577:       } else {
                   4578: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4579:       }
                   4580:       $string =~ s/^&//;
                   4581: 
                   4582:       $hash{$key}=$value;
1.204     albertel 4583:   }
1.265     albertel 4584: 
                   4585:   $string =~ s/^__END_HASH_REF__//;
                   4586: 
                   4587:   return (\%hash, $string);
1.204     albertel 4588: }
                   4589: 
                   4590: sub str2array {
1.265     albertel 4591:     my ($string)=@_;
                   4592:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4593:     return @$array;
                   4594: }
                   4595: 
                   4596: sub str2arrayref {
1.204     albertel 4597:   my ($string) = @_;
1.265     albertel 4598:   my @array;
                   4599: 
                   4600:   if($string !~ /^__ARRAY_REF__/) {
                   4601:       if (! ($string eq '' || !defined($string))) {
                   4602: 	  $array[0]='Array reference error';
                   4603:       }
                   4604:       return (\@array, $string);
                   4605:   }
                   4606: 
                   4607:   $string =~ s/^__ARRAY_REF__//;
                   4608: 
                   4609:   while($string !~ /^__END_ARRAY_REF__/) {
                   4610:       my $value='';
                   4611:       if($string =~ /^__HASH_REF__/) {
                   4612:           ($value, $string)=&str2hashref($string);
                   4613:           if(defined($value->{'error'})) {
                   4614:               $array[0] ='Array reference error';
                   4615:               return (\@array, $string);
                   4616:           }
                   4617:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4618:           ($value, $string)=&str2arrayref($string);
                   4619:           if($value->[0] eq 'Array reference error') {
                   4620:               $array[0] ='Array reference error';
                   4621:               return (\@array, $string);
                   4622:           }
                   4623:       } else {
                   4624: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4625:       }
                   4626:       $string =~ s/^&//;
                   4627: 
                   4628:       push(@array, $value);
1.191     harris41 4629:   }
1.265     albertel 4630: 
                   4631:   $string =~ s/^__END_ARRAY_REF__//;
                   4632: 
                   4633:   return (\@array, $string);
1.168     albertel 4634: }
                   4635: 
1.167     albertel 4636: # -------------------------------------------------------------------Temp Store
                   4637: 
1.168     albertel 4638: sub tmpreset {
                   4639:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4640:   if (!$symb) {
                   4641:     $symb=&symbread();
1.620     albertel 4642:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4643:   }
                   4644:   $symb=escape($symb);
                   4645: 
1.620     albertel 4646:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4647:   $namespace=~s/\//\_/g;
                   4648:   $namespace=~s/\W//g;
                   4649: 
1.620     albertel 4650:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4651:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4652:   if ($domain eq 'public' && $stuname eq 'public') {
                   4653:       $stuname=$ENV{'REMOTE_ADDR'};
                   4654:   }
1.1117    foxr     4655:   my $path=LONCAPA::tempdir();
1.168     albertel 4656:   my %hash;
                   4657:   if (tie(%hash,'GDBM_File',
                   4658: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4659: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4660:     foreach my $key (keys(%hash)) {
1.180     albertel 4661:       if ($key=~ /:$symb/) {
1.168     albertel 4662: 	delete($hash{$key});
                   4663:       }
                   4664:     }
                   4665:   }
                   4666: }
                   4667: 
1.167     albertel 4668: sub tmpstore {
1.168     albertel 4669:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4670: 
                   4671:   if (!$symb) {
                   4672:     $symb=&symbread();
1.620     albertel 4673:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4674:   }
                   4675:   $symb=escape($symb);
                   4676: 
                   4677:   if (!$namespace) {
                   4678:     # I don't think we would ever want to store this for a course.
                   4679:     # it seems this will only be used if we don't have a course.
1.620     albertel 4680:     #$namespace=$env{'request.course.id'};
1.168     albertel 4681:     #if (!$namespace) {
1.620     albertel 4682:       $namespace=$env{'request.state'};
1.168     albertel 4683:     #}
                   4684:   }
                   4685:   $namespace=~s/\//\_/g;
                   4686:   $namespace=~s/\W//g;
1.620     albertel 4687:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4688:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4689:   if ($domain eq 'public' && $stuname eq 'public') {
                   4690:       $stuname=$ENV{'REMOTE_ADDR'};
                   4691:   }
1.168     albertel 4692:   my $now=time;
                   4693:   my %hash;
1.1117    foxr     4694:   my $path=LONCAPA::tempdir();
1.168     albertel 4695:   if (tie(%hash,'GDBM_File',
                   4696: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4697: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4698:     $hash{"version:$symb"}++;
                   4699:     my $version=$hash{"version:$symb"};
                   4700:     my $allkeys=''; 
                   4701:     foreach my $key (keys(%$storehash)) {
                   4702:       $allkeys.=$key.':';
1.591     albertel 4703:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4704:     }
                   4705:     $hash{"$version:$symb:timestamp"}=$now;
                   4706:     $allkeys.='timestamp';
                   4707:     $hash{"$version:keys:$symb"}=$allkeys;
                   4708:     if (untie(%hash)) {
                   4709:       return 'ok';
                   4710:     } else {
                   4711:       return "error:$!";
                   4712:     }
                   4713:   } else {
                   4714:     return "error:$!";
                   4715:   }
                   4716: }
1.167     albertel 4717: 
1.168     albertel 4718: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4719: 
1.168     albertel 4720: sub tmprestore {
                   4721:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4722: 
1.168     albertel 4723:   if (!$symb) {
                   4724:     $symb=&symbread();
1.620     albertel 4725:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4726:   }
                   4727:   $symb=escape($symb);
                   4728: 
1.620     albertel 4729:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4730: 
1.620     albertel 4731:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4732:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4733:   if ($domain eq 'public' && $stuname eq 'public') {
                   4734:       $stuname=$ENV{'REMOTE_ADDR'};
                   4735:   }
1.168     albertel 4736:   my %returnhash;
                   4737:   $namespace=~s/\//\_/g;
                   4738:   $namespace=~s/\W//g;
                   4739:   my %hash;
1.1117    foxr     4740:   my $path=LONCAPA::tempdir();
1.168     albertel 4741:   if (tie(%hash,'GDBM_File',
                   4742: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4743: 	  &GDBM_READER(),0640)) {
1.168     albertel 4744:     my $version=$hash{"version:$symb"};
                   4745:     $returnhash{'version'}=$version;
                   4746:     my $scope;
                   4747:     for ($scope=1;$scope<=$version;$scope++) {
                   4748:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4749:       my @keys=split(/:/,$vkeys);
                   4750:       my $key;
                   4751:       $returnhash{"$scope:keys"}=$vkeys;
                   4752:       foreach $key (@keys) {
1.591     albertel 4753: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4754: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4755:       }
                   4756:     }
1.168     albertel 4757:     if (!(untie(%hash))) {
                   4758:       return "error:$!";
                   4759:     }
                   4760:   } else {
                   4761:     return "error:$!";
                   4762:   }
                   4763:   return %returnhash;
1.167     albertel 4764: }
                   4765: 
1.9       www      4766: # ----------------------------------------------------------------------- Store
                   4767: 
                   4768: sub store {
1.124     www      4769:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4770:     my $home='';
                   4771: 
1.168     albertel 4772:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4773: 
1.213     www      4774:     $symb=&symbclean($symb);
1.122     albertel 4775:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4776: 
1.620     albertel 4777:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4778:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4779: 
                   4780:     &devalidate($symb,$stuname,$domain);
1.109     www      4781: 
                   4782:     $symb=escape($symb);
1.187     www      4783:     if (!$namespace) { 
1.620     albertel 4784:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4785:           return ''; 
                   4786:        } 
                   4787:     }
1.620     albertel 4788:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4789: 
                   4790:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4791:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4792: 
1.12      www      4793:     my $namevalue='';
1.800     albertel 4794:     foreach my $key (keys(%$storehash)) {
                   4795:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4796:     }
1.12      www      4797:     $namevalue=~s/\&$//;
1.187     www      4798:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4799:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4800: }
                   4801: 
1.47      www      4802: # -------------------------------------------------------------- Critical Store
                   4803: 
                   4804: sub cstore {
1.124     www      4805:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4806:     my $home='';
                   4807: 
1.168     albertel 4808:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4809: 
1.213     www      4810:     $symb=&symbclean($symb);
1.122     albertel 4811:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4812: 
1.620     albertel 4813:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4814:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4815: 
                   4816:     &devalidate($symb,$stuname,$domain);
1.109     www      4817: 
                   4818:     $symb=escape($symb);
1.187     www      4819:     if (!$namespace) { 
1.620     albertel 4820:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4821:           return ''; 
                   4822:        } 
                   4823:     }
1.620     albertel 4824:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4825: 
                   4826:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4827:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4828: 
1.47      www      4829:     my $namevalue='';
1.800     albertel 4830:     foreach my $key (keys(%$storehash)) {
                   4831:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4832:     }
1.47      www      4833:     $namevalue=~s/\&$//;
1.187     www      4834:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4835:     return critical
                   4836:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4837: }
                   4838: 
1.9       www      4839: # --------------------------------------------------------------------- Restore
                   4840: 
                   4841: sub restore {
1.124     www      4842:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4843:     my $home='';
                   4844: 
1.168     albertel 4845:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4846: 
1.122     albertel 4847:     if (!$symb) {
1.1224    raeburn  4848:         return if ($namespace eq 'courserequests');
                   4849:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4850:     } else {
1.1224    raeburn  4851:         unless ($namespace eq 'courserequests') {
                   4852:             $symb=&escape(&symbclean($symb));
                   4853:         }
1.122     albertel 4854:     }
1.188     www      4855:     if (!$namespace) { 
1.620     albertel 4856:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4857:           return ''; 
                   4858:        } 
                   4859:     }
1.620     albertel 4860:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4861:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4862:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4863:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4864: 
1.12      www      4865:     my %returnhash=();
1.800     albertel 4866:     foreach my $line (split(/\&/,$answer)) {
                   4867: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4868:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4869:     }
1.75      www      4870:     my $version;
                   4871:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4872:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4873:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4874:        }
1.75      www      4875:     }
1.13      www      4876:     return %returnhash;
1.34      www      4877: }
                   4878: 
                   4879: # ---------------------------------------------------------- Course Description
1.1118    foxr     4880: #
                   4881: #  
1.34      www      4882: 
                   4883: sub coursedescription {
1.731     albertel 4884:     my ($courseid,$args)=@_;
1.34      www      4885:     $courseid=~s/^\///;
1.49      www      4886:     $courseid=~s/\_/\//g;
1.34      www      4887:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4888:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4889:     my $normalid=$cdomain.'_'.$cnum;
                   4890:     # need to always cache even if we get errors otherwise we keep 
                   4891:     # trying and trying and trying to get the course description.
                   4892:     my %envhash=();
                   4893:     my %returnhash=();
1.731     albertel 4894:     
                   4895:     my $expiretime=600;
                   4896:     if ($env{'request.course.id'} eq $normalid) {
                   4897: 	$expiretime=120;
                   4898:     }
                   4899: 
                   4900:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4901:     if (!$args->{'freshen_cache'}
                   4902: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4903: 	foreach my $key (keys(%env)) {
                   4904: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4905: 	    my ($setting) = $1;
                   4906: 	    $returnhash{$setting} = $env{$key};
                   4907: 	}
                   4908: 	return %returnhash;
                   4909:     }
                   4910: 
1.1118    foxr     4911:     # get the data again
                   4912: 
1.731     albertel 4913:     if (!$args->{'one_time'}) {
                   4914: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4915:     }
1.811     albertel 4916: 
1.34      www      4917:     if ($chome ne 'no_host') {
1.302     albertel 4918:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4919:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4920: 	   my $username = $env{'user.name'}; # Defult username
                   4921: 	   if(defined $args->{'user'}) {
                   4922: 	       $username = $args->{'user'};
                   4923: 	   }
1.129     albertel 4924:            $returnhash{'home'}= $chome;
                   4925: 	   $returnhash{'domain'} = $cdomain;
                   4926: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4927:            if (!defined($returnhash{'type'})) {
                   4928:                $returnhash{'type'} = 'Course';
                   4929:            }
1.130     albertel 4930:            while (my ($name,$value) = each %returnhash) {
1.53      www      4931:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4932:            }
1.270     www      4933:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4934:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4935: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4936:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4937:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4938:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4939:        }
                   4940:     }
1.731     albertel 4941:     if (!$args->{'one_time'}) {
1.949     raeburn  4942: 	&appenv(\%envhash);
1.731     albertel 4943:     }
1.302     albertel 4944:     return %returnhash;
1.461     www      4945: }
                   4946: 
1.1080    raeburn  4947: sub update_released_required {
                   4948:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4949:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4950:         $cid = $env{'request.course.id'};
                   4951:         $cdom = $env{'course.'.$cid.'.domain'};
                   4952:         $cnum = $env{'course.'.$cid.'.num'};
                   4953:         $chome = $env{'course.'.$cid.'.home'};
                   4954:     }
                   4955:     if ($needsrelease) {
                   4956:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4957:         my $needsupdate;
                   4958:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4959:             $needsupdate = 1;
                   4960:         } else {
                   4961:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4962:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4963:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4964:                 $needsupdate = 1;
                   4965:             }
                   4966:         }
                   4967:         if ($needsupdate) {
                   4968:             my %needshash = (
                   4969:                              'internal.releaserequired' => $needsrelease,
                   4970:                             );
                   4971:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4972:             if ($putresult eq 'ok') {
                   4973:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4974:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4975:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4976:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4977:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4978:                 }
                   4979:             }
                   4980:         }
                   4981:     }
                   4982:     return;
                   4983: }
                   4984: 
1.461     www      4985: # -------------------------------------------------See if a user is privileged
                   4986: 
                   4987: sub privileged {
1.1219    raeburn  4988:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 4989:     my $now = time;
1.1219    raeburn  4990:     my $roles;
                   4991:     if (ref($possroles) eq 'ARRAY') {
                   4992:         $roles = $possroles; 
                   4993:     } else {
                   4994:         $roles = ['dc','su'];
                   4995:     }
                   4996:     if (ref($possdomains) eq 'ARRAY') {
                   4997:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   4998:         foreach my $dom (@{$possdomains}) {
                   4999:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5000:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5001:                 foreach my $role (@{$roles}) {
                   5002:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5003:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5004:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5005:                             return 1 unless (($end && $end < $now) ||
                   5006:                                              ($start && $start > $now));
                   5007:                         }
                   5008:                     }
                   5009:                 }
                   5010:             }
                   5011:         }
                   5012:     } else {
                   5013:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5014:         my $now = time;
1.1170    droeschl 5015: 
1.1219    raeburn  5016:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5017:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5018:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5019:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5020:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5021:             }
1.1219    raeburn  5022:         }
                   5023:     }
                   5024:     return 0;
                   5025: }
1.1170    droeschl 5026: 
1.1219    raeburn  5027: sub privileged_by_domain {
                   5028:     my ($domains,$roles) = @_;
                   5029:     my %privileged = ();
                   5030:     my $cachetime = 60*60*24;
                   5031:     my $now = time;
                   5032:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5033:         return %privileged;
                   5034:     }
                   5035:     foreach my $dom (@{$domains}) {
                   5036:         next if (ref($privileged{$dom}) eq 'HASH');
                   5037:         my $needroles;
                   5038:         foreach my $role (@{$roles}) {
                   5039:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5040:             if (defined($cached)) {
                   5041:                 if (ref($result) eq 'HASH') {
                   5042:                     $privileged{$dom}{$role} = $result;
                   5043:                 }
                   5044:             } else {
                   5045:                 $needroles = 1;
                   5046:             }
                   5047:         }
                   5048:         if ($needroles) {
                   5049:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5050:             $privileged{$dom} = {};
                   5051:             foreach my $server (keys(%dompersonnel)) {
                   5052:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5053:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5054:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5055:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5056:                         next if ($end && $end < $now);
                   5057:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5058:                             $dompersonnel{$server}{$item};
                   5059:                     }
                   5060:                 }
                   5061:             }
                   5062:             if (ref($privileged{$dom}) eq 'HASH') {
                   5063:                 foreach my $role (@{$roles}) {
                   5064:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5065:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5066:                     } else {
                   5067:                         my %hash = ();
                   5068:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5069:                     }
                   5070:                 }
                   5071:             }
                   5072:         }
                   5073:     }
                   5074:     return %privileged;
1.9       www      5075: }
1.1       albertel 5076: 
1.103     harris41 5077: # -------------------------------------------------------- Get user privileges
1.11      www      5078: 
                   5079: sub rolesinit {
1.1169    droeschl 5080:     my ($domain, $username) = @_;
                   5081:     my %userroles = ('user.login.time' => time);
                   5082:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5083: 
                   5084:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5085:     # also, blocking can be triggered by an activating timer
                   5086:     # it's saved in the user's %env.
                   5087:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5088:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5089:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5090:         %timerintchk, %timerintenv);
                   5091: 
1.1162    raeburn  5092:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5093:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5094:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5095:     }
1.1169    droeschl 5096: 
1.1162    raeburn  5097:     foreach my $key (keys(%timerinterval)) {
                   5098:         my ($cid,$rest) = split(/\0/,$key);
                   5099:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5100:     }
1.1169    droeschl 5101: 
1.11      www      5102:     my %allroles=();
1.1162    raeburn  5103:     my %allgroups=();
1.11      www      5104: 
1.1169    droeschl 5105:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5106:         my $role = $rolesdump{$area};
                   5107:         $area =~ s/\_\w\w$//;
                   5108: 
                   5109:         my ($trole, $tend, $tstart, $group_privs);
                   5110: 
                   5111:         if ($role =~ /^cr/) {
                   5112:         # Custom role, defined by a user 
                   5113:         # e.g., user.role.cr/msu/smith/mynewrole
                   5114:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5115:                 $trole = $1;
                   5116:                 ($tend, $tstart) = split('_', $2);
                   5117:             } else {
                   5118:                 $trole = $role;
                   5119:             }
                   5120:         } elsif ($role =~ m|^gr/|) {
                   5121:         # Role of member in a group, defined within a course/community
                   5122:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5123:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5124:             next if $tstart eq '-1';
                   5125:             ($trole, $group_privs) = split(/\//, $trole);
                   5126:             $group_privs = &unescape($group_privs);
                   5127:         } else {
                   5128:         # Just a normal role, defined in roles.tab
                   5129:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5130:         }
                   5131: 
                   5132:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5133:                  $username);
                   5134:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5135: 
                   5136:         # role expired or not available yet?
                   5137:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5138:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5139: 
                   5140:         next if $area eq '' or $trole eq '';
                   5141: 
                   5142:         my $spec = "$trole.$area";
                   5143:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5144: 
                   5145:         if ($trole =~ /^cr\//) {
                   5146:         # Custom role, defined by a user
                   5147:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5148:         } elsif ($trole eq 'gr') {
                   5149:         # Role of a member in a group, defined within a course/community
                   5150:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5151:             next;
                   5152:         } else {
                   5153:         # Normal role, defined in roles.tab
                   5154:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5155:         }
                   5156: 
                   5157:         my $cid = $tdomain.'_'.$trest;
                   5158:         unless ($firstaccchk{$cid}) {
                   5159:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5160:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5161:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5162:                         $coursetimerstarts{$cid}{$item}; 
                   5163:                 }
                   5164:             }
                   5165:             $firstaccchk{$cid} = 1;
                   5166:         }
                   5167:         unless ($timerintchk{$cid}) {
                   5168:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5169:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5170:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5171:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5172:                 }
1.12      www      5173:             }
1.1169    droeschl 5174:             $timerintchk{$cid} = 1;
1.191     harris41 5175:         }
1.11      www      5176:     }
1.1169    droeschl 5177: 
                   5178:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5179:         \%allroles, \%allgroups);
                   5180:     $env{'user.adv'} = $userroles{'user.adv'};
                   5181: 
1.1162    raeburn  5182:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5183: }
                   5184: 
1.567     raeburn  5185: sub set_arearole {
1.1215    raeburn  5186:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5187:     unless ($nolog) {
1.567     raeburn  5188: # log the associated role with the area
1.1215    raeburn  5189:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5190:     }
1.743     albertel 5191:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5192: }
                   5193: 
                   5194: sub custom_roleprivs {
                   5195:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5196:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5197:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5198:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5199:         my ($rdummy,$roledef)=
                   5200:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5201:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5202:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5203:             if (defined($syspriv)) {
1.1043    raeburn  5204:                 if ($trest =~ /^$match_community$/) {
                   5205:                     $syspriv =~ s/bre\&S//; 
                   5206:                 }
1.567     raeburn  5207:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5208:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5209:             }
                   5210:             if ($tdomain ne '') {
                   5211:                 if (defined($dompriv)) {
                   5212:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5213:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5214:                 }
                   5215:                 if (($trest ne '') && (defined($coursepriv))) {
                   5216:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5217:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5218:                 }
                   5219:             }
                   5220:         }
                   5221:     }
                   5222: }
                   5223: 
1.678     raeburn  5224: sub group_roleprivs {
                   5225:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5226:     my $access = 1;
                   5227:     my $now = time;
                   5228:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5229:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5230:     if ($access) {
1.811     albertel 5231:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5232:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5233:     }
                   5234: }
1.567     raeburn  5235: 
                   5236: sub standard_roleprivs {
                   5237:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5238:     if (defined($pr{$trole.':s'})) {
                   5239:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5240:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5241:     }
                   5242:     if ($tdomain ne '') {
                   5243:         if (defined($pr{$trole.':d'})) {
                   5244:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5245:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5246:         }
                   5247:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5248:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5249:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5250:         }
                   5251:     }
                   5252: }
                   5253: 
                   5254: sub set_userprivs {
1.1064    raeburn  5255:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5256:     my $author=0;
                   5257:     my $adv=0;
1.678     raeburn  5258:     my %grouproles = ();
                   5259:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5260:         my @groupkeys; 
1.1000    raeburn  5261:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5262:             push(@groupkeys,$role);
                   5263:         }
                   5264:         if (ref($groups_roles) eq 'HASH') {
                   5265:             foreach my $key (keys(%{$groups_roles})) {
                   5266:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5267:                     push(@groupkeys,$key);
                   5268:                 }
                   5269:             }
                   5270:         }
                   5271:         if (@groupkeys > 0) {
                   5272:             foreach my $role (@groupkeys) {
                   5273:                 my ($trole,$area,$sec,$extendedarea);
                   5274:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5275:                     $trole = $1;
                   5276:                     $area = $2;
                   5277:                     $sec = $3;
                   5278:                     $extendedarea = $area.$sec;
                   5279:                     if (exists($$allgroups{$area})) {
                   5280:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5281:                             my $spec = $trole.'.'.$extendedarea;
                   5282:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5283:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5284:                         }
1.678     raeburn  5285:                     }
                   5286:                 }
                   5287:             }
                   5288:         }
                   5289:     }
1.800     albertel 5290:     foreach my $group (keys(%grouproles)) {
                   5291:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5292:     }
1.800     albertel 5293:     foreach my $role (keys(%{$allroles})) {
                   5294:         my %thesepriv;
1.941     raeburn  5295:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5296:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5297:             if ($item ne '') {
                   5298:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5299:                 if ($restrictions eq '') {
                   5300:                     $thesepriv{$privilege}='F';
                   5301:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5302:                     $thesepriv{$privilege}.=$restrictions;
                   5303:                 }
                   5304:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5305:             }
                   5306:         }
                   5307:         my $thesestr='';
1.1104    raeburn  5308:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5309: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5310: 	}
                   5311:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5312:     }
                   5313:     return ($author,$adv);
                   5314: }
                   5315: 
1.994     raeburn  5316: sub role_status {
1.1104    raeburn  5317:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5318:     my @pwhere = ();
                   5319:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5320:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5321:         unless (!defined($$role) || $$role eq '') {
                   5322:             $$where=join('.',@pwhere);
                   5323:             $$trolecode=$$role.'.'.$$where;
                   5324:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5325:             $$tstatus='is';
1.1104    raeburn  5326:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5327:                 $$tstatus='future';
1.1034    raeburn  5328:                 if ($$tstart<$now) {
                   5329:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5330:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5331:                             my (%allroles,%allgroups,$group_privs,
                   5332:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5333:                             my %userroles = (
                   5334:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5335:                             );
1.1064    raeburn  5336:                             @rolecodes = ('cm'); 
1.1002    raeburn  5337:                             my $spec=$$role.'.'.$$where;
                   5338:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5339:                             if ($$role =~ /^cr\//) {
                   5340:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5341:                                 push(@rolecodes,'cr');
1.1002    raeburn  5342:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5343:                                 push(@rolecodes,$$role);
1.1002    raeburn  5344:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5345:                                                     $env{'user.name'});
1.1064    raeburn  5346:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5347:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5348:                                 $group_privs = &unescape($group_privs);
                   5349:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5350:                                 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  5351:                                 &get_groups_roles($tdomain,$trest,
                   5352:                                                   \%course_roles,\@rolecodes,
                   5353:                                                   \%groups_roles);
1.1002    raeburn  5354:                             } else {
1.1064    raeburn  5355:                                 push(@rolecodes,$$role);
1.1002    raeburn  5356:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5357:                             }
1.1064    raeburn  5358:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5359:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5360:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5361:                         }
                   5362:                     }
1.1034    raeburn  5363:                     $$tstatus = 'is';
1.1002    raeburn  5364:                 }
1.994     raeburn  5365:             }
                   5366:             if ($$tend) {
1.1104    raeburn  5367:                 if ($$tend<$update) {
1.994     raeburn  5368:                     $$tstatus='expired';
                   5369:                 } elsif ($$tend<$now) {
                   5370:                     $$tstatus='will_not';
                   5371:                 }
                   5372:             }
                   5373:         }
                   5374:     }
                   5375: }
                   5376: 
1.1104    raeburn  5377: sub get_groups_roles {
                   5378:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5379:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5380:                   (ref($rolecodes) eq 'ARRAY') && 
                   5381:                   (ref($groups_roles) eq 'HASH')); 
                   5382:     if (keys(%{$cdom_courseroles}) > 0) {
                   5383:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5384:         if ($cdom ne '' && $cnum ne '') {
                   5385:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5386:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5387:                     my $crsrole = $1;
                   5388:                     my $crssec = $2;
                   5389:                     if ($crsrole =~ /^cr/) {
                   5390:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5391:                             push(@{$rolecodes},'cr');
                   5392:                         }
                   5393:                     } else {
                   5394:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5395:                             push(@{$rolecodes},$crsrole);
                   5396:                         }
                   5397:                     }
                   5398:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5399:                     if ($crssec ne '') {
                   5400:                         $rolekey .= "/$crssec";
                   5401:                     }
                   5402:                     $rolekey .= './';
                   5403:                     $groups_roles->{$rolekey} = $rolecodes;
                   5404:                 }
                   5405:             }
                   5406:         }
                   5407:     }
                   5408:     return;
                   5409: }
                   5410: 
                   5411: sub delete_env_groupprivs {
                   5412:     my ($where,$courseroles,$possroles) = @_;
                   5413:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5414:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5415:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5416:         %{$courseroles->{$udom}} =
                   5417:             &get_my_roles('','','userroles',['active'],
                   5418:                           $possroles,[$udom],1);
                   5419:     }
                   5420:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5421:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5422:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5423:             my $area = '/'.$cdom.'/'.$cnum;
                   5424:             my $privkey = "user.priv.$crsrole.$area";
                   5425:             if ($crssec ne '') {
                   5426:                 $privkey .= '/'.$crssec;
                   5427:             }
                   5428:             $privkey .= ".$area/$group";
                   5429:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5430:         }
                   5431:     }
                   5432:     return;
                   5433: }
                   5434: 
1.994     raeburn  5435: sub check_adhoc_privs {
1.1104    raeburn  5436:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5437:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5438:     my $setprivs;
1.994     raeburn  5439:     if ($env{$cckey}) {
                   5440:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5441:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5442:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5443:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5444:             $setprivs = 1;
1.994     raeburn  5445:         }
                   5446:     } else {
1.1088    raeburn  5447:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5448:         $setprivs = 1;
1.994     raeburn  5449:     }
1.1185    raeburn  5450:     return $setprivs;
1.994     raeburn  5451: }
                   5452: 
                   5453: sub set_adhoc_privileges {
                   5454: # role can be cc or ca
1.1088    raeburn  5455:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5456:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5457:     my $spec = $role.'.'.$area;
                   5458:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5459:                                   $env{'user.name'},1);
1.994     raeburn  5460:     my %ccrole = ();
                   5461:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5462:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5463:     &appenv(\%userroles,[$role,'cm']);
                   5464:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5465:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5466:         &appenv( {'request.role'        => $spec,
                   5467:                   'request.role.domain' => $dcdom,
                   5468:                   'request.course.sec'  => ''
                   5469:                  }
                   5470:                );
                   5471:         my $tadv=0;
                   5472:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5473:         &appenv({'request.role.adv'    => $tadv});
                   5474:     }
1.994     raeburn  5475: }
                   5476: 
1.12      www      5477: # --------------------------------------------------------------- get interface
                   5478: 
                   5479: sub get {
1.131     albertel 5480:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5481:    my $items='';
1.800     albertel 5482:    foreach my $item (@$storearr) {
                   5483:        $items.=&escape($item).'&';
1.191     harris41 5484:    }
1.12      www      5485:    $items=~s/\&$//;
1.620     albertel 5486:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5487:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5488:    my $uhome=&homeserver($uname,$udomain);
                   5489: 
1.133     albertel 5490:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5491:    my @pairs=split(/\&/,$rep);
1.273     albertel 5492:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5493:      return @pairs;
                   5494:    }
1.15      www      5495:    my %returnhash=();
1.42      www      5496:    my $i=0;
1.800     albertel 5497:    foreach my $item (@$storearr) {
                   5498:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5499:       $i++;
1.191     harris41 5500:    }
1.15      www      5501:    return %returnhash;
1.27      www      5502: }
                   5503: 
                   5504: # --------------------------------------------------------------- del interface
                   5505: 
                   5506: sub del {
1.133     albertel 5507:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5508:    my $items='';
1.800     albertel 5509:    foreach my $item (@$storearr) {
                   5510:        $items.=&escape($item).'&';
1.191     harris41 5511:    }
1.984     neumanie 5512: 
1.27      www      5513:    $items=~s/\&$//;
1.620     albertel 5514:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5515:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5516:    my $uhome=&homeserver($uname,$udomain);
                   5517:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5518: }
                   5519: 
                   5520: # -------------------------------------------------------------- dump interface
                   5521: 
1.1180    droeschl 5522: sub unserialize {
                   5523:     my ($rep, $escapedkeys) = @_;
                   5524: 
                   5525:     return {} if $rep =~ /^error/;
                   5526: 
                   5527:     my %returnhash=();
                   5528: 	foreach my $item (split /\&/, $rep) {
                   5529: 	    my ($key, $value) = split(/=/, $item, 2);
                   5530: 	    $key = unescape($key) unless $escapedkeys;
                   5531: 	    next if $key =~ /^error: 2 /;
                   5532: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5533: 	}
                   5534:     #return %returnhash;
                   5535:     return \%returnhash;
                   5536: }        
                   5537: 
                   5538: # see Lond::dump_with_regexp
                   5539: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5540: sub dump {
1.1180    droeschl 5541:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5542:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5543:     if (!$uname) { $uname=$env{'user.name'}; }
                   5544:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5545: 
1.1180    droeschl 5546:     my $reply;
                   5547:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5548:         # user is hosted on this machine
                   5549:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5550:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5551:         return %{unserialize($reply, $escapedkeys)};
                   5552:     }
1.755     albertel 5553:     if ($regexp) {
                   5554: 	$regexp=&escape($regexp);
                   5555:     } else {
                   5556: 	$regexp='.';
                   5557:     }
1.1166    raeburn  5558:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5559:     my @pairs=split(/\&/,$rep);
                   5560:     my %returnhash=();
1.1098    foxr     5561:     if (!($rep =~ /^error/ )) {
                   5562: 	foreach my $item (@pairs) {
                   5563: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5564:         $key = unescape($key) unless $escapedkeys;
                   5565:         #$key = &unescape($key);
1.1098    foxr     5566: 	    next if ($key =~ /^error: 2 /);
                   5567: 	    $returnhash{$key}=&thaw_unescape($value);
                   5568: 	}
1.755     albertel 5569:     }
                   5570:     return %returnhash;
1.407     www      5571: }
                   5572: 
1.1098    foxr     5573: 
1.717     albertel 5574: # --------------------------------------------------------- dumpstore interface
                   5575: 
                   5576: sub dumpstore {
                   5577:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5578:    # same as dump but keys must be escaped. They may contain colon separated
                   5579:    # lists of values that may themself contain colons (e.g. symbs).
                   5580:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5581: }
                   5582: 
1.407     www      5583: # -------------------------------------------------------------- keys interface
                   5584: 
                   5585: sub getkeys {
                   5586:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5587:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5588:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5589:    my $uhome=&homeserver($uname,$udomain);
                   5590:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5591:    my @keyarray=();
1.800     albertel 5592:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5593:       next if ($key =~ /^error: 2 /);
1.800     albertel 5594:       push(@keyarray,&unescape($key));
1.407     www      5595:    }
                   5596:    return @keyarray;
1.318     matthew  5597: }
                   5598: 
1.319     matthew  5599: # --------------------------------------------------------------- currentdump
                   5600: sub currentdump {
1.328     matthew  5601:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5602:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5603:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5604:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5605:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5606:    my $rep;
                   5607: 
                   5608:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5609:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5610:                    $courseid)));
                   5611:    } else {
                   5612:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5613:    }
                   5614: 
1.318     matthew  5615:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5616:    #
1.318     matthew  5617:    my %returnhash=();
1.319     matthew  5618:    #
                   5619:    if ($rep eq "unknown_cmd") { 
                   5620:        # an old lond will not know currentdump
                   5621:        # Do a dump and make it look like a currentdump
1.822     albertel 5622:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5623:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5624:        my %hash = @tmp;
                   5625:        @tmp=();
1.424     matthew  5626:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5627:    } else {
                   5628:        my @pairs=split(/\&/,$rep);
1.800     albertel 5629:        foreach my $pair (@pairs) {
                   5630:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5631:            my ($symb,$param) = split(/:/,$key);
                   5632:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5633:                                                         &thaw_unescape($value);
1.319     matthew  5634:        }
1.191     harris41 5635:    }
1.12      www      5636:    return %returnhash;
1.424     matthew  5637: }
                   5638: 
                   5639: sub convert_dump_to_currentdump{
                   5640:     my %hash = %{shift()};
                   5641:     my %returnhash;
                   5642:     # Code ripped from lond, essentially.  The only difference
                   5643:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5644:     # we might run in to problems with parameter names =~ /^v\./
                   5645:     while (my ($key,$value) = each(%hash)) {
                   5646:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5647: 	$symb  = &unescape($symb);
                   5648: 	$param = &unescape($param);
1.424     matthew  5649:         next if ($v eq 'version' || $symb eq 'keys');
                   5650:         next if (exists($returnhash{$symb}) &&
                   5651:                  exists($returnhash{$symb}->{$param}) &&
                   5652:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5653:         $returnhash{$symb}->{$param}=$value;
                   5654:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5655:     }
                   5656:     #
                   5657:     # Remove all of the keys in the hashes which keep track of
                   5658:     # the version of the parameter.
                   5659:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5660:         # use a foreach because we are going to delete from the hash.
                   5661:         foreach my $key (keys(%$param_hash)) {
                   5662:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5663:         }
                   5664:     }
                   5665:     return \%returnhash;
1.12      www      5666: }
                   5667: 
1.627     albertel 5668: # ------------------------------------------------------ critical inc interface
                   5669: 
                   5670: sub cinc {
                   5671:     return &inc(@_,'critical');
                   5672: }
                   5673: 
1.449     matthew  5674: # --------------------------------------------------------------- inc interface
                   5675: 
                   5676: sub inc {
1.627     albertel 5677:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5678:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5679:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5680:     my $uhome=&homeserver($uname,$udomain);
                   5681:     my $items='';
                   5682:     if (! ref($store)) {
                   5683:         # got a single value, so use that instead
                   5684:         $items = &escape($store).'=&';
                   5685:     } elsif (ref($store) eq 'SCALAR') {
                   5686:         $items = &escape($$store).'=&';        
                   5687:     } elsif (ref($store) eq 'ARRAY') {
                   5688:         $items = join('=&',map {&escape($_);} @{$store});
                   5689:     } elsif (ref($store) eq 'HASH') {
                   5690:         while (my($key,$value) = each(%{$store})) {
                   5691:             $items.= &escape($key).'='.&escape($value).'&';
                   5692:         }
                   5693:     }
                   5694:     $items=~s/\&$//;
1.627     albertel 5695:     if ($critical) {
                   5696: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5697:     } else {
                   5698: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5699:     }
1.449     matthew  5700: }
                   5701: 
1.12      www      5702: # --------------------------------------------------------------- put interface
                   5703: 
                   5704: sub put {
1.134     albertel 5705:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5706:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5707:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5708:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5709:    my $items='';
1.800     albertel 5710:    foreach my $item (keys(%$storehash)) {
                   5711:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5712:    }
1.12      www      5713:    $items=~s/\&$//;
1.134     albertel 5714:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5715: }
                   5716: 
1.631     albertel 5717: # ------------------------------------------------------------ newput interface
                   5718: 
                   5719: sub newput {
                   5720:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5721:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5722:    if (!$uname) { $uname=$env{'user.name'}; }
                   5723:    my $uhome=&homeserver($uname,$udomain);
                   5724:    my $items='';
                   5725:    foreach my $key (keys(%$storehash)) {
                   5726:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5727:    }
                   5728:    $items=~s/\&$//;
                   5729:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5730: }
                   5731: 
                   5732: # ---------------------------------------------------------  putstore interface
                   5733: 
1.524     raeburn  5734: sub putstore {
1.715     albertel 5735:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5736:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5737:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5738:    my $uhome=&homeserver($uname,$udomain);
                   5739:    my $items='';
1.715     albertel 5740:    foreach my $key (keys(%$storehash)) {
                   5741:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5742:    }
1.715     albertel 5743:    $items=~s/\&$//;
1.716     albertel 5744:    my $esc_symb=&escape($symb);
                   5745:    my $esc_v=&escape($version);
1.715     albertel 5746:    my $reply =
1.716     albertel 5747:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5748: 	      $uhome);
                   5749:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5750:        # gfall back to way things use to be done
1.715     albertel 5751:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5752: 			    $uname);
1.524     raeburn  5753:    }
1.715     albertel 5754:    return $reply;
                   5755: }
                   5756: 
                   5757: sub old_putstore {
1.716     albertel 5758:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5759:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5760:     if (!$uname) { $uname=$env{'user.name'}; }
                   5761:     my $uhome=&homeserver($uname,$udomain);
                   5762:     my %newstorehash;
1.800     albertel 5763:     foreach my $item (keys(%$storehash)) {
                   5764: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5765: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5766:     }
                   5767:     my $items='';
                   5768:     my %allitems = ();
1.800     albertel 5769:     foreach my $item (keys(%newstorehash)) {
                   5770: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5771: 	    my $key = $1.':keys:'.$2;
                   5772: 	    $allitems{$key} .= $3.':';
                   5773: 	}
1.800     albertel 5774: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5775:     }
1.800     albertel 5776:     foreach my $item (keys(%allitems)) {
                   5777: 	$allitems{$item} =~ s/\:$//;
                   5778: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5779:     }
                   5780:     $items=~s/\&$//;
                   5781:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5782: }
                   5783: 
1.47      www      5784: # ------------------------------------------------------ critical put interface
                   5785: 
                   5786: sub cput {
1.134     albertel 5787:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5789:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5790:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5791:    my $items='';
1.800     albertel 5792:    foreach my $item (keys(%$storehash)) {
                   5793:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5794:    }
1.47      www      5795:    $items=~s/\&$//;
1.134     albertel 5796:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5797: }
                   5798: 
                   5799: # -------------------------------------------------------------- eget interface
                   5800: 
                   5801: sub eget {
1.133     albertel 5802:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5803:    my $items='';
1.800     albertel 5804:    foreach my $item (@$storearr) {
                   5805:        $items.=&escape($item).'&';
1.191     harris41 5806:    }
1.12      www      5807:    $items=~s/\&$//;
1.620     albertel 5808:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5809:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5810:    my $uhome=&homeserver($uname,$udomain);
                   5811:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5812:    my @pairs=split(/\&/,$rep);
                   5813:    my %returnhash=();
1.42      www      5814:    my $i=0;
1.800     albertel 5815:    foreach my $item (@$storearr) {
                   5816:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5817:       $i++;
1.191     harris41 5818:    }
1.12      www      5819:    return %returnhash;
                   5820: }
                   5821: 
1.667     albertel 5822: # ------------------------------------------------------------ tmpput interface
                   5823: sub tmpput {
1.802     raeburn  5824:     my ($storehash,$server,$context)=@_;
1.667     albertel 5825:     my $items='';
1.800     albertel 5826:     foreach my $item (keys(%$storehash)) {
                   5827: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5828:     }
                   5829:     $items=~s/\&$//;
1.802     raeburn  5830:     if (defined($context)) {
                   5831:         $items .= ':'.&escape($context);
                   5832:     }
1.667     albertel 5833:     return &reply("tmpput:$items",$server);
                   5834: }
                   5835: 
                   5836: # ------------------------------------------------------------ tmpget interface
                   5837: sub tmpget {
1.688     albertel 5838:     my ($token,$server)=@_;
                   5839:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5840:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5841:     my %returnhash;
                   5842:     foreach my $item (split(/\&/,$rep)) {
                   5843: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5844:         next if ($key =~ /^error: 2 /);
1.667     albertel 5845: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5846:     }
                   5847:     return %returnhash;
                   5848: }
                   5849: 
1.1113    raeburn  5850: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5851: sub tmpdel {
                   5852:     my ($token,$server)=@_;
                   5853:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5854:     return &reply("tmpdel:$token",$server);
                   5855: }
                   5856: 
1.1198    raeburn  5857: # ------------------------------------------------------------ get_timebased_id 
                   5858: 
                   5859: sub get_timebased_id {
                   5860:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5861:         $maxtries) = @_;
                   5862:     my ($newid,$error,$dellock);
                   5863:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5864:         return ('','ok','invalid call to get suffix');
                   5865:     }
                   5866: 
                   5867: # set defaults for any optional args for which values were not supplied
                   5868:     if ($who eq '') {
                   5869:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5870:     }
                   5871:     if (!$locktries) {
                   5872:         $locktries = 3;
                   5873:     }
                   5874:     if (!$maxtries) {
                   5875:         $maxtries = 10;
                   5876:     }
                   5877:     
                   5878:     if (($cdom eq '') || ($cnum eq '')) {
                   5879:         if ($env{'request.course.id'}) {
                   5880:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5881:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5882:         }
                   5883:         if (($cdom eq '') || ($cnum eq '')) {
                   5884:             return ('','ok','call to get suffix not in course context');
                   5885:         }
                   5886:     }
                   5887: 
                   5888: # construct locking item
                   5889:     my $lockhash = {
                   5890:                       $prefix."\0".'locked_'.$keyid => $who,
                   5891:                    };
                   5892:     my $tries = 0;
                   5893: 
                   5894: # attempt to get lock on nohist_$namespace file
                   5895:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5896:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5897:         $tries ++;
                   5898:         sleep 1;
                   5899:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5900:     }
                   5901: 
                   5902: # attempt to get unique identifier, based on current timestamp
                   5903:     if ($gotlock eq 'ok') {
                   5904:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5905:         my $id = time;
                   5906:         $newid = $id;
                   5907:         my $idtries = 0;
                   5908:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5909:             if ($idtype eq 'concat') {
                   5910:                 $newid = $id.$idtries;
                   5911:             } else {
                   5912:                 $newid ++;
                   5913:             }
                   5914:             $idtries ++;
                   5915:         }
                   5916:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5917:             my %new_item =  (
                   5918:                               $prefix."\0".$newid => $who,
                   5919:                             );
                   5920:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5921:                                                  $cdom,$cnum);
                   5922:             if ($putresult ne 'ok') {
                   5923:                 undef($newid);
                   5924:                 $error = 'error saving new item: '.$putresult;
                   5925:             }
                   5926:         } else {
                   5927:              $error = ('error: no unique suffix available for the new item ');
                   5928:         }
                   5929: #  remove lock
                   5930:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5931:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5932:     } else {
                   5933:         $error = "error: could not obtain lockfile\n";
                   5934:         $dellock = 'ok';
                   5935:     }
                   5936:     return ($newid,$dellock,$error);
                   5937: }
                   5938: 
1.765     albertel 5939: # -------------------------------------------------- portfolio access checking
                   5940: 
                   5941: sub portfolio_access {
1.766     albertel 5942:     my ($requrl) = @_;
1.765     albertel 5943:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5944:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5945:     if ($result) {
                   5946:         my %setters;
                   5947:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5948:             my ($startblock,$endblock) =
                   5949:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5950:             if ($startblock && $endblock) {
                   5951:                 return 'B';
                   5952:             }
                   5953:         } else {
                   5954:             my ($startblock,$endblock) =
                   5955:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5956:             if ($startblock && $endblock) {
                   5957:                 return 'B';
                   5958:             }
                   5959:         }
                   5960:     }
1.765     albertel 5961:     if ($result eq 'ok') {
1.766     albertel 5962:        return 'F';
1.765     albertel 5963:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5964:        return 'A';
1.765     albertel 5965:     }
1.766     albertel 5966:     return '';
1.765     albertel 5967: }
                   5968: 
                   5969: sub get_portfolio_access {
1.767     albertel 5970:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5971: 
                   5972:     if (!ref($access_hash)) {
                   5973: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5974: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5975: 						   $file_name);
                   5976: 	$access_hash = $access_controls{$file_name};
                   5977:     }
                   5978: 
1.765     albertel 5979:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5980:     my $now = time;
                   5981:     if (ref($access_hash) eq 'HASH') {
                   5982:         foreach my $key (keys(%{$access_hash})) {
                   5983:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5984:             if ($start > $now) {
                   5985:                 next;
                   5986:             }
                   5987:             if ($end && $end<$now) {
                   5988:                 next;
                   5989:             }
                   5990:             if ($scope eq 'public') {
                   5991:                 $public = $key;
                   5992:                 last;
                   5993:             } elsif ($scope eq 'guest') {
                   5994:                 $guest = $key;
                   5995:             } elsif ($scope eq 'domains') {
                   5996:                 push(@domains,$key);
                   5997:             } elsif ($scope eq 'users') {
                   5998:                 push(@users,$key);
                   5999:             } elsif ($scope eq 'course') {
                   6000:                 push(@courses,$key);
                   6001:             } elsif ($scope eq 'group') {
                   6002:                 push(@groups,$key);
                   6003:             }
                   6004:         }
                   6005:         if ($public) {
                   6006:             return 'ok';
                   6007:         }
                   6008:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6009:             if ($guest) {
                   6010:                 return $guest;
                   6011:             }
                   6012:         } else {
                   6013:             if (@domains > 0) {
                   6014:                 foreach my $domkey (@domains) {
                   6015:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6016:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6017:                             return 'ok';
                   6018:                         }
                   6019:                     }
                   6020:                 }
                   6021:             }
                   6022:             if (@users > 0) {
                   6023:                 foreach my $userkey (@users) {
1.865     raeburn  6024:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6025:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6026:                             if (ref($item) eq 'HASH') {
                   6027:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6028:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6029:                                     return 'ok';
                   6030:                                 }
                   6031:                             }
                   6032:                         }
                   6033:                     } 
1.765     albertel 6034:                 }
                   6035:             }
                   6036:             my %roleshash;
                   6037:             my @courses_and_groups = @courses;
                   6038:             push(@courses_and_groups,@groups); 
                   6039:             if (@courses_and_groups > 0) {
                   6040:                 my (%allgroups,%allroles); 
                   6041:                 my ($start,$end,$role,$sec,$group);
                   6042:                 foreach my $envkey (%env) {
1.1060    raeburn  6043:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6044:                         my $cid = $2.'_'.$3; 
                   6045:                         if ($1 eq 'gr') {
                   6046:                             $group = $4;
                   6047:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6048:                         } else {
                   6049:                             if ($4 eq '') {
                   6050:                                 $sec = 'none';
                   6051:                             } else {
                   6052:                                 $sec = $4;
                   6053:                             }
                   6054:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6055:                         }
1.811     albertel 6056:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6057:                         my $cid = $2.'_'.$3;
                   6058:                         if ($4 eq '') {
                   6059:                             $sec = 'none';
                   6060:                         } else {
                   6061:                             $sec = $4;
                   6062:                         }
                   6063:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6064:                     }
                   6065:                 }
                   6066:                 if (keys(%allroles) == 0) {
                   6067:                     return;
                   6068:                 }
                   6069:                 foreach my $key (@courses_and_groups) {
                   6070:                     my %content = %{$$access_hash{$key}};
                   6071:                     my $cnum = $content{'number'};
                   6072:                     my $cdom = $content{'domain'};
                   6073:                     my $cid = $cdom.'_'.$cnum;
                   6074:                     if (!exists($allroles{$cid})) {
                   6075:                         next;
                   6076:                     }    
                   6077:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6078:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6079:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6080:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6081:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6082:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6083:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6084:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6085:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6086:                                         if (grep/^all$/,@sections) {
                   6087:                                             return 'ok';
                   6088:                                         } else {
                   6089:                                             if (grep/^$sec$/,@sections) {
                   6090:                                                 return 'ok';
                   6091:                                             }
                   6092:                                         }
                   6093:                                     }
                   6094:                                 }
                   6095:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6096:                                     if (grep/^none$/,@groups) {
                   6097:                                         return 'ok';
                   6098:                                     }
                   6099:                                 } else {
                   6100:                                     if (grep/^all$/,@groups) {
                   6101:                                         return 'ok';
                   6102:                                     } 
                   6103:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6104:                                         if (grep/^$group$/,@groups) {
                   6105:                                             return 'ok';
                   6106:                                         }
                   6107:                                     }
                   6108:                                 } 
                   6109:                             }
                   6110:                         }
                   6111:                     }
                   6112:                 }
                   6113:             }
                   6114:             if ($guest) {
                   6115:                 return $guest;
                   6116:             }
                   6117:         }
                   6118:     }
                   6119:     return;
                   6120: }
                   6121: 
                   6122: sub course_group_datechecker {
                   6123:     my ($dates,$now,$status) = @_;
                   6124:     my ($start,$end) = split(/\./,$dates);
                   6125:     if (!$start && !$end) {
                   6126:         return 'ok';
                   6127:     }
                   6128:     if (grep/^active$/,@{$status}) {
                   6129:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6130:             return 'ok';
                   6131:         }
                   6132:     }
                   6133:     if (grep/^previous$/,@{$status}) {
                   6134:         if ($end > $now ) {
                   6135:             return 'ok';
                   6136:         }
                   6137:     }
                   6138:     if (grep/^future$/,@{$status}) {
                   6139:         if ($start > $now) {
                   6140:             return 'ok';
                   6141:         }
                   6142:     }
                   6143:     return; 
                   6144: }
                   6145: 
                   6146: sub parse_portfolio_url {
                   6147:     my ($url) = @_;
                   6148: 
                   6149:     my ($type,$udom,$unum,$group,$file_name);
                   6150:     
1.823     albertel 6151:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6152: 	$type = 1;
                   6153:         $udom = $1;
                   6154:         $unum = $2;
                   6155:         $file_name = $3;
1.823     albertel 6156:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6157: 	$type = 2;
                   6158:         $udom = $1;
                   6159:         $unum = $2;
                   6160:         $group = $3;
                   6161:         $file_name = $3.'/'.$4;
                   6162:     }
                   6163:     if (wantarray) {
                   6164: 	return ($type,$udom,$unum,$file_name,$group);
                   6165:     }
                   6166:     return $type;
                   6167: }
                   6168: 
                   6169: sub is_portfolio_url {
                   6170:     my ($url) = @_;
                   6171:     return scalar(&parse_portfolio_url($url));
                   6172: }
                   6173: 
1.798     raeburn  6174: sub is_portfolio_file {
                   6175:     my ($file) = @_;
1.820     raeburn  6176:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6177:         return 1;
                   6178:     }
                   6179:     return;
                   6180: }
                   6181: 
1.976     raeburn  6182: sub usertools_access {
1.1084    raeburn  6183:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6184:     my ($access,%tools);
                   6185:     if ($context eq '') {
                   6186:         $context = 'tools';
                   6187:     }
                   6188:     if ($context eq 'requestcourses') {
                   6189:         %tools = (
                   6190:                       official   => 1,
                   6191:                       unofficial => 1,
1.1006    raeburn  6192:                       community  => 1,
1.985     raeburn  6193:                  );
1.1183    raeburn  6194:     } elsif ($context eq 'requestauthor') {
                   6195:         %tools = (
                   6196:                       requestauthor => 1,
                   6197:                  );
1.985     raeburn  6198:     } else {
                   6199:         %tools = (
                   6200:                       aboutme   => 1,
                   6201:                       blog      => 1,
1.1177    raeburn  6202:                       webdav    => 1,
1.985     raeburn  6203:                       portfolio => 1,
                   6204:                  );
                   6205:     }
1.976     raeburn  6206:     return if (!defined($tools{$tool}));
                   6207: 
1.1242  ! raeburn  6208:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6209:         $udom = $env{'user.domain'};
                   6210:         $uname = $env{'user.name'};
                   6211:     }
                   6212: 
1.978     raeburn  6213:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6214:         if ($action ne 'reload') {
1.985     raeburn  6215:             if ($context eq 'requestcourses') {
                   6216:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6217:             } elsif ($context eq 'requestauthor') {
                   6218:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6219:             } else {
                   6220:                 return $env{'environment.availabletools.'.$tool};
                   6221:             }
                   6222:         }
1.976     raeburn  6223:     }
                   6224: 
1.1183    raeburn  6225:     my ($toolstatus,$inststatus,$envkey);
                   6226:     if ($context eq 'requestauthor') {
                   6227:         $envkey = $context; 
                   6228:     } else {
                   6229:         $envkey = $context.'.'.$tool;
                   6230:     }
1.976     raeburn  6231: 
1.985     raeburn  6232:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6233:          ($action ne 'reload')) {
1.1183    raeburn  6234:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6235:         $inststatus = $env{'environment.inststatus'};
                   6236:     } else {
1.1084    raeburn  6237:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6238:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6239:             $inststatus = $userenvref->{'inststatus'};
                   6240:         } else {
1.1183    raeburn  6241:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6242:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6243:             $inststatus = $userenv{'inststatus'};
                   6244:         }
1.976     raeburn  6245:     }
                   6246: 
                   6247:     if ($toolstatus ne '') {
                   6248:         if ($toolstatus) {
                   6249:             $access = 1;
                   6250:         } else {
                   6251:             $access = 0;
                   6252:         }
                   6253:         return $access;
                   6254:     }
                   6255: 
1.1084    raeburn  6256:     my ($is_adv,%domdef);
                   6257:     if (ref($is_advref) eq 'HASH') {
                   6258:         $is_adv = $is_advref->{'is_adv'};
                   6259:     } else {
                   6260:         $is_adv = &is_advanced_user($udom,$uname);
                   6261:     }
                   6262:     if (ref($domdefref) eq 'HASH') {
                   6263:         %domdef = %{$domdefref};
                   6264:     } else {
                   6265:         %domdef = &get_domain_defaults($udom);
                   6266:     }
1.976     raeburn  6267:     if (ref($domdef{$tool}) eq 'HASH') {
                   6268:         if ($is_adv) {
                   6269:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6270:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6271:                     $access = 1;
                   6272:                 } else {
                   6273:                     $access = 0;
                   6274:                 }
                   6275:                 return $access;
                   6276:             }
                   6277:         }
                   6278:         if ($inststatus ne '') {
                   6279:             my ($hasaccess,$hasnoaccess);
                   6280:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6281:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6282:                     if ($domdef{$tool}{$affiliation}) {
                   6283:                         $hasaccess = 1;
                   6284:                     } else {
                   6285:                         $hasnoaccess = 1;
                   6286:                     }
                   6287:                 }
                   6288:             }
                   6289:             if ($hasaccess || $hasnoaccess) {
                   6290:                 if ($hasaccess) {
                   6291:                     $access = 1;
                   6292:                 } elsif ($hasnoaccess) {
                   6293:                     $access = 0; 
                   6294:                 }
                   6295:                 return $access;
                   6296:             }
                   6297:         } else {
                   6298:             if ($domdef{$tool}{'default'} ne '') {
                   6299:                 if ($domdef{$tool}{'default'}) {
                   6300:                     $access = 1;
                   6301:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6302:                     $access = 0;
                   6303:                 }
                   6304:                 return $access;
                   6305:             }
                   6306:         }
                   6307:     } else {
1.1177    raeburn  6308:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6309:             $access = 1;
                   6310:         } else {
                   6311:             $access = 0;
                   6312:         }
1.976     raeburn  6313:         return $access;
                   6314:     }
                   6315: }
                   6316: 
1.1050    raeburn  6317: sub is_course_owner {
                   6318:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6319:     if (($udom eq '') || ($uname eq '')) {
                   6320:         $udom = $env{'user.domain'};
                   6321:         $uname = $env{'user.name'};
                   6322:     }
                   6323:     unless (($udom eq '') || ($uname eq '')) {
                   6324:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6325:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6326:                 return 1;
                   6327:             } else {
                   6328:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6329:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6330:                     return 1;
                   6331:                 }
                   6332:             }
                   6333:         }
                   6334:     }
                   6335:     return;
                   6336: }
                   6337: 
1.976     raeburn  6338: sub is_advanced_user {
                   6339:     my ($udom,$uname) = @_;
1.1085    raeburn  6340:     if ($udom ne '' && $uname ne '') {
                   6341:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6342:             if (wantarray) {
                   6343:                 return ($env{'user.adv'},$env{'user.author'});
                   6344:             } else {
                   6345:                 return $env{'user.adv'};
                   6346:             }
1.1085    raeburn  6347:         }
                   6348:     }
1.976     raeburn  6349:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6350:     my %allroles;
1.1128    raeburn  6351:     my ($is_adv,$is_author);
1.976     raeburn  6352:     foreach my $role (keys(%roleshash)) {
                   6353:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6354:         my $area = '/'.$tdomain.'/'.$trest;
                   6355:         if ($sec ne '') {
                   6356:             $area .= '/'.$sec;
                   6357:         }
                   6358:         if (($area ne '') && ($trole ne '')) {
                   6359:             my $spec=$trole.'.'.$area;
                   6360:             if ($trole =~ /^cr\//) {
                   6361:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6362:             } elsif ($trole ne 'gr') {
                   6363:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6364:             }
1.1128    raeburn  6365:             if ($trole eq 'au') {
                   6366:                 $is_author = 1;
                   6367:             }
1.976     raeburn  6368:         }
                   6369:     }
                   6370:     foreach my $role (keys(%allroles)) {
                   6371:         last if ($is_adv);
                   6372:         foreach my $item (split(/:/,$allroles{$role})) {
                   6373:             if ($item ne '') {
                   6374:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6375:                 if ($privilege eq 'adv') {
                   6376:                     $is_adv = 1;
                   6377:                     last;
                   6378:                 }
                   6379:             }
                   6380:         }
                   6381:     }
1.1128    raeburn  6382:     if (wantarray) {
                   6383:         return ($is_adv,$is_author);
                   6384:     }
1.976     raeburn  6385:     return $is_adv;
                   6386: }
1.798     raeburn  6387: 
1.1035    raeburn  6388: sub check_can_request {
1.1036    raeburn  6389:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6390:     my $canreq = 0;
                   6391:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6392:     my @options = ('approval','validate','autolimit');
                   6393:     my $optregex = join('|',@options);
                   6394:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6395:         foreach my $type (@{$types}) {
                   6396:             if (&usertools_access($env{'user.name'},
                   6397:                                   $env{'user.domain'},
                   6398:                                   $type,undef,'requestcourses')) {
                   6399:                 $canreq ++;
1.1036    raeburn  6400:                 if (ref($request_domains) eq 'HASH') {
                   6401:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6402:                 }
1.1035    raeburn  6403:                 if ($dom eq $env{'user.domain'}) {
                   6404:                     $can_request->{$type} = 1;
                   6405:                 }
                   6406:             }
                   6407:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6408:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6409:                 if (@curr > 0) {
1.1036    raeburn  6410:                     foreach my $item (@curr) {
                   6411:                         if (ref($request_domains) eq 'HASH') {
                   6412:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6413:                             if ($otherdom ne '') {
                   6414:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6415:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6416:                                         push(@{$request_domains->{$type}},$otherdom);
                   6417:                                     }
                   6418:                                 } else {
                   6419:                                     push(@{$request_domains->{$type}},$otherdom);
                   6420:                                 }
                   6421:                             }
                   6422:                         }
                   6423:                     }
                   6424:                     unless($dom eq $env{'user.domain'}) {
                   6425:                         $canreq ++;
1.1035    raeburn  6426:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6427:                             $can_request->{$type} = 1;
                   6428:                         }
                   6429:                     }
                   6430:                 }
                   6431:             }
                   6432:         }
                   6433:     }
                   6434:     return $canreq;
                   6435: }
                   6436: 
1.341     www      6437: # ---------------------------------------------- Custom access rule evaluation
                   6438: 
                   6439: sub customaccess {
                   6440:     my ($priv,$uri)=@_;
1.807     albertel 6441:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6442:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6443:     $udom = &LONCAPA::clean_domain($udom);
                   6444:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6445:     my $access=0;
1.800     albertel 6446:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6447: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6448: 	if ($type eq 'user') {
                   6449: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6450: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6451: 		if ($tdom) {
                   6452: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6453: 		}
1.896     albertel 6454: 		if ($tuname) {
                   6455: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6456: 		}
                   6457: 		$access=($effect eq 'allow');
                   6458: 		last;
                   6459: 	    }
                   6460: 	} else {
                   6461: 	    if ($role) {
                   6462: 		if ($role ne $urole) { next; }
                   6463: 	    }
                   6464: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6465: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6466: 		if ($tdom) {
                   6467: 		    if ($tdom ne $udom) { next; }
                   6468: 		}
                   6469: 		if ($tcrs) {
                   6470: 		    if ($tcrs ne $ucrs) { next; }
                   6471: 		}
                   6472: 		if ($tsec) {
                   6473: 		    if ($tsec ne $usec) { next; }
                   6474: 		}
                   6475: 		$access=($effect eq 'allow');
                   6476: 		last;
                   6477: 	    }
                   6478: 	    if ($realm eq '' && $role eq '') {
                   6479: 		$access=($effect eq 'allow');
                   6480: 	    }
1.402     bowersj2 6481: 	}
1.341     www      6482:     }
                   6483:     return $access;
                   6484: }
                   6485: 
1.103     harris41 6486: # ------------------------------------------------- Check for a user privilege
1.12      www      6487: 
                   6488: sub allowed {
1.810     raeburn  6489:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6490:     my $ver_orguri=$uri;
1.439     www      6491:     $uri=&deversion($uri);
1.152     www      6492:     my $orguri=$uri;
1.52      www      6493:     $uri=&declutter($uri);
1.809     raeburn  6494: 
1.810     raeburn  6495:     if ($priv eq 'evb') {
                   6496: # Evade communication block restrictions for specified role in a course
                   6497:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6498:             return $1;
                   6499:         } else {
                   6500:             return;
                   6501:         }
                   6502:     }
                   6503: 
1.620     albertel 6504:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6505: # Free bre access to adm and meta resources
1.775     albertel 6506:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6507: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6508: 	&& ($priv eq 'bre')) {
1.14      www      6509: 	return 'F';
1.159     www      6510:     }
                   6511: 
1.545     banghart 6512: # Free bre access to user's own portfolio contents
1.714     raeburn  6513:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6514:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6515: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6516:         my %setters;
                   6517:         my ($startblock,$endblock) = 
                   6518:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6519:         if ($startblock && $endblock) {
                   6520:             return 'B';
                   6521:         } else {
                   6522:             return 'F';
                   6523:         }
1.545     banghart 6524:     }
                   6525: 
1.762     raeburn  6526: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6527:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6528:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6529:         if (exists($env{'request.course.id'})) {
                   6530:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6531:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6532:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6533:                 my $courseprivid=$env{'request.course.id'};
                   6534:                 $courseprivid=~s/\_/\//;
                   6535:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6536:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6537:                     return $1; 
1.762     raeburn  6538:                 } else {
                   6539:                     if ($env{'request.course.sec'}) {
                   6540:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6541:                     }
                   6542:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6543:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6544:                         return $2;
                   6545:                     }
1.714     raeburn  6546:                 }
                   6547:             }
                   6548:         }
                   6549:     }
                   6550: 
1.159     www      6551: # Free bre to public access
                   6552: 
                   6553:     if ($priv eq 'bre') {
1.238     www      6554:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6555: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6556:            return 'F'; 
                   6557:         }
1.238     www      6558:         if ($copyright eq 'priv') {
                   6559:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6560: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6561: 		return '';
                   6562:             }
                   6563:         }
                   6564:         if ($copyright eq 'domain') {
                   6565:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6566: 	    unless (($env{'user.domain'} eq $1) ||
                   6567:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6568: 		return '';
                   6569:             }
1.262     matthew  6570:         }
1.620     albertel 6571:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6572:             # Library role, so allow browsing of resources in this domain.
                   6573:             return 'F';
1.238     www      6574:         }
1.341     www      6575:         if ($copyright eq 'custom') {
                   6576: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6577:         }
1.14      www      6578:     }
1.264     matthew  6579:     # Domain coordinator is trying to create a course
1.620     albertel 6580:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6581:         # uri is the requested domain in this case.
                   6582:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6583:         # a role of dc for the domain in question.
1.620     albertel 6584:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6585:     }
1.29      www      6586: 
1.52      www      6587:     my $thisallowed='';
                   6588:     my $statecond=0;
                   6589:     my $courseprivid='';
                   6590: 
1.1039    raeburn  6591:     my $ownaccess;
1.1043    raeburn  6592:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6593:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6594:         if ($uri eq '') {
                   6595:             $ownaccess = 1;
                   6596:         } else {
                   6597:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6598:                 my $udom = $env{'user.domain'};
                   6599:                 my $uname = $env{'user.name'};
                   6600:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6601:                     $ownaccess = 1;
1.1040    raeburn  6602:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6603:                     unless ($uri =~ m{\.\./}) {
                   6604:                         $ownaccess = 1;
                   6605:                     }
                   6606:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6607:                     my $now = time;
                   6608:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6609:                         my $adom = $1;
                   6610:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6611:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6612:                                 my ($start,$end) = split('.',$env{$key});
                   6613:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6614:                                     $ownaccess = 1;
                   6615:                                     last;
                   6616:                                 }
                   6617:                             }
                   6618:                         }
                   6619:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6620:                         my $adom = $1;
                   6621:                         my $aname = $2;
1.1042    raeburn  6622:                         foreach my $role ('ca','aa') { 
                   6623:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6624:                                 my ($start,$end) =
                   6625:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6626:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6627:                                     $ownaccess = 1;
                   6628:                                     last;
                   6629:                                 }
1.1039    raeburn  6630:                             }
                   6631:                         }
                   6632:                     }
                   6633:                 }
                   6634:             }
                   6635:         }
                   6636:     }
                   6637: 
1.52      www      6638: # Course
                   6639: 
1.620     albertel 6640:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6641:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6642:             $thisallowed.=$1;
                   6643:         }
1.52      www      6644:     }
1.29      www      6645: 
1.52      www      6646: # Domain
                   6647: 
1.620     albertel 6648:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6649:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6650:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6651:             $thisallowed.=$1;
                   6652:         }
1.12      www      6653:     }
1.52      www      6654: 
1.1141    raeburn  6655: # User who is not author or co-author might still be able to edit
                   6656: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6657:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6658:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6659:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6660:             $thisallowed.=$1;
                   6661:         }
                   6662:     }
                   6663: 
1.52      www      6664: # Course: uri itself is a course
1.66      www      6665:     my $courseuri=$uri;
                   6666:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6667:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6668: 
1.620     albertel 6669:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6670:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6671:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6672:             $thisallowed.=$1;
                   6673:         }
1.12      www      6674:     }
1.29      www      6675: 
1.665     albertel 6676: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6677: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6678:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6679: 	$thisallowed='';
1.671     raeburn  6680:         my ($match)=&is_on_map($uri);
                   6681:         if ($match) {
                   6682:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6683:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6684:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6685:                 if (@blockers > 0) {
                   6686:                     $thisallowed = 'B';
                   6687:                 } else {
                   6688:                     $thisallowed.=$1;
                   6689:                 }
1.671     raeburn  6690:             }
                   6691:         } else {
1.705     albertel 6692:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6693:             if ($refuri) {
                   6694:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6695:                     $thisallowed='F';
1.671     raeburn  6696:                 } else {
                   6697:                     $refuri=&declutter($refuri);
                   6698:                     my ($match) = &is_on_map($refuri);
                   6699:                     if ($match) {
1.1162    raeburn  6700:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6701:                         if (@blockers > 0) {
                   6702:                             $thisallowed = 'B';
                   6703:                         } else {
                   6704:                             $thisallowed='F';
                   6705:                         }
1.671     raeburn  6706:                     }
1.669     raeburn  6707:                 }
1.671     raeburn  6708:             }
                   6709:         }
1.314     www      6710:     }
1.492     albertel 6711: 
1.766     albertel 6712:     if ($priv eq 'bre'
                   6713: 	&& $thisallowed ne 'F' 
                   6714: 	&& $thisallowed ne '2'
                   6715: 	&& &is_portfolio_url($uri)) {
                   6716: 	$thisallowed = &portfolio_access($uri);
                   6717:     }
                   6718:     
1.52      www      6719: # Full access at system, domain or course-wide level? Exit.
1.29      www      6720:     if ($thisallowed=~/F/) {
                   6721: 	return 'F';
                   6722:     }
                   6723: 
1.52      www      6724: # If this is generating or modifying users, exit with special codes
1.29      www      6725: 
1.643     www      6726:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6727: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6728: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6729: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6730: 	    unless ($auname) { return $thisallowed; }
                   6731: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6732: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6733: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6734: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6735: 	}
1.52      www      6736: 	return $thisallowed;
                   6737:     }
                   6738: #
1.103     harris41 6739: # Gathered so far: system, domain and course wide privileges
1.52      www      6740: #
                   6741: # Course: See if uri or referer is an individual resource that is part of 
                   6742: # the course
                   6743: 
1.620     albertel 6744:     if ($env{'request.course.id'}) {
1.232     www      6745: 
1.620     albertel 6746:        $courseprivid=$env{'request.course.id'};
                   6747:        if ($env{'request.course.sec'}) {
                   6748:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6749:        }
                   6750:        $courseprivid=~s/\_/\//;
                   6751:        my $checkreferer=1;
1.232     www      6752:        my ($match,$cond)=&is_on_map($uri);
                   6753:        if ($match) {
                   6754:            $statecond=$cond;
1.620     albertel 6755:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6756:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6757:                my $value = $1;
                   6758:                if ($priv eq 'bre') {
                   6759:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6760:                    if (@blockers > 0) {
                   6761:                        $thisallowed = 'B';
                   6762:                    } else {
                   6763:                        $thisallowed.=$value;
                   6764:                    }
                   6765:                } else {
                   6766:                    $thisallowed.=$value;
                   6767:                }
1.52      www      6768:                $checkreferer=0;
                   6769:            }
1.29      www      6770:        }
1.83      www      6771:        
1.148     www      6772:        if ($checkreferer) {
1.620     albertel 6773: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6774:             unless ($refuri) {
1.800     albertel 6775:                 foreach my $key (keys(%env)) {
                   6776: 		    if ($key=~/^httpref\..*\*/) {
                   6777: 			my $pattern=$key;
1.156     www      6778:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6779:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6780:                         $pattern=~s/\//\\\//g;
1.152     www      6781:                         if ($orguri=~/$pattern/) {
1.800     albertel 6782: 			    $refuri=$env{$key};
1.148     www      6783:                         }
                   6784:                     }
1.191     harris41 6785:                 }
1.148     www      6786:             }
1.232     www      6787: 
1.148     www      6788:          if ($refuri) { 
1.152     www      6789: 	  $refuri=&declutter($refuri);
1.232     www      6790:           my ($match,$cond)=&is_on_map($refuri);
                   6791:             if ($match) {
                   6792:               my $refstatecond=$cond;
1.620     albertel 6793:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6794:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6795:                   my $value = $1;
                   6796:                   if ($priv eq 'bre') {
                   6797:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6798:                       if (@blockers > 0) {
                   6799:                           $thisallowed = 'B';
                   6800:                       } else {
                   6801:                           $thisallowed.=$value;
                   6802:                       }
                   6803:                   } else {
                   6804:                       $thisallowed.=$value;
                   6805:                   }
1.53      www      6806:                   $uri=$refuri;
                   6807:                   $statecond=$refstatecond;
1.52      www      6808:               }
                   6809:           }
1.148     www      6810:         }
1.29      www      6811:        }
1.52      www      6812:    }
1.29      www      6813: 
1.52      www      6814: #
1.103     harris41 6815: # Gathered now: all privileges that could apply, and condition number
1.52      www      6816: # 
                   6817: #
                   6818: # Full or no access?
                   6819: #
1.29      www      6820: 
1.52      www      6821:     if ($thisallowed=~/F/) {
                   6822: 	return 'F';
                   6823:     }
1.29      www      6824: 
1.52      www      6825:     unless ($thisallowed) {
                   6826:         return '';
                   6827:     }
1.29      www      6828: 
1.52      www      6829: # Restrictions exist, deal with them
                   6830: #
                   6831: #   C:according to course preferences
                   6832: #   R:according to resource settings
                   6833: #   L:unless locked
                   6834: #   X:according to user session state
                   6835: #
                   6836: 
                   6837: # Possibly locked functionality, check all courses
1.54      www      6838: # Locks might take effect only after 10 minutes cache expiration for other
                   6839: # courses, and 2 minutes for current course
1.52      www      6840: 
                   6841:     my $envkey;
                   6842:     if ($thisallowed=~/L/) {
1.1000    raeburn  6843:         foreach $envkey (keys(%env)) {
1.54      www      6844:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6845:                my $courseid=$2;
                   6846:                my $roleid=$1.'.'.$2;
1.92      www      6847:                $courseid=~s/^\///;
1.54      www      6848:                my $expiretime=600;
1.620     albertel 6849:                if ($env{'request.role'} eq $roleid) {
1.54      www      6850: 		  $expiretime=120;
                   6851:                }
                   6852: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6853:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6854:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6855: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6856:                }
1.620     albertel 6857:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6858:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6859: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6860:                        &log($env{'user.domain'},$env{'user.name'},
                   6861:                             $env{'user.home'},
1.57      www      6862:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6863:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6864:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6865: 		       return '';
                   6866:                    }
                   6867:                }
1.620     albertel 6868:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6869:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6870: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6871:                        &log($env{'user.domain'},$env{'user.name'},
                   6872:                             $env{'user.home'},
1.57      www      6873:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6874:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6875:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6876: 		       return '';
                   6877:                    }
                   6878:                }
                   6879: 	   }
1.29      www      6880:        }
1.52      www      6881:     }
                   6882:    
                   6883: #
                   6884: # Rest of the restrictions depend on selected course
                   6885: #
                   6886: 
1.620     albertel 6887:     unless ($env{'request.course.id'}) {
1.766     albertel 6888: 	if ($thisallowed eq 'A') {
                   6889: 	    return 'A';
1.814     raeburn  6890:         } elsif ($thisallowed eq 'B') {
                   6891:             return 'B';
1.766     albertel 6892: 	} else {
                   6893: 	    return '1';
                   6894: 	}
1.52      www      6895:     }
1.29      www      6896: 
1.52      www      6897: #
                   6898: # Now user is definitely in a course
                   6899: #
1.53      www      6900: 
                   6901: 
                   6902: # Course preferences
                   6903: 
                   6904:    if ($thisallowed=~/C/) {
1.620     albertel 6905:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6906:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6907:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6908: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6909: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6910: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6911: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6912: 			$env{'request.course.id'});
                   6913: 	   }
1.237     www      6914:            return '';
                   6915:        }
                   6916: 
1.620     albertel 6917:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6918: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6919: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6920: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6921: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6922: 			$env{'request.course.id'});
                   6923: 	   }
1.54      www      6924:            return '';
                   6925:        }
1.53      www      6926:    }
                   6927: 
                   6928: # Resource preferences
                   6929: 
                   6930:    if ($thisallowed=~/R/) {
1.620     albertel 6931:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6932:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6933: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6934: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6935: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6936: 	   }
                   6937: 	   return '';
1.54      www      6938:        }
1.53      www      6939:    }
1.30      www      6940: 
1.246     www      6941: # Restricted by state or randomout?
1.30      www      6942: 
1.52      www      6943:    if ($thisallowed=~/X/) {
1.620     albertel 6944:       if ($env{'acc.randomout'}) {
1.579     albertel 6945: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6946:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6947:             return ''; 
                   6948:          }
1.247     www      6949:       }
                   6950:       if (&condval($statecond)) {
1.52      www      6951: 	 return '2';
                   6952:       } else {
                   6953:          return '';
                   6954:       }
                   6955:    }
1.30      www      6956: 
1.766     albertel 6957:     if ($thisallowed eq 'A') {
                   6958: 	return 'A';
1.814     raeburn  6959:     } elsif ($thisallowed eq 'B') {
                   6960:         return 'B';
1.766     albertel 6961:     }
1.52      www      6962:    return 'F';
1.232     www      6963: }
1.1162    raeburn  6964: 
1.1192    raeburn  6965: # ------------------------------------------- Check construction space access
                   6966: 
                   6967: sub constructaccess {
                   6968:     my ($url,$setpriv)=@_;
                   6969: 
                   6970: # We do not allow editing of previous versions of files
                   6971:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6972: 
                   6973: # Get username and domain from URL
                   6974:     my ($ownername,$ownerdomain,$ownerhome);
                   6975: 
                   6976:     ($ownerdomain,$ownername) =
                   6977:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6978: 
                   6979: # The URL does not really point to any authorspace, forget it
                   6980:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6981: 
                   6982: # Now we need to see if the user has access to the authorspace of
                   6983: # $ownername at $ownerdomain
                   6984: 
                   6985:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6986: # Real author for this?
                   6987:        $ownerhome = $env{'user.home'};
                   6988:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6989:           return ($ownername,$ownerdomain,$ownerhome);
                   6990:        }
                   6991:     } else {
                   6992: # Co-author for this?
                   6993:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6994:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6995:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6996:             return ($ownername,$ownerdomain,$ownerhome);
                   6997:         }
                   6998:     }
                   6999: 
                   7000: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7001: # we might as well leave
                   7002:    unless ($setpriv) { return ''; }
                   7003: 
                   7004: # Backdoor access?
                   7005:     my $allowed=&allowed('eco',$ownerdomain);
                   7006: # Nope
                   7007:     unless ($allowed) { return ''; }
                   7008: # Looks like we may have access, but could be locked by the owner of the construction space
                   7009:     if ($allowed eq 'U') {
                   7010:         my %blocked=&get('environment',['domcoord.author'],
                   7011:                          $ownerdomain,$ownername);
                   7012: # Is blocked by owner
                   7013:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7014:     }
                   7015:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7016: # Grant temporary access
                   7017:         my $then=$env{'user.login.time'};
1.1209    raeburn  7018:         my $update=$env{'user.update.time'};
1.1192    raeburn  7019:         if (!$update) { $update = $then; }
                   7020:         my $refresh=$env{'user.refresh.time'};
                   7021:         if (!$refresh) { $refresh = $update; }
                   7022:         my $now = time;
                   7023:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7024:                            $now,'ca','constructaccess');
                   7025:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7026:         return($ownername,$ownerdomain,$ownerhome);
                   7027:     }
                   7028: # No business here
                   7029:     return '';
                   7030: }
                   7031: 
1.1162    raeburn  7032: sub get_comm_blocks {
                   7033:     my ($cdom,$cnum) = @_;
                   7034:     if ($cdom eq '' || $cnum eq '') {
                   7035:         return unless ($env{'request.course.id'});
                   7036:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7037:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7038:     }
                   7039:     my %commblocks;
                   7040:     my $hashid=$cdom.'_'.$cnum;
                   7041:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7042:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7043:         %commblocks = %{$blocksref};
                   7044:     } else {
                   7045:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7046:         my $cachetime = 600;
                   7047:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7048:     }
                   7049:     return %commblocks;
                   7050: }
                   7051: 
                   7052: sub has_comm_blocking {
                   7053:     my ($priv,$symb,$uri,$blocks) = @_;
                   7054:     return unless ($env{'request.course.id'});
                   7055:     return unless ($priv eq 'bre');
                   7056:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7057:     my %commblocks;
                   7058:     if (ref($blocks) eq 'HASH') {
                   7059:         %commblocks = %{$blocks};
                   7060:     } else {
                   7061:         %commblocks = &get_comm_blocks();
                   7062:     }
                   7063:     return unless (keys(%commblocks) > 0);
                   7064:     if (!$symb) { $symb=&symbread($uri,1); }
                   7065:     my ($map,$resid,undef)=&decode_symb($symb);
                   7066:     my %tocheck = (
                   7067:                     maps      => $map,
                   7068:                     resources => $symb,
                   7069:                   );
                   7070:     my @blockers;
                   7071:     my $now = time;
1.1163    raeburn  7072:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7073:     foreach my $block (keys(%commblocks)) {
                   7074:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7075:             my ($start,$end) = ($1,$2);
                   7076:             if ($start <= $now && $end >= $now) {
                   7077:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7078:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7079:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7080:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7081:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7082:                                     push(@blockers,$block);
                   7083:                                 }
                   7084:                             }
                   7085:                         }
                   7086:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7087:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7088:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7089:                                     push(@blockers,$block);
                   7090:                                 }
                   7091:                             }
                   7092:                         }
                   7093:                     }
                   7094:                 }
                   7095:             }
                   7096:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7097:             my $item = $1;
1.1163    raeburn  7098:             my @to_test;
1.1162    raeburn  7099:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7100:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7101:                     my $check_interval;
                   7102:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7103:                         my @interval;
                   7104:                         my $type = 'map';
                   7105:                         if ($item eq 'course') {
                   7106:                             $type = 'course';
                   7107:                             @interval=&EXT("resource.0.interval");
                   7108:                         } else {
                   7109:                             if ($item =~ /___\d+___/) {
                   7110:                                 $type = 'resource';
                   7111:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7112:                                 if (ref($navmap)) {                        
                   7113:                                     my $res = $navmap->getBySymb($item); 
                   7114:                                     push(@to_test,$res);
                   7115:                                 }
1.1162    raeburn  7116:                             } else {
                   7117:                                 my $mapsymb = &symbread($item,1);
                   7118:                                 if ($mapsymb) {
                   7119:                                     if (ref($navmap)) {
                   7120:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7121:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7122:                                         foreach my $res (@to_test) {
1.1162    raeburn  7123:                                             my $symb = $res->symb();
                   7124:                                             next if ($symb eq $mapsymb);
                   7125:                                             if ($symb ne '') {
                   7126:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7127:                                                 last;
                   7128:                                             }
                   7129:                                         }
                   7130:                                     }
                   7131:                                 }
                   7132:                             }
                   7133:                         }
                   7134:                         if ($interval[0] =~ /\d+/) {
                   7135:                             my $first_access;
                   7136:                             if ($type eq 'resource') {
                   7137:                                 $first_access=&get_first_access($interval[1],$item);
                   7138:                             } elsif ($type eq 'map') {
                   7139:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7140:                             } else {
                   7141:                                 $first_access=&get_first_access($interval[1]);
                   7142:                             }
                   7143:                             if ($first_access) {
                   7144:                                 my $timesup = $first_access+$interval[0];
                   7145:                                 if ($timesup > $now) {
1.1163    raeburn  7146:                                     foreach my $res (@to_test) {
                   7147:                                         if ($res->is_problem()) {
                   7148:                                             if ($res->completable()) {
                   7149:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7150:                                                     push(@blockers,$block);
                   7151:                                                 }
                   7152:                                                 last;
                   7153:                                             }
                   7154:                                         }
1.1162    raeburn  7155:                                     }
                   7156:                                 }
                   7157:                             }
                   7158:                         }
                   7159:                     }
                   7160:                 }
                   7161:             }
                   7162:         }
                   7163:     }
                   7164:     return @blockers;
                   7165: }
                   7166: 
                   7167: sub check_docs_block {
                   7168:     my ($docsblock,$tocheck) =@_;
                   7169:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7170:         return;
                   7171:     }
                   7172:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7173:         if ($tocheck->{'maps'}) {
                   7174:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7175:                 return 1;
                   7176:             }
                   7177:         }
                   7178:     }
                   7179:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7180:         if ($tocheck->{'resources'}) {
                   7181:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7182:                 return 1;
                   7183:             }
                   7184:         }
                   7185:     }
                   7186:     return;
                   7187: }
                   7188: 
1.1133    foxr     7189: #
                   7190: #   Removes the versino from a URI and
                   7191: #   splits it in to its filename and path to the filename.
                   7192: #   Seems like File::Basename could have done this more clearly.
                   7193: #   Parameters:
                   7194: #      $uri   - input URI
                   7195: #   Returns:
                   7196: #     Two element list consisting of 
                   7197: #     $pathname  - the URI up to and excluding the trailing /
                   7198: #     $filename  - The part of the URI following the last /
                   7199: #  NOTE:
                   7200: #    Another realization of this is simply:
                   7201: #    use File::Basename;
                   7202: #    ...
                   7203: #    $uri = shift;
                   7204: #    $filename = basename($uri);
                   7205: #    $path     = dirname($uri);
                   7206: #    return ($filename, $path);
                   7207: #
                   7208: #     The implementation below is probably faster however.
                   7209: #
1.710     albertel 7210: sub split_uri_for_cond {
                   7211:     my $uri=&deversion(&declutter(shift));
                   7212:     my @uriparts=split(/\//,$uri);
                   7213:     my $filename=pop(@uriparts);
                   7214:     my $pathname=join('/',@uriparts);
                   7215:     return ($pathname,$filename);
                   7216: }
1.232     www      7217: # --------------------------------------------------- Is a resource on the map?
                   7218: 
                   7219: sub is_on_map {
1.710     albertel 7220:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7221:     #Trying to find the conditional for the file
1.620     albertel 7222:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7223: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7224:     if ($match) {
1.289     bowersj2 7225: 	return (1,$1);
                   7226:     } else {
1.434     www      7227: 	return (0,0);
1.289     bowersj2 7228:     }
1.12      www      7229: }
                   7230: 
1.427     www      7231: # --------------------------------------------------------- Get symb from alias
                   7232: 
                   7233: sub get_symb_from_alias {
                   7234:     my $symb=shift;
                   7235:     my ($map,$resid,$url)=&decode_symb($symb);
                   7236: # Already is a symb
                   7237:     if ($url) { return $symb; }
                   7238: # Must be an alias
                   7239:     my $aliassymb='';
                   7240:     my %bighash;
1.620     albertel 7241:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7242:                             &GDBM_READER(),0640)) {
                   7243:         my $rid=$bighash{'mapalias_'.$symb};
                   7244: 	if ($rid) {
                   7245: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7246: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7247: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7248: 	}
                   7249:         untie %bighash;
                   7250:     }
                   7251:     return $aliassymb;
                   7252: }
                   7253: 
1.12      www      7254: # ----------------------------------------------------------------- Define Role
                   7255: 
                   7256: sub definerole {
                   7257:   if (allowed('mcr','/')) {
                   7258:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7259:     foreach my $role (split(':',$sysrole)) {
                   7260: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7261:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7262:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7263: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7264:                return "refused:s:$crole&$cqual"; 
                   7265:             }
                   7266:         }
1.191     harris41 7267:     }
1.800     albertel 7268:     foreach my $role (split(':',$domrole)) {
                   7269: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7270:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7271:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7272: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7273:                return "refused:d:$crole&$cqual"; 
                   7274:             }
                   7275:         }
1.191     harris41 7276:     }
1.800     albertel 7277:     foreach my $role (split(':',$courole)) {
                   7278: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7279:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7280:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7281: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7282:                return "refused:c:$crole&$cqual"; 
                   7283:             }
                   7284:         }
1.191     harris41 7285:     }
1.620     albertel 7286:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7287:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7288: 	        "rolesdef_$rolename=".
                   7289:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7290:     return reply($command,$env{'user.home'});
1.12      www      7291:   } else {
                   7292:     return 'refused';
                   7293:   }
1.105     harris41 7294: }
                   7295: 
                   7296: # ---------------- Make a metadata query against the network of library servers
                   7297: 
                   7298: sub metadata_query {
1.1237    raeburn  7299:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7300:     my %rhash;
1.845     albertel 7301:     my %libserv = &all_library();
1.244     matthew  7302:     my @server_list = (defined($server_array) ? @$server_array
                   7303:                                               : keys(%libserv) );
                   7304:     for my $server (@server_list) {
1.1237    raeburn  7305:         my $domains = ''; 
                   7306:         if (ref($domains_hash) eq 'HASH') {
                   7307:             $domains = $domains_hash->{$server}; 
                   7308:         }
1.118     harris41 7309: 	unless ($custom or $customshow) {
1.1237    raeburn  7310: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7311: 	    $rhash{$server}=$reply;
                   7312: 	}
                   7313: 	else {
                   7314: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7315: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7316: 			     $server);
                   7317: 	    $rhash{$server}=$reply;
                   7318: 	}
1.112     harris41 7319:     }
1.118     harris41 7320:     return \%rhash;
1.240     www      7321: }
                   7322: 
                   7323: # ----------------------------------------- Send log queries and wait for reply
                   7324: 
                   7325: sub log_query {
                   7326:     my ($uname,$udom,$query,%filters)=@_;
                   7327:     my $uhome=&homeserver($uname,$udom);
                   7328:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7329:     my $uhost=&hostname($uhome);
1.800     albertel 7330:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7331:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7332:                        $uhome);
1.479     albertel 7333:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7334:     return get_query_reply($queryid);
                   7335: }
                   7336: 
1.818     raeburn  7337: # -------------------------- Update MySQL table for portfolio file
                   7338: 
                   7339: sub update_portfolio_table {
1.821     raeburn  7340:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7341:     if ($group ne '') {
                   7342:         $file_name =~s /^\Q$group\E//;
                   7343:     }
1.818     raeburn  7344:     my $homeserver = &homeserver($uname,$udom);
                   7345:     my $queryid=
1.821     raeburn  7346:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7347:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7348:     my $reply = &get_query_reply($queryid);
                   7349:     return $reply;
                   7350: }
                   7351: 
1.899     raeburn  7352: # -------------------------- Update MySQL allusers table
                   7353: 
                   7354: sub update_allusers_table {
                   7355:     my ($uname,$udom,$names) = @_;
                   7356:     my $homeserver = &homeserver($uname,$udom);
                   7357:     my $queryid=
                   7358:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7359:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7360:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7361:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7362:                'generation='.&escape($names->{'generation'}).'%%'.
                   7363:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7364:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7365:     return;
1.899     raeburn  7366: }
                   7367: 
1.508     raeburn  7368: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7369: 
                   7370: sub fetch_enrollment_query {
1.511     raeburn  7371:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7372:     my $homeserver;
1.547     raeburn  7373:     my $maxtries = 1;
1.508     raeburn  7374:     if ($context eq 'automated') {
                   7375:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7376:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7377:     } else {
                   7378:         $homeserver = &homeserver($cnum,$dom);
                   7379:     }
1.838     albertel 7380:     my $host=&hostname($homeserver);
1.506     raeburn  7381:     my $cmd = '';
1.1000    raeburn  7382:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7383:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7384:     }
                   7385:     $cmd =~ s/%%$//;
                   7386:     $cmd = &escape($cmd);
                   7387:     my $query = 'fetchenrollment';
1.620     albertel 7388:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7389:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7390:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7391:         return 'error: '.$queryid;
                   7392:     }
1.506     raeburn  7393:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7394:     my $tries = 1;
                   7395:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7396:         $reply = &get_query_reply($queryid);
                   7397:         $tries ++;
                   7398:     }
1.526     raeburn  7399:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7400:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7401:     } else {
1.901     albertel 7402:         my @responses = split(/:/,$reply);
1.515     raeburn  7403:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7404:             foreach my $line (@responses) {
                   7405:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7406:                 $$replyref{$key} = $value;
                   7407:             }
                   7408:         } else {
1.1117    foxr     7409:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7410:             foreach my $line (@responses) {
                   7411:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7412:                 $$replyref{$key} = $value;
                   7413:                 if ($value > 0) {
1.800     albertel 7414:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7415:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7416:                         my $destname = $pathname.'/'.$filename;
                   7417:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7418:                         if ($xml_classlist =~ /^error/) {
                   7419:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7420:                         } else {
1.506     raeburn  7421:                             if ( open(FILE,">$destname") ) {
                   7422:                                 print FILE &unescape($xml_classlist);
                   7423:                                 close(FILE);
1.526     raeburn  7424:                             } else {
                   7425:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7426:                             }
                   7427:                         }
                   7428:                     }
                   7429:                 }
                   7430:             }
                   7431:         }
                   7432:         return 'ok';
                   7433:     }
                   7434:     return 'error';
                   7435: }
                   7436: 
1.242     www      7437: sub get_query_reply {
                   7438:     my $queryid=shift;
1.1117    foxr     7439:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7440:     my $reply='';
                   7441:     for (1..100) {
                   7442: 	sleep 2;
                   7443:         if (-e $replyfile.'.end') {
1.448     albertel 7444: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7445: 		$reply = join('',<$fh>);
                   7446: 		close($fh);
1.240     www      7447: 	   } else { return 'error: reply_file_error'; }
1.242     www      7448:            return &unescape($reply);
                   7449: 	}
1.240     www      7450:     }
1.242     www      7451:     return 'timeout:'.$queryid;
1.240     www      7452: }
                   7453: 
                   7454: sub courselog_query {
1.241     www      7455: #
                   7456: # possible filters:
                   7457: # url: url or symb
                   7458: # username
                   7459: # domain
                   7460: # action: view, submit, grade
                   7461: # start: timestamp
                   7462: # end: timestamp
                   7463: #
1.240     www      7464:     my (%filters)=@_;
1.620     albertel 7465:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7466:     if ($filters{'url'}) {
                   7467: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7468:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7469:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7470:     }
1.620     albertel 7471:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7472:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7473:     return &log_query($cname,$cdom,'courselog',%filters);
                   7474: }
                   7475: 
                   7476: sub userlog_query {
1.858     raeburn  7477: #
                   7478: # possible filters:
                   7479: # action: log check role
                   7480: # start: timestamp
                   7481: # end: timestamp
                   7482: #
1.240     www      7483:     my ($uname,$udom,%filters)=@_;
                   7484:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7485: }
                   7486: 
1.506     raeburn  7487: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7488: 
                   7489: sub auto_run {
1.508     raeburn  7490:     my ($cnum,$cdom) = @_;
1.876     raeburn  7491:     my $response = 0;
                   7492:     my $settings;
                   7493:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7494:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7495:         $settings = $domconfig{'autoenroll'};
                   7496:         if ($settings->{'run'} eq '1') {
                   7497:             $response = 1;
                   7498:         }
                   7499:     } else {
1.934     raeburn  7500:         my $homeserver;
                   7501:         if (&is_course($cdom,$cnum)) {
                   7502:             $homeserver = &homeserver($cnum,$cdom);
                   7503:         } else {
                   7504:             $homeserver = &domain($cdom,'primary');
                   7505:         }
                   7506:         if ($homeserver ne 'no_host') {
                   7507:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7508:         }
1.876     raeburn  7509:     }
1.506     raeburn  7510:     return $response;
                   7511: }
1.776     albertel 7512: 
1.506     raeburn  7513: sub auto_get_sections {
1.508     raeburn  7514:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7515:     my $homeserver;
                   7516:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7517:         $homeserver = &homeserver($cnum,$cdom);
                   7518:     }
                   7519:     if (!defined($homeserver)) { 
                   7520:         if ($cdom =~ /^$match_domain$/) {
                   7521:             $homeserver = &domain($cdom,'primary');
                   7522:         }
                   7523:     }
                   7524:     my @secs;
                   7525:     if (defined($homeserver)) {
                   7526:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7527:         unless ($response eq 'refused') {
                   7528:             @secs = split(/:/,$response);
                   7529:         }
1.506     raeburn  7530:     }
                   7531:     return @secs;
                   7532: }
1.776     albertel 7533: 
1.506     raeburn  7534: sub auto_new_course {
1.1099    raeburn  7535:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7536:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7537:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7538:     return $response;
                   7539: }
1.776     albertel 7540: 
1.506     raeburn  7541: sub auto_validate_courseID {
1.508     raeburn  7542:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7543:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7544:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7545:     return $response;
                   7546: }
1.776     albertel 7547: 
1.1007    raeburn  7548: sub auto_validate_instcode {
1.1020    raeburn  7549:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7550:     my ($homeserver,$response);
                   7551:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7552:         $homeserver = &homeserver($cnum,$cdom);
                   7553:     }
                   7554:     if (!defined($homeserver)) {
                   7555:         if ($cdom =~ /^$match_domain$/) {
                   7556:             $homeserver = &domain($cdom,'primary');
                   7557:         }
                   7558:     }
1.1065    raeburn  7559:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7560:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7561:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7562:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7563: }
                   7564: 
1.506     raeburn  7565: sub auto_create_password {
1.873     raeburn  7566:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7567:     my ($homeserver,$response);
1.506     raeburn  7568:     my $create_passwd = 0;
                   7569:     my $authchk = '';
1.873     raeburn  7570:     if ($udom =~ /^$match_domain$/) {
                   7571:         $homeserver = &domain($udom,'primary');
                   7572:     }
                   7573:     if ($homeserver eq '') {
                   7574:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7575:             $homeserver = &homeserver($cnum,$cdom);
                   7576:         }
                   7577:     }
                   7578:     if ($homeserver eq '') {
                   7579:         $authchk = 'nodomain';
1.506     raeburn  7580:     } else {
1.873     raeburn  7581:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7582:         if ($response eq 'refused') {
                   7583:             $authchk = 'refused';
                   7584:         } else {
1.901     albertel 7585:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7586:         }
1.506     raeburn  7587:     }
                   7588:     return ($authparam,$create_passwd,$authchk);
                   7589: }
                   7590: 
1.706     raeburn  7591: sub auto_photo_permission {
                   7592:     my ($cnum,$cdom,$students) = @_;
                   7593:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7594:     my ($outcome,$perm_reqd,$conditions) = 
                   7595: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7596:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7597: 	return (undef,undef);
                   7598:     }
1.706     raeburn  7599:     return ($outcome,$perm_reqd,$conditions);
                   7600: }
                   7601: 
                   7602: sub auto_checkphotos {
                   7603:     my ($uname,$udom,$pid) = @_;
                   7604:     my $homeserver = &homeserver($uname,$udom);
                   7605:     my ($result,$resulttype);
                   7606:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7607: 				   &escape($uname).':'.&escape($pid),
                   7608: 				   $homeserver));
1.709     albertel 7609:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7610: 	return (undef,undef);
                   7611:     }
1.706     raeburn  7612:     if ($outcome) {
                   7613:         ($result,$resulttype) = split(/:/,$outcome);
                   7614:     } 
                   7615:     return ($result,$resulttype);
                   7616: }
                   7617: 
                   7618: sub auto_photochoice {
                   7619:     my ($cnum,$cdom) = @_;
                   7620:     my $homeserver = &homeserver($cnum,$cdom);
                   7621:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7622: 						       &escape($cdom),
                   7623: 						       $homeserver)));
1.709     albertel 7624:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7625: 	return (undef,undef);
                   7626:     }
1.706     raeburn  7627:     return ($update,$comment);
                   7628: }
                   7629: 
                   7630: sub auto_photoupdate {
                   7631:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7632:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7633:     my $host=&hostname($homeserver);
1.706     raeburn  7634:     my $cmd = '';
                   7635:     my $maxtries = 1;
1.800     albertel 7636:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7637:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7638:     }
                   7639:     $cmd =~ s/%%$//;
                   7640:     $cmd = &escape($cmd);
                   7641:     my $query = 'institutionalphotos';
                   7642:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7643:     unless ($queryid=~/^\Q$host\E\_/) {
                   7644:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7645:         return 'error: '.$queryid;
                   7646:     }
                   7647:     my $reply = &get_query_reply($queryid);
                   7648:     my $tries = 1;
                   7649:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7650:         $reply = &get_query_reply($queryid);
                   7651:         $tries ++;
                   7652:     }
                   7653:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7654:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7655:     } else {
                   7656:         my @responses = split(/:/,$reply);
                   7657:         my $outcome = shift(@responses); 
                   7658:         foreach my $item (@responses) {
                   7659:             my ($key,$value) = split(/=/,$item);
                   7660:             $$photo{$key} = $value;
                   7661:         }
                   7662:         return $outcome;
                   7663:     }
                   7664:     return 'error';
                   7665: }
                   7666: 
1.521     raeburn  7667: sub auto_instcode_format {
1.793     albertel 7668:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7669: 	$cat_order) = @_;
1.521     raeburn  7670:     my $courses = '';
1.772     raeburn  7671:     my @homeservers;
1.521     raeburn  7672:     if ($caller eq 'global') {
1.841     albertel 7673: 	my %servers = &get_servers($codedom,'library');
                   7674: 	foreach my $tryserver (keys(%servers)) {
                   7675: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7676: 		push(@homeservers,$tryserver);
                   7677: 	    }
1.584     raeburn  7678:         }
1.1022    raeburn  7679:     } elsif ($caller eq 'requests') {
                   7680:         if ($codedom =~ /^$match_domain$/) {
                   7681:             my $chome = &domain($codedom,'primary');
                   7682:             unless ($chome eq 'no_host') {
                   7683:                 push(@homeservers,$chome);
                   7684:             }
                   7685:         }
1.521     raeburn  7686:     } else {
1.772     raeburn  7687:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7688:     }
1.793     albertel 7689:     foreach my $code (keys(%{$instcodes})) {
                   7690:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7691:     }
                   7692:     chop($courses);
1.772     raeburn  7693:     my $ok_response = 0;
                   7694:     my $response;
                   7695:     while (@homeservers > 0 && $ok_response == 0) {
                   7696:         my $server = shift(@homeservers); 
                   7697:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7698:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7699:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7700: 		split(/:/,$response);
1.772     raeburn  7701:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7702:             push(@{$codetitles},&str2array($codetitles_str));
                   7703:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7704:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7705:             $ok_response = 1;
                   7706:         }
                   7707:     }
                   7708:     if ($ok_response) {
1.521     raeburn  7709:         return 'ok';
1.772     raeburn  7710:     } else {
                   7711:         return $response;
1.521     raeburn  7712:     }
                   7713: }
                   7714: 
1.792     raeburn  7715: sub auto_instcode_defaults {
                   7716:     my ($domain,$returnhash,$code_order) = @_;
                   7717:     my @homeservers;
1.841     albertel 7718: 
                   7719:     my %servers = &get_servers($domain,'library');
                   7720:     foreach my $tryserver (keys(%servers)) {
                   7721: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7722: 	    push(@homeservers,$tryserver);
                   7723: 	}
1.792     raeburn  7724:     }
1.841     albertel 7725: 
1.792     raeburn  7726:     my $response;
1.841     albertel 7727:     foreach my $server (@homeservers) {
1.792     raeburn  7728:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7729:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7730: 	
                   7731: 	foreach my $pair (split(/\&/,$response)) {
                   7732: 	    my ($name,$value)=split(/\=/,$pair);
                   7733: 	    if ($name eq 'code_order') {
                   7734: 		@{$code_order} = split(/\&/,&unescape($value));
                   7735: 	    } else {
                   7736: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7737: 	    }
                   7738: 	}
                   7739: 	return 'ok';
1.792     raeburn  7740:     }
1.841     albertel 7741: 
                   7742:     return $response;
1.1003    raeburn  7743: }
                   7744: 
                   7745: sub auto_possible_instcodes {
1.1007    raeburn  7746:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7747:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7748:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7749:         return;
                   7750:     }
1.1003    raeburn  7751:     my (@homeservers,$uhome);
                   7752:     if (defined(&domain($domain,'primary'))) {
                   7753:         $uhome=&domain($domain,'primary');
                   7754:         push(@homeservers,&domain($domain,'primary'));
                   7755:     } else {
                   7756:         my %servers = &get_servers($domain,'library');
                   7757:         foreach my $tryserver (keys(%servers)) {
                   7758:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7759:                 push(@homeservers,$tryserver);
                   7760:             }
                   7761:         }
                   7762:     }
                   7763:     my $response;
                   7764:     foreach my $server (@homeservers) {
                   7765:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7766:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7767:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7768:             split(':',$response);
                   7769:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7770:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7771:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7772:             my ($name,$value)=split('=',$item);
                   7773:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7774:         }
                   7775:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7776:             my ($name,$value)=split('=',$item);
                   7777:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7778:         }
                   7779:         return 'ok';
                   7780:     }
                   7781:     return $response;
                   7782: }
1.792     raeburn  7783: 
1.1010    raeburn  7784: sub auto_courserequest_checks {
                   7785:     my ($dom) = @_;
1.1020    raeburn  7786:     my ($homeserver,%validations);
                   7787:     if ($dom =~ /^$match_domain$/) {
                   7788:         $homeserver = &domain($dom,'primary');
                   7789:     }
                   7790:     unless ($homeserver eq 'no_host') {
                   7791:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7792:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7793:             my @items = split(/&/,$response);
                   7794:             foreach my $item (@items) {
                   7795:                 my ($key,$value) = split('=',$item);
                   7796:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7797:             }
                   7798:         }
                   7799:     }
1.1010    raeburn  7800:     return %validations; 
                   7801: }
                   7802: 
1.1020    raeburn  7803: sub auto_courserequest_validation {
                   7804:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7805:     my ($homeserver,$response);
                   7806:     if ($dom =~ /^$match_domain$/) {
                   7807:         $homeserver = &domain($dom,'primary');
                   7808:     }
                   7809:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7810:           
1.1020    raeburn  7811:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7812:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7813:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7814:                                     $homeserver));
                   7815:     }
                   7816:     return $response;
                   7817: }
                   7818: 
1.777     albertel 7819: sub auto_validate_class_sec {
1.918     raeburn  7820:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7821:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7822:     my $ownerlist;
                   7823:     if (ref($owners) eq 'ARRAY') {
                   7824:         $ownerlist = join(',',@{$owners});
                   7825:     } else {
                   7826:         $ownerlist = $owners;
                   7827:     }
1.773     raeburn  7828:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7829:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7830:     return $response;
                   7831: }
                   7832: 
1.679     raeburn  7833: # ------------------------------------------------------- Course Group routines
                   7834: 
                   7835: sub get_coursegroups {
1.809     raeburn  7836:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7837:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7838: }
                   7839: 
1.679     raeburn  7840: sub modify_coursegroup {
                   7841:     my ($cdom,$cnum,$groupsettings) = @_;
                   7842:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7843: }
                   7844: 
1.809     raeburn  7845: sub toggle_coursegroup_status {
                   7846:     my ($cdom,$cnum,$group,$action) = @_;
                   7847:     my ($from_namespace,$to_namespace);
                   7848:     if ($action eq 'delete') {
                   7849:         $from_namespace = 'coursegroups';
                   7850:         $to_namespace = 'deleted_groups';
                   7851:     } else {
                   7852:         $from_namespace = 'deleted_groups';
                   7853:         $to_namespace = 'coursegroups';
                   7854:     }
                   7855:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7856:     if (my $tmp = &error(%curr_group)) {
                   7857:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7858:         return ('read error',$tmp);
                   7859:     } else {
                   7860:         my %savedsettings = %curr_group; 
1.809     raeburn  7861:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7862:         my $deloutcome;
                   7863:         if ($result eq 'ok') {
1.809     raeburn  7864:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7865:         } else {
                   7866:             return ('write error',$result);
                   7867:         }
                   7868:         if ($deloutcome eq 'ok') {
                   7869:             return 'ok';
                   7870:         } else {
                   7871:             return ('delete error',$deloutcome);
                   7872:         }
                   7873:     }
                   7874: }
                   7875: 
1.679     raeburn  7876: sub modify_group_roles {
1.957     raeburn  7877:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7878:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7879:     my $role = 'gr/'.&escape($userprivs);
                   7880:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7881:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7882:     if ($result eq 'ok') {
                   7883:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7884:     }
1.679     raeburn  7885:     return $result;
                   7886: }
                   7887: 
                   7888: sub modify_coursegroup_membership {
                   7889:     my ($cdom,$cnum,$membership) = @_;
                   7890:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7891:     return $result;
                   7892: }
                   7893: 
1.682     raeburn  7894: sub get_active_groups {
                   7895:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7896:     my $now = time;
                   7897:     my %groups = ();
                   7898:     foreach my $key (keys(%env)) {
1.811     albertel 7899:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7900:             my ($start,$end) = split(/\./,$env{$key});
                   7901:             if (($end!=0) && ($end<$now)) { next; }
                   7902:             if (($start!=0) && ($start>$now)) { next; }
                   7903:             if ($1 eq $cdom && $2 eq $cnum) {
                   7904:                 $groups{$3} = $env{$key} ;
                   7905:             }
                   7906:         }
                   7907:     }
                   7908:     return %groups;
                   7909: }
                   7910: 
1.683     raeburn  7911: sub get_group_membership {
                   7912:     my ($cdom,$cnum,$group) = @_;
                   7913:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7914: }
                   7915: 
                   7916: sub get_users_groups {
                   7917:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7918:     my @usersgroups;
1.683     raeburn  7919:     my $cachetime=1800;
                   7920: 
                   7921:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7922:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7923:     if (defined($cached)) {
1.734     albertel 7924:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7925:     } else {  
                   7926:         $grouplist = '';
1.816     raeburn  7927:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7928:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7929:         my $access_end = $env{'course.'.$courseid.
                   7930:                               '.default_enrollment_end_date'};
                   7931:         my $now = time;
                   7932:         foreach my $key (keys(%roleshash)) {
                   7933:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7934:                 my $group = $1;
                   7935:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7936:                     my $start = $2;
                   7937:                     my $end = $1;
                   7938:                     if ($start == -1) { next; } # deleted from group
                   7939:                     if (($start!=0) && ($start>$now)) { next; }
                   7940:                     if (($end!=0) && ($end<$now)) {
                   7941:                         if ($access_end && $access_end < $now) {
                   7942:                             if ($access_end - $end < 86400) {
                   7943:                                 push(@usersgroups,$group);
1.733     raeburn  7944:                             }
                   7945:                         }
1.817     raeburn  7946:                         next;
1.733     raeburn  7947:                     }
1.817     raeburn  7948:                     push(@usersgroups,$group);
1.683     raeburn  7949:                 }
                   7950:             }
                   7951:         }
1.817     raeburn  7952:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7953:         $grouplist = join(':',@usersgroups);
                   7954:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7955:     }
1.733     raeburn  7956:     return @usersgroups;
1.683     raeburn  7957: }
                   7958: 
                   7959: sub devalidate_getgroups_cache {
                   7960:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7961:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7962: 
1.683     raeburn  7963:     my $hashid="$udom:$uname:$courseid";
                   7964:     &devalidate_cache_new('getgroups',$hashid);
                   7965: }
                   7966: 
1.12      www      7967: # ------------------------------------------------------------------ Plain Text
                   7968: 
                   7969: sub plaintext {
1.988     raeburn  7970:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7971:     if ($short =~ m{^cr/}) {
1.758     albertel 7972: 	return (split('/',$short))[-1];
                   7973:     }
1.742     raeburn  7974:     if (!defined($cid)) {
                   7975:         $cid = $env{'request.course.id'};
                   7976:     }
                   7977:     my %rolenames = (
1.1008    raeburn  7978:                       Course    => 'std',
                   7979:                       Community => 'alt1',
1.742     raeburn  7980:                     );
1.1037    raeburn  7981:     if ($cid ne '') {
                   7982:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7983:             unless ($forcedefault) {
                   7984:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7985:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7986:                 return &Apache::lonlocal::mt($roletext);
                   7987:             }
                   7988:         }
                   7989:     }
                   7990:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7991:         (defined($rolenames{$type})) && 
                   7992:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7993:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7994:     } elsif ($cid ne '') {
                   7995:         my $crstype = $env{'course.'.$cid.'.type'};
                   7996:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7997:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7998:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7999:         }
1.742     raeburn  8000:     }
1.1037    raeburn  8001:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8002: }
                   8003: 
                   8004: # ----------------------------------------------------------------- Assign Role
                   8005: 
                   8006: sub assignrole {
1.957     raeburn  8007:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8008:         $context)=@_;
1.21      www      8009:     my $mrole;
                   8010:     if ($role =~ /^cr\//) {
1.393     www      8011:         my $cwosec=$url;
1.811     albertel 8012:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8013: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8014:            my $refused = 1;
                   8015:            if ($context eq 'requestcourses') {
                   8016:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8017:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8018:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8019:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8020:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8021:                            if ($crsenv{'internal.courseowner'} eq
                   8022:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8023:                                $refused = '';
                   8024:                            }
                   8025:                        }
                   8026:                    }
                   8027:                }
                   8028:            }
                   8029:            if ($refused) {
                   8030:                &logthis('Refused custom assignrole: '.
                   8031:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8032:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8033:                return 'refused';
                   8034:            }
1.104     www      8035:         }
1.21      www      8036:         $mrole='cr';
1.678     raeburn  8037:     } elsif ($role =~ /^gr\//) {
                   8038:         my $cwogrp=$url;
1.811     albertel 8039:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8040:         unless (&allowed('mdg',$cwogrp)) {
                   8041:             &logthis('Refused group assignrole: '.
                   8042:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8043:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8044:             return 'refused';
                   8045:         }
                   8046:         $mrole='gr';
1.21      www      8047:     } else {
1.82      www      8048:         my $cwosec=$url;
1.811     albertel 8049:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8050:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8051:             my $refused;
                   8052:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8053:                 if (!(&allowed('c'.$role,$url))) {
                   8054:                     $refused = 1;
                   8055:                 }
                   8056:             } else {
                   8057:                 $refused = 1;
                   8058:             }
1.947     raeburn  8059:             if ($refused) {
1.1045    raeburn  8060:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8061:                 if (!$selfenroll && $context eq 'course') {
                   8062:                     my %crsenv;
                   8063:                     if ($role eq 'cc' || $role eq 'co') {
                   8064:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8065:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8066:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8067:                                 if ($crsenv{'internal.courseowner'} eq 
                   8068:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8069:                                     $refused = '';
                   8070:                                 }
                   8071:                             }
                   8072:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8073:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8074:                                 if ($crsenv{'internal.courseowner'} eq 
                   8075:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8076:                                     $refused = '';
                   8077:                                 }
                   8078:                             }
                   8079:                         }
                   8080:                     }
                   8081:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8082:                     $refused = '';
1.1017    raeburn  8083:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8084:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8085:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8086:                         my $wrongcc;
                   8087:                         if ($cnum =~ /^$match_community$/) {
                   8088:                             $wrongcc = 1 if ($role eq 'cc');
                   8089:                         } else {
                   8090:                             $wrongcc = 1 if ($role eq 'co');
                   8091:                         }
                   8092:                         unless ($wrongcc) {
                   8093:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8094:                             if ($crsenv{'internal.courseowner'} eq 
                   8095:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8096:                                 $refused = '';
                   8097:                             }
1.1017    raeburn  8098:                         }
                   8099:                     }
1.1183    raeburn  8100:                 } elsif ($context eq 'requestauthor') {
                   8101:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8102:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8103:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8104:                             $refused = '';
                   8105:                         } else {
                   8106:                             my %domdefaults = &get_domain_defaults($udom);
                   8107:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8108:                                 my $checkbystatus;
                   8109:                                 if ($env{'user.adv'}) { 
                   8110:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8111:                                     if ($disposition eq 'automatic') {
                   8112:                                         $refused = '';
                   8113:                                     } elsif ($disposition eq '') {
                   8114:                                         $checkbystatus = 1;
                   8115:                                     } 
                   8116:                                 } else {
                   8117:                                     $checkbystatus = 1;
                   8118:                                 }
                   8119:                                 if ($checkbystatus) {
                   8120:                                     if ($env{'environment.inststatus'}) {
                   8121:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8122:                                         foreach my $type (@inststatuses) {
                   8123:                                             if (($type ne '') &&
                   8124:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8125:                                                 $refused = '';
                   8126:                                             }
                   8127:                                         }
                   8128:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8129:                                         $refused = '';
                   8130:                                     }
                   8131:                                 }
                   8132:                             }
                   8133:                         }
                   8134:                     }
1.1017    raeburn  8135:                 }
                   8136:                 if ($refused) {
1.947     raeburn  8137:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8138:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8139: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8140:                     return 'refused';
                   8141:                 }
1.932     raeburn  8142:             }
1.1131    raeburn  8143:         } elsif ($role eq 'au') {
                   8144:             if ($url ne '/'.$udom.'/') {
                   8145:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8146:                          ' to assign author role for '.$uname.':'.$udom.
                   8147:                          ' in domain: '.$url.' refused (wrong domain).');
                   8148:                 return 'refused';
                   8149:             }
1.104     www      8150:         }
1.21      www      8151:         $mrole=$role;
                   8152:     }
1.620     albertel 8153:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8154:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8155:     if ($end) { $command.='_'.$end; }
1.21      www      8156:     if ($start) {
                   8157: 	if ($end) { 
1.81      www      8158:            $command.='_'.$start; 
1.21      www      8159:         } else {
1.81      www      8160:            $command.='_0_'.$start;
1.21      www      8161:         }
                   8162:     }
1.739     raeburn  8163:     my $origstart = $start;
                   8164:     my $origend = $end;
1.957     raeburn  8165:     my $delflag;
1.357     www      8166: # actually delete
                   8167:     if ($deleteflag) {
1.373     www      8168: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8169: # modify command to delete the role
1.620     albertel 8170:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8171:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8172: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8173: # set start and finish to negative values for userrolelog
                   8174:            $start=-1;
                   8175:            $end=-1;
1.957     raeburn  8176:            $delflag = 1;
1.357     www      8177:         }
                   8178:     }
                   8179: # send command
1.349     www      8180:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8181: # log new user role if status is ok
1.349     www      8182:     if ($answer eq 'ok') {
1.663     raeburn  8183: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8184:         if (($role eq 'cc') || ($role eq 'in') ||
                   8185:             ($role eq 'ep') || ($role eq 'ad') ||
                   8186:             ($role eq 'ta') || ($role eq 'st') ||
                   8187:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8188:             ($role eq 'co')) {
1.1200    raeburn  8189: # for course roles, perform group memberships changes triggered by role change.
                   8190:             unless ($role =~ /^gr/) {
                   8191:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8192:                                                  $origstart,$selfenroll,$context);
                   8193:             }
1.1184    raeburn  8194:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8195:                            $selfenroll,$context);
                   8196:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8197:                  ($role eq 'au') || ($role eq 'dc')) {
                   8198:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8199:                            $context);
                   8200:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8201:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8202:                              $context); 
                   8203:         }
1.1053    raeburn  8204:         if ($role eq 'cc') {
                   8205:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8206:         }
1.349     www      8207:     }
                   8208:     return $answer;
1.169     harris41 8209: }
                   8210: 
1.1053    raeburn  8211: sub autoupdate_coowners {
                   8212:     my ($url,$end,$start,$uname,$udom) = @_;
                   8213:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8214:     if (($cdom ne '') && ($cnum ne '')) {
                   8215:         my $now = time;
                   8216:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8217:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8218:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8219:             my $instcode = $coursehash{'internal.coursecode'};
                   8220:             if ($instcode ne '') {
1.1056    raeburn  8221:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8222:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8223:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8224:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8225:                         if ($result eq 'valid') {
                   8226:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8227:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8228:                                     push(@newcoowners,$coowner);
                   8229:                                 }
                   8230:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8231:                                     push(@newcoowners,$uname.':'.$udom);
                   8232:                                 }
                   8233:                                 @newcoowners = sort(@newcoowners);
                   8234:                             } else {
                   8235:                                 push(@newcoowners,$uname.':'.$udom);
                   8236:                             }
                   8237:                         } else {
                   8238:                             if ($coursehash{'internal.co-owners'}) {
                   8239:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8240:                                     unless ($coowner eq $uname.':'.$udom) {
                   8241:                                         push(@newcoowners,$coowner);
                   8242:                                     }
                   8243:                                 }
                   8244:                                 unless (@newcoowners > 0) {
                   8245:                                     $delcoowners = 1;
                   8246:                                     $coowners = '';
                   8247:                                 }
                   8248:                             }
                   8249:                         }
                   8250:                         if (@newcoowners || $delcoowners) {
                   8251:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8252:                                             $delcoowners,@newcoowners);
                   8253:                         }
                   8254:                     }
                   8255:                 }
                   8256:             }
                   8257:         }
                   8258:     }
                   8259: }
                   8260: 
                   8261: sub store_coowners {
                   8262:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8263:     my $cid = $cdom.'_'.$cnum;
                   8264:     my ($coowners,$delresult,$putresult);
                   8265:     if (@newcoowners) {
                   8266:         $coowners = join(',',@newcoowners);
                   8267:         my %coownershash = (
                   8268:                             'internal.co-owners' => $coowners,
                   8269:                            );
                   8270:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8271:         if ($putresult eq 'ok') {
                   8272:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8273:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8274:             }
                   8275:         }
                   8276:     }
                   8277:     if ($delcoowners) {
                   8278:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8279:         if ($delresult eq 'ok') {
                   8280:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8281:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8282:             }
                   8283:         }
                   8284:     }
                   8285:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8286:         my %crsinfo =
                   8287:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8288:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8289:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8290:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8291:         }
                   8292:     }
                   8293: }
                   8294: 
1.169     harris41 8295: # -------------------------------------------------- Modify user authentication
1.197     www      8296: # Overrides without validation
                   8297: 
1.169     harris41 8298: sub modifyuserauth {
                   8299:     my ($udom,$uname,$umode,$upass)=@_;
                   8300:     my $uhome=&homeserver($uname,$udom);
1.197     www      8301:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8302:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8303:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8304:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8305:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8306: 		     &escape($upass),$uhome);
1.620     albertel 8307:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8308:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8309:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8310:     &log($udom,,$uname,$uhome,
1.620     albertel 8311:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8312:                                      $env{'user.name'}.', '.$umode.
1.197     www      8313:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8314:     unless ($reply eq 'ok') {
1.197     www      8315:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8316: 	return 'error: '.$reply;
                   8317:     }   
1.170     harris41 8318:     return 'ok';
1.80      www      8319: }
                   8320: 
1.81      www      8321: # --------------------------------------------------------------- Modify a user
1.80      www      8322: 
1.81      www      8323: sub modifyuser {
1.206     matthew  8324:     my ($udom,    $uname, $uid,
                   8325:         $umode,   $upass, $first,
                   8326:         $middle,  $last,  $gene,
1.1058    raeburn  8327:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8328:     $udom= &LONCAPA::clean_domain($udom);
                   8329:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8330:     my $showcandelete = 'none';
                   8331:     if (ref($candelete) eq 'ARRAY') {
                   8332:         if (@{$candelete} > 0) {
                   8333:             $showcandelete = join(', ',@{$candelete});
                   8334:         }
                   8335:     }
1.81      www      8336:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8337:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8338: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8339:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8340:                                      ' desiredhome not specified'). 
1.620     albertel 8341:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8342:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8343:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8344:     my $newuser;
                   8345:     if ($uhome eq 'no_host') {
                   8346:         $newuser = 1;
                   8347:     }
1.80      www      8348: # ----------------------------------------------------------------- Create User
1.406     albertel 8349:     if (($uhome eq 'no_host') && 
                   8350: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8351:         my $unhome='';
1.844     albertel 8352:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8353:             $unhome = $desiredhome;
1.620     albertel 8354: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8355: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8356:         } else { # load balancing routine for determining $unhome
1.81      www      8357:             my $loadm=10000000;
1.841     albertel 8358: 	    my %servers = &get_servers($udom,'library');
                   8359: 	    foreach my $tryserver (keys(%servers)) {
                   8360: 		my $answer=reply('load',$tryserver);
                   8361: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8362: 		    $loadm=$answer;
                   8363: 		    $unhome=$tryserver;
                   8364: 		}
1.80      www      8365: 	    }
                   8366:         }
                   8367:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8368: 	    return 'error: unable to find a home server for '.$uname.
                   8369:                    ' in domain '.$udom;
1.80      www      8370:         }
                   8371:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8372:                          &escape($upass),$unhome);
                   8373: 	unless ($reply eq 'ok') {
                   8374:             return 'error: '.$reply;
                   8375:         }   
1.230     stredwic 8376:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8377:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8378: 	    return 'error: unable verify users home machine.';
1.80      www      8379:         }
1.209     matthew  8380:     }   # End of creation of new user
1.80      www      8381: # ---------------------------------------------------------------------- Add ID
                   8382:     if ($uid) {
                   8383:        $uid=~tr/A-Z/a-z/;
                   8384:        my %uidhash=&idrget($udom,$uname);
1.196     www      8385:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8386:          && (!$forceid)) {
1.80      www      8387: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8388: 	      return 'error: user id "'.$uid.'" does not match '.
                   8389:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8390:           }
                   8391:        } else {
                   8392: 	  &idput($udom,($uname => $uid));
                   8393:        }
                   8394:     }
                   8395: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8396:     my @tmp=&get('environment',
1.899     raeburn  8397: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8398:                     'permanentemail','inststatus'],
1.134     albertel 8399: 		   $udom,$uname);
1.1075    raeburn  8400:     my (%names,%oldnames);
1.313     matthew  8401:     if ($tmp[0] =~ m/^error:.*/) { 
                   8402:         %names=(); 
                   8403:     } else {
                   8404:         %names = @tmp;
1.1075    raeburn  8405:         %oldnames = %names;
1.313     matthew  8406:     }
1.388     www      8407: #
1.1058    raeburn  8408: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8409: # of users did not contain them), do not overwrite existing values
                   8410: # unless field is in $candelete array ref.  
                   8411: #
                   8412: 
                   8413:     my @fields = ('firstname','middlename','lastname','generation',
                   8414:                   'permanentemail','id');
                   8415:     my %newvalues;
                   8416:     if (ref($candelete) eq 'ARRAY') {
                   8417:         foreach my $field (@fields) {
                   8418:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8419:                 if ($field eq 'firstname') {
                   8420:                     $names{$field} = $first;
                   8421:                 } elsif ($field eq 'middlename') {
                   8422:                     $names{$field} = $middle;
                   8423:                 } elsif ($field eq 'lastname') {
                   8424:                     $names{$field} = $last;
                   8425:                 } elsif ($field eq 'generation') { 
                   8426:                     $names{$field} = $gene;
                   8427:                 } elsif ($field eq 'permanentemail') {
                   8428:                     $names{$field} = $email;
                   8429:                 } elsif ($field eq 'id') {
                   8430:                     $names{$field}  = $uid;
                   8431:                 }
                   8432:             }
                   8433:         }
                   8434:     }
1.388     www      8435:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8436:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8437:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8438:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8439:     if ($email) {
                   8440:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8441:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8442:     }
1.899     raeburn  8443:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8444:     if (defined($inststatus)) {
                   8445:         $names{'inststatus'} = '';
                   8446:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8447:         if (ref($usertypes) eq 'HASH') {
                   8448:             my @okstatuses; 
                   8449:             foreach my $item (split(/:/,$inststatus)) {
                   8450:                 if (defined($usertypes->{$item})) {
                   8451:                     push(@okstatuses,$item);  
                   8452:                 }
                   8453:             }
                   8454:             if (@okstatuses) {
                   8455:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8456:             }
                   8457:         }
                   8458:     }
1.1075    raeburn  8459:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8460:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8461:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8462:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8463:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8464:     } else {
                   8465:         $logmsg .= ' during self creation';
                   8466:     }
1.1075    raeburn  8467:     my $changed;
                   8468:     if ($newuser) {
                   8469:         $changed = 1;
                   8470:     } else {
                   8471:         foreach my $field (@fields) {
                   8472:             if ($names{$field} ne $oldnames{$field}) {
                   8473:                 $changed = 1;
                   8474:                 last;
                   8475:             }
                   8476:         }
                   8477:     }
                   8478:     unless ($changed) {
                   8479:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8480:         &logthis($logmsg);
                   8481:         return 'ok';
                   8482:     }
                   8483:     my $reply = &put('environment', \%names, $udom,$uname);
                   8484:     if ($reply ne 'ok') { 
                   8485:         return 'error: '.$reply;
                   8486:     }
1.1087    raeburn  8487:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8488:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8489:     }
1.1075    raeburn  8490:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8491:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8492:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8493:     &logthis($logmsg);
1.134     albertel 8494:     return 'ok';
1.80      www      8495: }
                   8496: 
1.81      www      8497: # -------------------------------------------------------------- Modify student
1.80      www      8498: 
1.81      www      8499: sub modifystudent {
                   8500:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8501:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8502:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8503:     if (!$cid) {
1.620     albertel 8504: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8505: 	    return 'not_in_class';
                   8506: 	}
1.80      www      8507:     }
                   8508: # --------------------------------------------------------------- Make the user
1.81      www      8509:     my $reply=&modifyuser
1.209     matthew  8510: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8511:          $desiredhome,$email,$inststatus);
1.80      www      8512:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8513:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8514:     # student's environment
1.297     matthew  8515:     $uid = undef if (!$forceid);
1.455     albertel 8516:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8517:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8518:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8519:     return $reply;
                   8520: }
                   8521: 
                   8522: sub modify_student_enrollment {
1.1216    raeburn  8523:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8524:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8525:     my ($cdom,$cnum,$chome);
                   8526:     if (!$cid) {
1.620     albertel 8527: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8528: 	    return 'not_in_class';
                   8529: 	}
1.620     albertel 8530: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8531: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8532:     } else {
                   8533: 	($cdom,$cnum)=split(/_/,$cid);
                   8534:     }
1.620     albertel 8535:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8536:     if (!$chome) {
1.457     raeburn  8537: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8538:     }
1.455     albertel 8539:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8540:     # Make sure the user exists
1.81      www      8541:     my $uhome=&homeserver($uname,$udom);
                   8542:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8543: 	return 'error: no such user';
                   8544:     }
1.297     matthew  8545:     # Get student data if we were not given enough information
                   8546:     if (!defined($first)  || $first  eq '' || 
                   8547:         !defined($last)   || $last   eq '' || 
                   8548:         !defined($uid)    || $uid    eq '' || 
                   8549:         !defined($middle) || $middle eq '' || 
                   8550:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8551:         # They did not supply us with enough data to enroll the student, so
                   8552:         # we need to pick up more information.
1.297     matthew  8553:         my %tmp = &get('environment',
1.294     matthew  8554:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8555:                        ,$udom,$uname);
                   8556: 
1.800     albertel 8557:         #foreach my $key (keys(%tmp)) {
                   8558:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8559:         #}
1.294     matthew  8560:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8561:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8562:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8563:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8564:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8565:     }
1.556     albertel 8566:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8567:     my $user = "$uname:$udom";
                   8568:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8569:     my $reply=cput('classlist',
1.1148    raeburn  8570: 		   {$user => 
1.1216    raeburn  8571: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8572: 		   $cdom,$cnum);
1.1148    raeburn  8573:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8574:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8575:     } else { 
1.81      www      8576: 	return 'error: '.$reply;
                   8577:     }
1.297     matthew  8578:     # Add student role to user
1.83      www      8579:     my $uurl='/'.$cid;
1.81      www      8580:     $uurl=~s/\_/\//g;
                   8581:     if ($usec) {
                   8582: 	$uurl.='/'.$usec;
                   8583:     }
1.1148    raeburn  8584:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8585:                              $selfenroll,$context);
                   8586:     if ($result ne 'ok') {
                   8587:         if ($old_entry{$user} ne '') {
                   8588:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8589:         } else {
                   8590:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8591:         }
                   8592:     }
                   8593:     return $result; 
1.21      www      8594: }
                   8595: 
1.556     albertel 8596: sub format_name {
                   8597:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8598:     my $name;
                   8599:     if ($first ne 'lastname') {
                   8600: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8601:     } else {
                   8602: 	if ($lastname=~/\S/) {
                   8603: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8604: 	    $name=~s/\s+,/,/;
                   8605: 	} else {
                   8606: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8607: 	}
                   8608:     }
                   8609:     $name=~s/^\s+//;
                   8610:     $name=~s/\s+$//;
                   8611:     $name=~s/\s+/ /g;
                   8612:     return $name;
                   8613: }
                   8614: 
1.84      www      8615: # ------------------------------------------------- Write to course preferences
                   8616: 
                   8617: sub writecoursepref {
                   8618:     my ($courseid,%prefs)=@_;
                   8619:     $courseid=~s/^\///;
                   8620:     $courseid=~s/\_/\//g;
                   8621:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8622:     my $chome=homeserver($cnum,$cdomain);
                   8623:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8624: 	return 'error: no such course';
                   8625:     }
                   8626:     my $cstring='';
1.800     albertel 8627:     foreach my $pref (keys(%prefs)) {
                   8628: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8629:     }
1.84      www      8630:     $cstring=~s/\&$//;
                   8631:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8632: }
                   8633: 
                   8634: # ---------------------------------------------------------- Make/modify course
                   8635: 
                   8636: sub createcourse {
1.741     raeburn  8637:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8638:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8639:     $url=&declutter($url);
                   8640:     my $cid='';
1.1028    raeburn  8641:     if ($context eq 'requestcourses') {
                   8642:         my $can_create = 0;
                   8643:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8644:         if ($udom eq $ownerdom) {
                   8645:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8646:                                   $context)) {
                   8647:                 $can_create = 1;
                   8648:             }
                   8649:         } else {
                   8650:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8651:                                            $category);
                   8652:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8653:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8654:                 if (@curr > 0) {
                   8655:                     my @options = qw(approval validate autolimit);
                   8656:                     my $optregex = join('|',@options);
                   8657:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8658:                         $can_create = 1;
                   8659:                     }
                   8660:                 }
                   8661:             }
                   8662:         }
                   8663:         if ($can_create) {
                   8664:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8665:                 unless (&allowed('ccc',$udom)) {
                   8666:                     return 'refused'; 
                   8667:                 }
1.1017    raeburn  8668:             }
                   8669:         } else {
                   8670:             return 'refused';
                   8671:         }
1.1028    raeburn  8672:     } elsif (!&allowed('ccc',$udom)) {
                   8673:         return 'refused';
1.84      www      8674:     }
1.1011    raeburn  8675: # --------------------------------------------------------------- Get Unique ID
                   8676:     my $uname;
                   8677:     if ($cnum =~ /^$match_courseid$/) {
                   8678:         my $chome=&homeserver($cnum,$udom,'true');
                   8679:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8680:             $uname = $cnum;
                   8681:         } else {
1.1038    raeburn  8682:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8683:         }
                   8684:     } else {
1.1038    raeburn  8685:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8686:     }
                   8687:     return $uname if ($uname =~ /^error/);
                   8688: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8689:     if (!defined($course_server)) {
                   8690:         if (defined(&domain($udom,'primary'))) {
                   8691:             $course_server = &domain($udom,'primary');
                   8692:         } else {
                   8693:             $course_server = $env{'user.home'}; 
                   8694:         }
                   8695:     }
                   8696:     my %host_servers =
                   8697:         &Apache::lonnet::get_servers($udom,'library');
                   8698:     unless ($host_servers{$course_server}) {
                   8699:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8700:     }
1.84      www      8701: # ------------------------------------------------------------- Make the course
                   8702:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8703:                       $course_server);
1.84      www      8704:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8705:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8706:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8707: 	return 'error: no such course';
                   8708:     }
1.271     www      8709: # ----------------------------------------------------------------- Course made
1.516     raeburn  8710: # log existence
1.1029    raeburn  8711:     my $now = time;
1.918     raeburn  8712:     my $newcourse = {
                   8713:                     $udom.'_'.$uname => {
1.921     raeburn  8714:                                      description => $description,
                   8715:                                      inst_code   => $inst_code,
                   8716:                                      owner       => $course_owner,
                   8717:                                      type        => $crstype,
1.1029    raeburn  8718:                                      creator     => $env{'user.name'}.':'.
                   8719:                                                     $env{'user.domain'},
                   8720:                                      created     => $now,
                   8721:                                      context     => $context,
1.918     raeburn  8722:                                                 },
                   8723:                     };
1.921     raeburn  8724:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8725: # set toplevel url
1.271     www      8726:     my $topurl=$url;
                   8727:     unless ($nonstandard) {
                   8728: # ------------------------------------------ For standard courses, make top url
                   8729:         my $mapurl=&clutter($url);
1.278     www      8730:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8731:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8732: <map>
                   8733: <resource id="1" type="start"></resource>
                   8734: <resource id="2" src="$mapurl"></resource>
                   8735: <resource id="3" type="finish"></resource>
                   8736: <link index="1" from="1" to="2"></link>
                   8737: <link index="2" from="2" to="3"></link>
                   8738: </map>
                   8739: ENDINITMAP
                   8740:         $topurl=&declutter(
1.638     albertel 8741:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8742:                           );
                   8743:     }
                   8744: # ----------------------------------------------------------- Write preferences
1.84      www      8745:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8746:                      ('description'              => $description,
                   8747:                       'url'                      => $topurl,
                   8748:                       'internal.creator'         => $env{'user.name'}.':'.
                   8749:                                                     $env{'user.domain'},
                   8750:                       'internal.created'         => $now,
                   8751:                       'internal.creationcontext' => $context)
                   8752:                     );
1.84      www      8753:     return '/'.$udom.'/'.$uname;
                   8754: }
                   8755: 
1.1011    raeburn  8756: # ------------------------------------------------------------------- Create ID
                   8757: sub generate_coursenum {
1.1038    raeburn  8758:     my ($udom,$crstype) = @_;
1.1011    raeburn  8759:     my $domdesc = &domain($udom);
                   8760:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8761:     my $first;
                   8762:     if ($crstype eq 'Community') {
                   8763:         $first = '0';
                   8764:     } else {
                   8765:         $first = int(1+rand(9)); 
                   8766:     } 
                   8767:     my $uname=$first.
1.1011    raeburn  8768:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8769:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8770:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8771: # ----------------------------------------------- Make sure that does not exist
                   8772:     my $uhome=&homeserver($uname,$udom,'true');
                   8773:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8774:         if ($crstype eq 'Community') {
                   8775:             $first = '0';
                   8776:         } else {
                   8777:             $first = int(1+rand(9));
                   8778:         }
                   8779:         $uname=$first.
1.1011    raeburn  8780:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8781:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8782:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8783:         $uhome=&homeserver($uname,$udom,'true');
                   8784:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8785:             return 'error: unable to generate unique course-ID';
                   8786:         }
                   8787:     }
                   8788:     return $uname;
                   8789: }
                   8790: 
1.813     albertel 8791: sub is_course {
1.1167    droeschl 8792:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8793:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8794: 
                   8795:     return unless $cdom and $cnum;
                   8796: 
                   8797:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8798:         '.');
                   8799: 
1.1219    raeburn  8800:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8801:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8802: }
                   8803: 
1.1015    raeburn  8804: sub store_userdata {
                   8805:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8806:     my $result;
1.1016    raeburn  8807:     if ($datakey ne '') {
1.1013    raeburn  8808:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8809:             if ($udom eq '' || $uname eq '') {
                   8810:                 $udom = $env{'user.domain'};
                   8811:                 $uname = $env{'user.name'};
                   8812:             }
                   8813:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8814:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8815:                 $result = 'error: no_host';
                   8816:             } else {
                   8817:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8818:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8819: 
                   8820:                 my $namevalue='';
                   8821:                 foreach my $key (keys(%{$storehash})) {
                   8822:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8823:                 }
                   8824:                 $namevalue=~s/\&$//;
1.1224    raeburn  8825:                 unless ($namespace eq 'courserequests') {
                   8826:                     $datakey = &escape($datakey);
                   8827:                 }
1.1105    raeburn  8828:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8829:                                   $namevalue,$uhome);
1.1013    raeburn  8830:             }
                   8831:         } else {
                   8832:             $result = 'error: data to store was not a hash reference'; 
                   8833:         }
                   8834:     } else {
                   8835:         $result= 'error: invalid requestkey'; 
                   8836:     }
                   8837:     return $result;
                   8838: }
                   8839: 
1.21      www      8840: # ---------------------------------------------------------- Assign Custom Role
                   8841: 
                   8842: sub assigncustomrole {
1.957     raeburn  8843:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8844:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8845:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8846: }
                   8847: 
                   8848: # ----------------------------------------------------------------- Revoke Role
                   8849: 
                   8850: sub revokerole {
1.957     raeburn  8851:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8852:     my $now=time;
1.965     raeburn  8853:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8854: }
                   8855: 
                   8856: # ---------------------------------------------------------- Revoke Custom Role
                   8857: 
                   8858: sub revokecustomrole {
1.957     raeburn  8859:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8860:     my $now=time;
1.357     www      8861:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8862:            $deleteflag,$selfenroll,$context);
1.17      www      8863: }
                   8864: 
1.533     banghart 8865: # ------------------------------------------------------------ Disk usage
1.535     albertel 8866: sub diskusage {
1.955     raeburn  8867:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8868:     $directorypath =~ s/\/$//;
                   8869:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8870:                        .&escape($getpropath).':'.&escape($uname).':'
                   8871:                        .&escape($udom),homeserver($uname,$udom));
                   8872:     if ($listing eq 'unknown_cmd') {
                   8873:         if ($getpropath) {
                   8874:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8875:         }
                   8876:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8877:     }
1.514     albertel 8878:     return $listing;
1.512     banghart 8879: }
                   8880: 
1.566     banghart 8881: sub is_locked {
1.1096    raeburn  8882:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8883:     my @check;
                   8884:     my $is_locked;
1.1093    raeburn  8885:     push (@check,$file_name);
1.613     albertel 8886:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8887: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8888:     my ($tmp)=keys(%locked);
                   8889:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8890:     
1.566     banghart 8891:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8892:         $is_locked = 'false';
                   8893:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8894:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8895:                $is_locked = 'true';
1.1096    raeburn  8896:                if (ref($which) eq 'ARRAY') {
                   8897:                    push(@{$which},$entry);
                   8898:                } else {
                   8899:                    last;
                   8900:                }
1.745     raeburn  8901:            }
                   8902:        }
1.566     banghart 8903:     } else {
                   8904:         $is_locked = 'false';
                   8905:     }
1.1093    raeburn  8906:     return $is_locked;
1.566     banghart 8907: }
                   8908: 
1.759     albertel 8909: sub declutter_portfile {
                   8910:     my ($file) = @_;
1.833     albertel 8911:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8912:     return $file;
                   8913: }
                   8914: 
1.559     banghart 8915: # ------------------------------------------------------------- Mark as Read Only
                   8916: 
                   8917: sub mark_as_readonly {
                   8918:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8919:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8920:     my ($tmp)=keys(%current_permissions);
                   8921:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8922:     foreach my $file (@{$files}) {
1.759     albertel 8923: 	$file = &declutter_portfile($file);
1.561     banghart 8924:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8925:     }
1.613     albertel 8926:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8927:     return;
                   8928: }
                   8929: 
1.572     banghart 8930: # ------------------------------------------------------------Save Selected Files
                   8931: 
                   8932: sub save_selected_files {
                   8933:     my ($user, $path, @files) = @_;
                   8934:     my $filename = $user."savedfiles";
1.573     banghart 8935:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8936:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8937:     foreach my $file (@files) {
1.620     albertel 8938:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8939:     }
                   8940:     foreach my $file (@other_files) {
1.574     banghart 8941:         print (OUT $file."\n");
1.572     banghart 8942:     }
1.574     banghart 8943:     close (OUT);
1.572     banghart 8944:     return 'ok';
                   8945: }
                   8946: 
1.574     banghart 8947: sub clear_selected_files {
                   8948:     my ($user) = @_;
                   8949:     my $filename = $user."savedfiles";
1.1117    foxr     8950:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8951:     print (OUT undef);
                   8952:     close (OUT);
                   8953:     return ("ok");    
                   8954: }
                   8955: 
1.572     banghart 8956: sub files_in_path {
                   8957:     my ($user, $path) = @_;
                   8958:     my $filename = $user."savedfiles";
                   8959:     my %return_files;
1.1117    foxr     8960:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8961:     while (my $line_in = <IN>) {
1.574     banghart 8962:         chomp ($line_in);
                   8963:         my @paths_and_file = split (m!/!, $line_in);
                   8964:         my $file_part = pop (@paths_and_file);
                   8965:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8966:         $path_part.='/';
                   8967:         my $path_and_file = $path_part.$file_part;
                   8968:         if ($path_part eq $path) {
                   8969:             $return_files{$file_part}= 'selected';
                   8970:         }
                   8971:     }
1.574     banghart 8972:     close (IN);
                   8973:     return (\%return_files);
1.572     banghart 8974: }
                   8975: 
                   8976: # called in portfolio select mode, to show files selected NOT in current directory
                   8977: sub files_not_in_path {
                   8978:     my ($user, $path) = @_;
                   8979:     my $filename = $user."savedfiles";
                   8980:     my @return_files;
                   8981:     my $path_part;
1.1117    foxr     8982:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8983:     while (my $line = <IN>) {
1.572     banghart 8984:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8985:         my @paths_and_file = split(m|/|, $line);
                   8986:         my $file_part = pop(@paths_and_file);
                   8987:         chomp($file_part);
                   8988:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8989:         $path_part .= '/';
                   8990:         my $path_and_file = $path_part.$file_part;
                   8991:         if ($path_part ne $path) {
1.800     albertel 8992:             push(@return_files, ($path_and_file));
1.572     banghart 8993:         }
                   8994:     }
1.800     albertel 8995:     close(OUT);
1.574     banghart 8996:     return (@return_files);
1.572     banghart 8997: }
                   8998: 
1.745     raeburn  8999: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9000: 
1.745     raeburn  9001: sub get_portfile_permissions {
                   9002:     my ($domain,$user) = @_;
1.613     albertel 9003:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9004:     my ($tmp)=keys(%current_permissions);
                   9005:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9006:     return \%current_permissions;
                   9007: }
                   9008: 
                   9009: #---------------------------------------------Get portfolio file access controls
                   9010: 
1.749     raeburn  9011: sub get_access_controls {
1.745     raeburn  9012:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9013:     my %access;
                   9014:     my $real_file = $file;
                   9015:     $file =~ s/\.meta$//;
1.745     raeburn  9016:     if (defined($file)) {
1.749     raeburn  9017:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9018:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9019:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9020:             }
                   9021:         }
1.745     raeburn  9022:     } else {
1.749     raeburn  9023:         foreach my $key (keys(%{$current_permissions})) {
                   9024:             if ($key =~ /\0accesscontrol$/) {
                   9025:                 if (defined($group)) {
                   9026:                     if ($key !~ m-^\Q$group\E/-) {
                   9027:                         next;
                   9028:                     }
                   9029:                 }
                   9030:                 my ($fullpath) = split(/\0/,$key);
                   9031:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9032:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9033:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9034:                     }
                   9035:                 }
                   9036:             }
                   9037:         }
                   9038:     }
                   9039:     return %access;
                   9040: }
                   9041: 
                   9042: sub modify_access_controls {
                   9043:     my ($file_name,$changes,$domain,$user)=@_;
                   9044:     my ($outcome,$deloutcome);
                   9045:     my %store_permissions;
                   9046:     my %new_values;
                   9047:     my %new_control;
                   9048:     my %translation;
                   9049:     my @deletions = ();
                   9050:     my $now = time;
                   9051:     if (exists($$changes{'activate'})) {
                   9052:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9053:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9054:             my $numnew = scalar(@newitems);
                   9055:             for (my $i=0; $i<$numnew; $i++) {
                   9056:                 my $newkey = $newitems[$i];
                   9057:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9058:                 if ($newkey =~ /^\d+:/) { 
                   9059:                     $newkey =~ s/^(\d+)/$newid/;
                   9060:                     $translation{$1} = $newid;
                   9061:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9062:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9063:                     $translation{$1} = $newid;
                   9064:                 }
1.749     raeburn  9065:                 $new_values{$file_name."\0".$newkey} = 
                   9066:                                           $$changes{'activate'}{$newitems[$i]};
                   9067:                 $new_control{$newkey} = $now;
                   9068:             }
                   9069:         }
                   9070:     }
                   9071:     my %todelete;
                   9072:     my %changed_items;
                   9073:     foreach my $action ('delete','update') {
                   9074:         if (exists($$changes{$action})) {
                   9075:             if (ref($$changes{$action}) eq 'HASH') {
                   9076:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9077:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9078:                     if ($action eq 'delete') { 
                   9079:                         $todelete{$itemnum} = 1;
                   9080:                     } else {
                   9081:                         $changed_items{$itemnum} = $key;
                   9082:                     }
                   9083:                 }
1.745     raeburn  9084:             }
                   9085:         }
1.749     raeburn  9086:     }
                   9087:     # get lock on access controls for file.
                   9088:     my $lockhash = {
                   9089:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9090:                                                        ':'.$env{'user.domain'},
                   9091:                    }; 
                   9092:     my $tries = 0;
                   9093:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9094:    
                   9095:     while (($gotlock ne 'ok') && $tries <3) {
                   9096:         $tries ++;
                   9097:         sleep 1;
                   9098:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9099:     }
                   9100:     if ($gotlock eq 'ok') {
                   9101:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9102:         my ($tmp)=keys(%curr_permissions);
                   9103:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9104:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9105:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9106:             if (ref($curr_controls) eq 'HASH') {
                   9107:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9108:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9109:                     if (defined($todelete{$itemnum})) {
                   9110:                         push(@deletions,$file_name."\0".$control_item);
                   9111:                     } else {
                   9112:                         if (defined($changed_items{$itemnum})) {
                   9113:                             $new_control{$changed_items{$itemnum}} = $now;
                   9114:                             push(@deletions,$file_name."\0".$control_item);
                   9115:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9116:                         } else {
                   9117:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9118:                         }
                   9119:                     }
1.745     raeburn  9120:                 }
                   9121:             }
                   9122:         }
1.970     raeburn  9123:         my ($group);
                   9124:         if (&is_course($domain,$user)) {
                   9125:             ($group,my $file) = split(/\//,$file_name,2);
                   9126:         }
1.749     raeburn  9127:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9128:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9129:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9130:         #  remove lock
                   9131:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9132:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9133:         my $sqlresult =
1.970     raeburn  9134:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9135:                                     $group);
1.749     raeburn  9136:     } else {
                   9137:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9138:     }
1.749     raeburn  9139:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9140: }
                   9141: 
1.827     raeburn  9142: sub make_public_indefinitely {
                   9143:     my ($requrl) = @_;
                   9144:     my $now = time;
                   9145:     my $action = 'activate';
                   9146:     my $aclnum = 0;
                   9147:     if (&is_portfolio_url($requrl)) {
                   9148:         my (undef,$udom,$unum,$file_name,$group) =
                   9149:             &parse_portfolio_url($requrl);
                   9150:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9151:         my %access_controls = &get_access_controls($current_perms,
                   9152:                                                    $group,$file_name);
                   9153:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9154:             my ($num,$scope,$end,$start) = 
                   9155:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9156:             if ($scope eq 'public') {
                   9157:                 if ($start <= $now && $end == 0) {
                   9158:                     $action = 'none';
                   9159:                 } else {
                   9160:                     $action = 'update';
                   9161:                     $aclnum = $num;
                   9162:                 }
                   9163:                 last;
                   9164:             }
                   9165:         }
                   9166:         if ($action eq 'none') {
                   9167:              return 'ok';
                   9168:         } else {
                   9169:             my %changes;
                   9170:             my $newend = 0;
                   9171:             my $newstart = $now;
                   9172:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9173:             $changes{$action}{$newkey} = {
                   9174:                 type => 'public',
                   9175:                 time => {
                   9176:                     start => $newstart,
                   9177:                     end   => $newend,
                   9178:                 },
                   9179:             };
                   9180:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9181:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9182:             return $outcome;
                   9183:         }
                   9184:     } else {
                   9185:         return 'invalid';
                   9186:     }
                   9187: }
                   9188: 
1.745     raeburn  9189: #------------------------------------------------------Get Marked as Read Only
                   9190: 
                   9191: sub get_marked_as_readonly {
                   9192:     my ($domain,$user,$what,$group) = @_;
                   9193:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9194:     my @readonly_files;
1.629     banghart 9195:     my $cmp1=$what;
                   9196:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9197:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9198:         if (defined($group)) {
                   9199:             if ($file_name !~ m-^\Q$group\E/-) {
                   9200:                 next;
                   9201:             }
                   9202:         }
1.561     banghart 9203:         if (ref($value) eq "ARRAY"){
                   9204:             foreach my $stored_what (@{$value}) {
1.629     banghart 9205:                 my $cmp2=$stored_what;
1.759     albertel 9206:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9207:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9208:                 }
1.629     banghart 9209:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9210:                     push(@readonly_files, $file_name);
1.745     raeburn  9211:                     last;
1.563     banghart 9212:                 } elsif (!defined($what)) {
                   9213:                     push(@readonly_files, $file_name);
1.745     raeburn  9214:                     last;
1.561     banghart 9215:                 }
                   9216:             }
1.745     raeburn  9217:         }
1.561     banghart 9218:     }
                   9219:     return @readonly_files;
                   9220: }
1.577     banghart 9221: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9222: 
1.577     banghart 9223: sub get_marked_as_readonly_hash {
1.745     raeburn  9224:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9225:     my %readonly_files;
1.745     raeburn  9226:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9227:         if (defined($group)) {
                   9228:             if ($file_name !~ m-^\Q$group\E/-) {
                   9229:                 next;
                   9230:             }
                   9231:         }
1.577     banghart 9232:         if (ref($value) eq "ARRAY"){
                   9233:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9234:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9235:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9236:                         if ($lock_descriptor eq 'graded') {
                   9237:                             $readonly_files{$file_name} = 'graded';
                   9238:                         } elsif ($lock_descriptor eq 'handback') {
                   9239:                             $readonly_files{$file_name} = 'handback';
                   9240:                         } else {
                   9241:                             if (!exists($readonly_files{$file_name})) {
                   9242:                                 $readonly_files{$file_name} = 'locked';
                   9243:                             }
                   9244:                         }
1.745     raeburn  9245:                     }
1.750     banghart 9246:                 } 
1.577     banghart 9247:             }
                   9248:         } 
                   9249:     }
                   9250:     return %readonly_files;
                   9251: }
1.559     banghart 9252: # ------------------------------------------------------------ Unmark as Read Only
                   9253: 
                   9254: sub unmark_as_readonly {
1.629     banghart 9255:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9256:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9257:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9258:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9259:     my $symb_crs = $what;
                   9260:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9261:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9262:     my ($tmp)=keys(%current_permissions);
                   9263:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9264:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9265:     foreach my $file (@readonly_files) {
1.759     albertel 9266: 	my $clean_file = &declutter_portfile($file);
                   9267: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9268: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9269:         my @new_locks;
                   9270:         my @del_keys;
                   9271:         if (ref($current_locks) eq "ARRAY"){
                   9272:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9273:                 my $compare=$locker;
1.749     raeburn  9274:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9275:                     $compare=join('',@{$locker});
1.746     raeburn  9276:                     if ($compare ne $symb_crs) {
                   9277:                         push(@new_locks, $locker);
                   9278:                     }
1.563     banghart 9279:                 }
                   9280:             }
1.650     albertel 9281:             if (scalar(@new_locks) > 0) {
1.563     banghart 9282:                 $current_permissions{$file} = \@new_locks;
                   9283:             } else {
                   9284:                 push(@del_keys, $file);
1.613     albertel 9285:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9286:                 delete($current_permissions{$file});
1.563     banghart 9287:             }
                   9288:         }
1.561     banghart 9289:     }
1.613     albertel 9290:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9291:     return;
                   9292: }
1.512     banghart 9293: 
1.17      www      9294: # ------------------------------------------------------------ Directory lister
                   9295: 
                   9296: sub dirlist {
1.955     raeburn  9297:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9298:     $uri=~s/^\///;
                   9299:     $uri=~s/\/$//;
1.253     stredwic 9300:     my ($udom, $uname);
1.955     raeburn  9301:     if ($getuserdir) {
1.253     stredwic 9302:         $udom = $userdomain;
                   9303:         $uname = $username;
1.955     raeburn  9304:     } else {
                   9305:         (undef,$udom,$uname)=split(/\//,$uri);
                   9306:         if(defined($userdomain)) {
                   9307:             $udom = $userdomain;
                   9308:         }
                   9309:         if(defined($username)) {
                   9310:             $uname = $username;
                   9311:         }
1.253     stredwic 9312:     }
1.955     raeburn  9313:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9314: 
1.955     raeburn  9315:     $dirRoot = $perlvar{'lonDocRoot'};
                   9316:     if (defined($getpropath)) {
                   9317:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9318:         $dirRoot =~ s/\/$//;
1.955     raeburn  9319:     } elsif (defined($getuserdir)) {
                   9320:         my $subdir=$uname.'__';
                   9321:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9322:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9323:                    ."/$udom/$subdir/$uname";
                   9324:     } elsif (defined($alternateRoot)) {
                   9325:         $dirRoot = $alternateRoot;
1.751     banghart 9326:     }
1.253     stredwic 9327: 
                   9328:     if($udom) {
                   9329:         if($uname) {
1.1135    raeburn  9330:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9331:             if ($uhome eq 'no_host') {
                   9332:                 return ([],'no_host');
                   9333:             }
1.955     raeburn  9334:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9335:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9336:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9337:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9338:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9339:             } else {
                   9340:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9341:             }
1.605     matthew  9342:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9343:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9344:                 @listing_results = split(/:/,$listing);
                   9345:             } else {
                   9346:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9347:             }
1.1135    raeburn  9348:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9349:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9350:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9351:                 return ([],$listing);
                   9352:             } else {
                   9353:                 return (\@listing_results);
1.1135    raeburn  9354:             }
1.955     raeburn  9355:         } elsif(!$alternateRoot) {
1.1136    raeburn  9356:             my (%allusers,%listerror);
1.841     albertel 9357: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9358:  	    foreach my $tryserver (keys(%servers)) {
                   9359:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9360:                                   &escape($udom),$tryserver);
                   9361:                 if ($listing eq 'unknown_cmd') {
                   9362: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9363: 				      $udom, $tryserver);
                   9364:                 } else {
                   9365:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9366:                 }
1.841     albertel 9367: 		if ($listing eq 'unknown_cmd') {
                   9368: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9369: 				      $udom, $tryserver);
                   9370: 		    @listing_results = split(/:/,$listing);
                   9371: 		} else {
                   9372: 		    @listing_results =
                   9373: 			map { &unescape($_); } split(/:/,$listing);
                   9374: 		}
1.1136    raeburn  9375:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9376:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9377:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9378:                     $listerror{$tryserver} = $listing;
                   9379:                 } else {
1.841     albertel 9380: 		    foreach my $line (@listing_results) {
                   9381: 			my ($entry) = split(/&/,$line,2);
                   9382: 			$allusers{$entry} = 1;
                   9383: 		    }
                   9384: 		}
1.253     stredwic 9385:             }
1.1136    raeburn  9386:             my @alluserslist=();
1.800     albertel 9387:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9388:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9389:             }
1.1136    raeburn  9390:             return (\@alluserslist);
1.253     stredwic 9391:         } else {
1.1136    raeburn  9392:             return ([],'missing username');
1.253     stredwic 9393:         }
1.955     raeburn  9394:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9395:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9396:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9397:         return (\@all_domains);
1.955     raeburn  9398:     } else {
1.1136    raeburn  9399:         return ([],'missing domain');
1.275     stredwic 9400:     }
                   9401: }
                   9402: 
                   9403: # --------------------------------------------- GetFileTimestamp
                   9404: # This function utilizes dirlist and returns the date stamp for
                   9405: # when it was last modified.  It will also return an error of -1
                   9406: # if an error occurs
                   9407: 
                   9408: sub GetFileTimestamp {
1.955     raeburn  9409:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9410:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9411:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9412:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9413:                                     undef,$getuserdir);
                   9414:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9415:         return -1;
                   9416:     }
                   9417:     if (ref($fileref) eq 'ARRAY') {
                   9418:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9419:         # @stats contains first the filename, then the stat output
                   9420:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9421:     } else {
                   9422:         return -1;
1.253     stredwic 9423:     }
1.26      www      9424: }
                   9425: 
1.712     albertel 9426: sub stat_file {
                   9427:     my ($uri) = @_;
1.787     albertel 9428:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9429: 
1.955     raeburn  9430:     my ($udom,$uname,$file);
1.712     albertel 9431:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9432: 	($udom,$uname,$file) =
1.811     albertel 9433: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9434: 	$file = 'userfiles/'.$file;
                   9435:     }
                   9436:     if ($uri =~ m-^/res/-) {
                   9437: 	($udom,$uname) = 
1.807     albertel 9438: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9439: 	$file = $uri;
                   9440:     }
                   9441: 
                   9442:     if (!$udom || !$uname || !$file) {
                   9443: 	# unable to handle the uri
                   9444: 	return ();
                   9445:     }
1.956     raeburn  9446:     my $getpropath;
                   9447:     if ($file =~ /^userfiles\//) {
                   9448:         $getpropath = 1;
                   9449:     }
1.1136    raeburn  9450:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9451:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9452:         return ();
                   9453:     } else {
                   9454:         if (ref($listref) eq 'ARRAY') {
                   9455:             my @stats = split('&',$listref->[0]);
                   9456: 	    shift(@stats); #filename is first
                   9457: 	    return @stats;
                   9458:         }
1.712     albertel 9459:     }
                   9460:     return ();
                   9461: }
                   9462: 
1.26      www      9463: # -------------------------------------------------------- Value of a Condition
                   9464: 
1.713     albertel 9465: # gets the value of a specific preevaluated condition
                   9466: #    stored in the string  $env{user.state.<cid>}
                   9467: # or looks up a condition reference in the bighash and if if hasn't
                   9468: # already been evaluated recurses into docondval to get the value of
                   9469: # the condition, then memoizing it to 
                   9470: #   $env{user.state.<cid>.<condition>}
1.40      www      9471: sub directcondval {
                   9472:     my $number=shift;
1.620     albertel 9473:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9474: 	&Apache::lonuserstate::evalstate();
                   9475:     }
1.713     albertel 9476:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9477: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9478:     } elsif ($number =~ /^_/) {
                   9479: 	my $sub_condition;
                   9480: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9481: 		&GDBM_READER(),0640)) {
                   9482: 	    $sub_condition=$bighash{'conditions'.$number};
                   9483: 	    untie(%bighash);
                   9484: 	}
                   9485: 	my $value = &docondval($sub_condition);
1.949     raeburn  9486: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9487: 	return $value;
                   9488:     }
1.620     albertel 9489:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9490:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9491:     } else {
                   9492:        return 2;
                   9493:     }
                   9494: }
                   9495: 
1.713     albertel 9496: # get the collection of conditions for this resource
1.26      www      9497: sub condval {
                   9498:     my $condidx=shift;
1.54      www      9499:     my $allpathcond='';
1.713     albertel 9500:     foreach my $cond (split(/\|/,$condidx)) {
                   9501: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9502: 	    $allpathcond.=
                   9503: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9504: 	}
1.191     harris41 9505:     }
1.54      www      9506:     $allpathcond=~s/\|$//;
1.713     albertel 9507:     return &docondval($allpathcond);
                   9508: }
                   9509: 
                   9510: #evaluates an expression of conditions
                   9511: sub docondval {
                   9512:     my ($allpathcond) = @_;
                   9513:     my $result=0;
                   9514:     if ($env{'request.course.id'}
                   9515: 	&& defined($allpathcond)) {
                   9516: 	my $operand='|';
                   9517: 	my @stack;
                   9518: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9519: 	    if ($chunk eq '(') {
                   9520: 		push @stack,($operand,$result);
                   9521: 	    } elsif ($chunk eq ')') {
                   9522: 		my $before=pop @stack;
                   9523: 		if (pop @stack eq '&') {
                   9524: 		    $result=$result>$before?$before:$result;
                   9525: 		} else {
                   9526: 		    $result=$result>$before?$result:$before;
                   9527: 		}
                   9528: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9529: 		$operand=$chunk;
                   9530: 	    } else {
                   9531: 		my $new=directcondval($chunk);
                   9532: 		if ($operand eq '&') {
                   9533: 		    $result=$result>$new?$new:$result;
                   9534: 		} else {
                   9535: 		    $result=$result>$new?$result:$new;
                   9536: 		}
                   9537: 	    }
                   9538: 	}
1.26      www      9539:     }
                   9540:     return $result;
1.421     albertel 9541: }
                   9542: 
                   9543: # ---------------------------------------------------- Devalidate courseresdata
                   9544: 
                   9545: sub devalidatecourseresdata {
                   9546:     my ($coursenum,$coursedomain)=@_;
                   9547:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9548:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9549: }
                   9550: 
1.763     www      9551: 
1.200     www      9552: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9553: #
                   9554: #  Parameters:
                   9555: #      $coursenum    - Number of the course.
                   9556: #      $coursedomain - Domain at which the course was created.
                   9557: #  Returns:
                   9558: #     A hash of the course parameters along (I think) with timestamps
                   9559: #     and version info.
1.877     foxr     9560: 
1.624     albertel 9561: sub get_courseresdata {
                   9562:     my ($coursenum,$coursedomain)=@_;
1.200     www      9563:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9564:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9565:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9566:     my %dumpreply;
1.417     albertel 9567:     unless (defined($cached)) {
1.624     albertel 9568: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9569: 	$result=\%dumpreply;
1.251     albertel 9570: 	my ($tmp) = keys(%dumpreply);
                   9571: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9572: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9573: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9574: 	    return $tmp;
1.416     albertel 9575: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9576: 	    $result=undef;
1.599     albertel 9577: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9578: 	}
                   9579:     }
1.624     albertel 9580:     return $result;
                   9581: }
                   9582: 
1.633     albertel 9583: sub devalidateuserresdata {
                   9584:     my ($uname,$udom)=@_;
                   9585:     my $hashid="$udom:$uname";
                   9586:     &devalidate_cache_new('userres',$hashid);
                   9587: }
                   9588: 
1.624     albertel 9589: sub get_userresdata {
                   9590:     my ($uname,$udom)=@_;
                   9591:     #most student don\'t have any data set, check if there is some data
                   9592:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9593: 
                   9594:     my $hashid="$udom:$uname";
                   9595:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9596:     if (!defined($cached)) {
                   9597: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9598: 	$result=\%resourcedata;
                   9599: 	&do_cache_new('userres',$hashid,$result,600);
                   9600:     }
                   9601:     my ($tmp)=keys(%$result);
                   9602:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9603: 	return $result;
                   9604:     }
                   9605:     #error 2 occurs when the .db doesn't exist
                   9606:     if ($tmp!~/error: 2 /) {
1.672     albertel 9607: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9608: 		 " Trying to get resource data for ".
                   9609: 		 $uname." at ".$udom.": ".
                   9610: 		 $tmp."</font>");
                   9611:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9612: 	#&EXT_cache_set($udom,$uname);
                   9613: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9614: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9615:     }
                   9616:     return $tmp;
                   9617: }
1.879     foxr     9618: #----------------------------------------------- resdata - return resource data
                   9619: #  Purpose:
                   9620: #    Return resource data for either users or for a course.
                   9621: #  Parameters:
                   9622: #     $name      - Course/user name.
                   9623: #     $domain    - Name of the domain the user/course is registered on.
                   9624: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9625: #     @which     - Array of names of resources desired.
                   9626: #  Returns:
                   9627: #     The value of the first reasource in @which that is found in the
                   9628: #     resource hash.
                   9629: #  Exceptional Conditions:
                   9630: #     If the $type passed in is not valid (not the string 'course' or 
                   9631: #     'user', an undefined  reference is returned.
                   9632: #     If none of the resources are found, an undef is returned
1.624     albertel 9633: sub resdata {
                   9634:     my ($name,$domain,$type,@which)=@_;
                   9635:     my $result;
                   9636:     if ($type eq 'course') {
                   9637: 	$result=&get_courseresdata($name,$domain);
                   9638:     } elsif ($type eq 'user') {
                   9639: 	$result=&get_userresdata($name,$domain);
                   9640:     }
                   9641:     if (!ref($result)) { return $result; }    
1.251     albertel 9642:     foreach my $item (@which) {
1.927     albertel 9643: 	if (defined($result->{$item->[0]})) {
                   9644: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9645: 	}
1.250     albertel 9646:     }
1.291     albertel 9647:     return undef;
1.200     www      9648: }
                   9649: 
1.1236    raeburn  9650: sub get_numsuppfiles {
                   9651:     my ($cnum,$cdom,$ignorecache)=@_;
                   9652:     my $hashid=$cnum.':'.$cdom;
                   9653:     my ($suppcount,$cached);
                   9654:     unless ($ignorecache) {
                   9655:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9656:     }
                   9657:     unless (defined($cached)) {
                   9658:         my $chome=&homeserver($cnum,$cdom);
                   9659:         unless ($chome eq 'no_host') {
                   9660:             ($suppcount,my $errors) = (0,0);
                   9661:             my $suppmap = 'supplemental.sequence';
                   9662:             ($suppcount,$errors) = 
                   9663:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9664:         }
                   9665:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9666:     }
                   9667:     return $suppcount;
                   9668: }
                   9669: 
1.379     matthew  9670: #
                   9671: # EXT resource caching routines
                   9672: #
                   9673: 
                   9674: sub clear_EXT_cache_status {
1.383     albertel 9675:     &delenv('cache.EXT.');
1.379     matthew  9676: }
                   9677: 
                   9678: sub EXT_cache_status {
                   9679:     my ($target_domain,$target_user) = @_;
1.383     albertel 9680:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9681:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9682:         # We know already the user has no data
                   9683:         return 1;
                   9684:     } else {
                   9685:         return 0;
                   9686:     }
                   9687: }
                   9688: 
                   9689: sub EXT_cache_set {
                   9690:     my ($target_domain,$target_user) = @_;
1.383     albertel 9691:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9692:     #&appenv({$cachename => time});
1.379     matthew  9693: }
                   9694: 
1.28      www      9695: # --------------------------------------------------------- Value of a Variable
1.58      www      9696: sub EXT {
1.715     albertel 9697: 
1.1228    raeburn  9698:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9699:     unless ($varname) { return ''; }
1.218     albertel 9700:     #get real user name/domain, courseid and symb
                   9701:     my $courseid;
1.359     albertel 9702:     my $publicuser;
1.427     www      9703:     if ($symbparm) {
                   9704: 	$symbparm=&get_symb_from_alias($symbparm);
                   9705:     }
1.218     albertel 9706:     if (!($uname && $udom)) {
1.790     albertel 9707:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9708:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9709:     } else {
1.620     albertel 9710: 	$courseid=$env{'request.course.id'};
1.218     albertel 9711:     }
1.48      www      9712:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9713:     my $rest;
1.320     albertel 9714:     if (defined($therest[0])) {
1.48      www      9715:        $rest=join('.',@therest);
                   9716:     } else {
                   9717:        $rest='';
                   9718:     }
1.320     albertel 9719: 
1.57      www      9720:     my $qualifierrest=$qualifier;
                   9721:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9722:     my $spacequalifierrest=$space;
                   9723:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9724:     if ($realm eq 'user') {
1.48      www      9725: # --------------------------------------------------------------- user.resource
                   9726: 	if ($space eq 'resource') {
1.651     albertel 9727: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9728: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9729: 		 &&
1.744     albertel 9730: 		 ($symbparm eq &symbread()) ) {	
                   9731: 		# if we are in the middle of processing the resource the
                   9732: 		# get the value we are planning on committing
                   9733:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9734:                     return $Apache::lonhomework::results{$qualifierrest};
                   9735:                 } else {
                   9736:                     return $Apache::lonhomework::history{$qualifierrest};
                   9737:                 }
1.335     albertel 9738: 	    } else {
1.359     albertel 9739: 		my %restored;
1.620     albertel 9740: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9741: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9742: 		} else {
                   9743: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9744: 		}
1.335     albertel 9745: 		return $restored{$qualifierrest};
                   9746: 	    }
1.48      www      9747: # ----------------------------------------------------------------- user.access
                   9748:         } elsif ($space eq 'access') {
1.218     albertel 9749: 	    # FIXME - not supporting calls for a specific user
1.48      www      9750:             return &allowed($qualifier,$rest);
                   9751: # ------------------------------------------ user.preferences, user.environment
                   9752:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9753: 	    if (($uname eq $env{'user.name'}) &&
                   9754: 		($udom eq $env{'user.domain'})) {
                   9755: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9756: 	    } else {
1.359     albertel 9757: 		my %returnhash;
                   9758: 		if (!$publicuser) {
                   9759: 		    %returnhash=&userenvironment($udom,$uname,
                   9760: 						 $qualifierrest);
                   9761: 		}
1.218     albertel 9762: 		return $returnhash{$qualifierrest};
                   9763: 	    }
1.48      www      9764: # ----------------------------------------------------------------- user.course
                   9765:         } elsif ($space eq 'course') {
1.218     albertel 9766: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9767:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9768: # ------------------------------------------------------------------- user.role
                   9769:         } elsif ($space eq 'role') {
1.218     albertel 9770: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9771:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9772:             if ($qualifier eq 'value') {
                   9773: 		return $role;
                   9774:             } elsif ($qualifier eq 'extent') {
                   9775:                 return $where;
                   9776:             }
                   9777: # ----------------------------------------------------------------- user.domain
                   9778:         } elsif ($space eq 'domain') {
1.218     albertel 9779:             return $udom;
1.48      www      9780: # ------------------------------------------------------------------- user.name
                   9781:         } elsif ($space eq 'name') {
1.218     albertel 9782:             return $uname;
1.48      www      9783: # ---------------------------------------------------- Any other user namespace
1.29      www      9784:         } else {
1.359     albertel 9785: 	    my %reply;
                   9786: 	    if (!$publicuser) {
                   9787: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9788: 	    }
                   9789: 	    return $reply{$qualifierrest};
1.48      www      9790:         }
1.236     www      9791:     } elsif ($realm eq 'query') {
                   9792: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9793:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9794: 						[$spacequalifierrest]);
1.620     albertel 9795: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9796:    } elsif ($realm eq 'request') {
1.48      www      9797: # ------------------------------------------------------------- request.browser
                   9798:         if ($space eq 'browser') {
1.1145    bisitz   9799:             return $env{'browser.'.$qualifier};
1.57      www      9800: # ------------------------------------------------------------ request.filename
                   9801:         } else {
1.620     albertel 9802:             return $env{'request.'.$spacequalifierrest};
1.29      www      9803:         }
1.28      www      9804:     } elsif ($realm eq 'course') {
1.48      www      9805: # ---------------------------------------------------------- course.description
1.620     albertel 9806:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9807:     } elsif ($realm eq 'resource') {
1.165     www      9808: 
1.620     albertel 9809: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9810: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9811: 	}
1.693     albertel 9812: 
1.1232    raeburn  9813:         if ($qualifier eq '') {
                   9814: 	    if ($space eq 'title') {
                   9815: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9816: 	        return &gettitle($symbparm);
                   9817: 	    }
1.693     albertel 9818: 	
1.1232    raeburn  9819: 	    if ($space eq 'map') {
                   9820: 	        my ($map) = &decode_symb($symbparm);
                   9821: 	        return &symbread($map);
                   9822: 	    }
                   9823:             if ($space eq 'maptitle') {
                   9824:                 my ($map) = &decode_symb($symbparm);
                   9825:                 return &gettitle($map);
                   9826:             }
                   9827: 	    if ($space eq 'filename') {
                   9828: 	        if ($symbparm) {
                   9829: 		    return &clutter((&decode_symb($symbparm))[2]);
                   9830: 	        }
                   9831: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9832: 	    }
1.1232    raeburn  9833: 
1.1233    raeburn  9834:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   9835:                 if ($space eq 'visibleparts') {
                   9836:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9837:                     my $item;
                   9838:                     if (ref($navmap)) {
                   9839:                         my $res = $navmap->getBySymb($symbparm);
                   9840:                         my $parts = $res->parts();
                   9841:                         if (ref($parts) eq 'ARRAY') {
                   9842:                             $item = join(',',@{$parts});
                   9843:                         }
                   9844:                         undef($navmap);
1.1232    raeburn  9845:                     }
1.1233    raeburn  9846:                     return $item;
1.1232    raeburn  9847:                 }
                   9848:             }
                   9849:         }
1.693     albertel 9850: 
                   9851: 	my ($section, $group, @groups);
1.593     albertel 9852: 	my ($courselevelm,$courselevel);
1.1228    raeburn  9853:         if (($courseid eq '') && ($cid)) {
                   9854:             $courseid = $cid;
                   9855:         }
                   9856: 	if (($symbparm && $courseid) && 
                   9857: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      9858: 
1.218     albertel 9859: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9860: 
1.60      www      9861: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9862: 	    my $symbp=$symbparm;
1.735     albertel 9863: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9864: 
                   9865: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9866: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9867: 
1.620     albertel 9868: 	    if (($env{'user.name'} eq $uname) &&
                   9869: 		($env{'user.domain'} eq $udom)) {
                   9870: 		$section=$env{'request.course.sec'};
1.733     raeburn  9871:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9872:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9873: 	    } else {
1.539     albertel 9874: 		if (! defined($usection)) {
1.551     albertel 9875: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9876: 		} else {
                   9877: 		    $section = $usection;
                   9878: 		}
1.733     raeburn  9879:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9880: 	    }
                   9881: 
                   9882: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9883: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9884: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9885: 
1.593     albertel 9886: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9887: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9888: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9889: 
1.60      www      9890: # ----------------------------------------------------------- first, check user
1.624     albertel 9891: 
                   9892: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9893: 				       ([$courselevelr,'resource'],
                   9894: 					[$courselevelm,'map'     ],
                   9895: 					[$courselevel, 'course'  ]));
1.931     albertel 9896: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9897: 
1.594     albertel 9898: # ------------------------------------------------ second, check some of course
1.684     raeburn  9899:             my $coursereply;
1.691     raeburn  9900:             if (@groups > 0) {
                   9901:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9902:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9903:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9904:             }
1.96      www      9905: 
1.684     raeburn  9906: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9907: 				  $env{'course.'.$courseid.'.domain'},
                   9908: 				  'course',
                   9909: 				  ([$seclevelr,   'resource'],
                   9910: 				   [$seclevelm,   'map'     ],
                   9911: 				   [$seclevel,    'course'  ],
                   9912: 				   [$courselevelr,'resource']));
                   9913: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9914: 
1.60      www      9915: # ------------------------------------------------------ third, check map parms
1.218     albertel 9916: 	    my %parmhash=();
                   9917: 	    my $thisparm='';
                   9918: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9919: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9920: 		    &GDBM_READER(),0640)) {
1.218     albertel 9921: 		$thisparm=$parmhash{$symbparm};
                   9922: 		untie(%parmhash);
                   9923: 	    }
1.927     albertel 9924: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9925: 	}
1.594     albertel 9926: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9927: 
1.218     albertel 9928: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9929: 	my $filename;
                   9930: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9931: 	if ($symbparm) {
1.409     www      9932: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9933: 	} else {
1.620     albertel 9934: 	    $filename=$env{'request.filename'};
1.282     albertel 9935: 	}
                   9936: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9937: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9938: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9939: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9940: 
1.927     albertel 9941: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9942: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9943: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9944: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9945: 				     $env{'course.'.$courseid.'.domain'},
                   9946: 				     'course',
1.927     albertel 9947: 				     ([$courselevelm,'map'   ],
                   9948: 				      [$courselevel, 'course']));
                   9949: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9950: 	}
1.145     www      9951: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9952: 	unless ($space eq '0') {
1.336     albertel 9953: 	    my @parts=split(/_/,$space);
                   9954: 	    my $id=pop(@parts);
                   9955: 	    my $part=join('_',@parts);
                   9956: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9957: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9958: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9959: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9960: 	}
1.395     albertel 9961: 	if ($recurse) { return undef; }
                   9962: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9963: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9964: # ---------------------------------------------------- Any other user namespace
                   9965:     } elsif ($realm eq 'environment') {
                   9966: # ----------------------------------------------------------------- environment
1.620     albertel 9967: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9968: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9969: 	} else {
1.770     albertel 9970: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9971: 		return '';
                   9972: 	    }
1.219     albertel 9973: 	    my %returnhash=&userenvironment($udom,$uname,
                   9974: 					    $spacequalifierrest);
                   9975: 	    return $returnhash{$spacequalifierrest};
                   9976: 	}
1.28      www      9977:     } elsif ($realm eq 'system') {
1.48      www      9978: # ----------------------------------------------------------------- system.time
                   9979: 	if ($space eq 'time') {
                   9980: 	    return time;
                   9981:         }
1.696     albertel 9982:     } elsif ($realm eq 'server') {
                   9983: # ----------------------------------------------------------------- system.time
                   9984: 	if ($space eq 'name') {
                   9985: 	    return $ENV{'SERVER_NAME'};
                   9986:         }
1.28      www      9987:     }
1.48      www      9988:     return '';
1.61      www      9989: }
                   9990: 
1.927     albertel 9991: sub get_reply {
                   9992:     my ($reply_value) = @_;
1.940     raeburn  9993:     if (ref($reply_value) eq 'ARRAY') {
                   9994:         if (wantarray) {
                   9995: 	    return @$reply_value;
                   9996:         }
                   9997:         return $reply_value->[0];
                   9998:     } else {
                   9999:         return $reply_value;
1.927     albertel 10000:     }
                   10001: }
                   10002: 
1.691     raeburn  10003: sub check_group_parms {
                   10004:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10005:     my @groupitems = ();
                   10006:     my $resultitem;
1.927     albertel 10007:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10008:     foreach my $group (@{$groups}) {
                   10009:         foreach my $level (@levels) {
1.927     albertel 10010:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10011:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10012:         }
                   10013:     }
                   10014:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10015:                             $env{'course.'.$courseid.'.domain'},
                   10016:                                      'course',@groupitems);
                   10017:     return $coursereply;
                   10018: }
                   10019: 
                   10020: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10021:     my ($courseid,@groups) = @_;
                   10022:     @groups = sort(@groups);
1.691     raeburn  10023:     return @groups;
                   10024: }
                   10025: 
1.395     albertel 10026: sub packages_tab_default {
                   10027:     my ($uri,$varname)=@_;
                   10028:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10029: 
                   10030:     my (@extension,@specifics,$do_default);
                   10031:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10032: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10033: 	if ($pack_type eq 'default') {
                   10034: 	    $do_default=1;
                   10035: 	} elsif ($pack_type eq 'extension') {
                   10036: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10037: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10038: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10039: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10040: 	}
                   10041:     }
                   10042:     # first look for a package that matches the requested part id
                   10043:     foreach my $package (@specifics) {
                   10044: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10045: 	next if ($pack_part ne $part);
                   10046: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10047: 	    return $packagetab{"$pack_type&$name&default"};
                   10048: 	}
                   10049:     }
                   10050:     # look for any possible matching non extension_ package
                   10051:     foreach my $package (@specifics) {
                   10052: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10053: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10054: 	    return $packagetab{"$pack_type&$name&default"};
                   10055: 	}
1.585     albertel 10056: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10057: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10058: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10059: 	}
                   10060:     }
1.738     albertel 10061:     # look for any posible extension_ match
                   10062:     foreach my $package (@extension) {
                   10063: 	my ($package,$pack_type)=@{$package};
                   10064: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10065: 	    return $packagetab{"$pack_type&$name&default"};
                   10066: 	}
                   10067: 	if (defined($packagetab{$package."&$name&default"})) {
                   10068: 	    return $packagetab{$package."&$name&default"};
                   10069: 	}
                   10070:     }
                   10071:     # look for a global default setting
                   10072:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10073: 	return $packagetab{"default&$name&default"};
                   10074:     }
1.395     albertel 10075:     return undef;
                   10076: }
                   10077: 
1.334     albertel 10078: sub add_prefix_and_part {
                   10079:     my ($prefix,$part)=@_;
                   10080:     my $keyroot;
                   10081:     if (defined($prefix) && $prefix !~ /^__/) {
                   10082: 	# prefix that has a part already
                   10083: 	$keyroot=$prefix;
                   10084:     } elsif (defined($prefix)) {
                   10085: 	# prefix that is missing a part
                   10086: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10087:     } else {
                   10088: 	# no prefix at all
                   10089: 	if (defined($part)) { $keyroot='_'.$part; }
                   10090:     }
                   10091:     return $keyroot;
                   10092: }
                   10093: 
1.71      www      10094: # ---------------------------------------------------------------- Get metadata
                   10095: 
1.599     albertel 10096: my %metaentry;
1.1070    www      10097: my %importedpartids;
1.71      www      10098: sub metadata {
1.176     www      10099:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10100:     $uri=&declutter($uri);
1.288     albertel 10101:     # if it is a non metadata possible uri return quickly
1.529     albertel 10102:     if (($uri eq '') || 
                   10103: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10104: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10105:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10106: 	return undef;
                   10107:     }
1.1140    www      10108:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10109: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10110: 	return undef;
1.288     albertel 10111:     }
1.73      www      10112:     my $filename=$uri;
                   10113:     $uri=~s/\.meta$//;
1.172     www      10114: #
                   10115: # Is the metadata already cached?
1.177     www      10116: # Look at timestamp of caching
1.172     www      10117: # Everything is cached by the main uri, libraries are never directly cached
                   10118: #
1.428     albertel 10119:     if (!defined($liburi)) {
1.599     albertel 10120: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10121: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10122:     }
                   10123:     {
1.1069    www      10124: # Imported parts would go here
1.1070    www      10125:         my %importedids=();
                   10126:         my @origfileimportpartids=();
1.1069    www      10127:         my $importedparts=0;
1.172     www      10128: #
                   10129: # Is this a recursive call for a library?
                   10130: #
1.599     albertel 10131: #	if (! exists($metacache{$uri})) {
                   10132: #	    $metacache{$uri}={};
                   10133: #	}
1.924     albertel 10134: 	my $cachetime = 60*60;
1.171     www      10135:         if ($liburi) {
                   10136: 	    $liburi=&declutter($liburi);
                   10137:             $filename=$liburi;
1.401     bowersj2 10138:         } else {
1.599     albertel 10139: 	    &devalidate_cache_new('meta',$uri);
                   10140: 	    undef(%metaentry);
1.401     bowersj2 10141: 	}
1.140     www      10142:         my %metathesekeys=();
1.73      www      10143:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10144: 	my $metastring;
1.1140    www      10145: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10146: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10147: 	    $metastring = 
1.929     albertel 10148: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10149: 					  ('grade_target' => 'meta'));
                   10150: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10151: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10152:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10153: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10154: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10155: 	    $metastring=&getfile($file);
1.489     albertel 10156: 	}
1.208     albertel 10157:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10158:         my $token;
1.140     www      10159:         undef %metathesekeys;
1.71      www      10160:         while ($token=$parser->get_token) {
1.339     albertel 10161: 	    if ($token->[0] eq 'S') {
                   10162: 		if (defined($token->[2]->{'package'})) {
1.172     www      10163: #
                   10164: # This is a package - get package info
                   10165: #
1.339     albertel 10166: 		    my $package=$token->[2]->{'package'};
                   10167: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10168: 		    if (defined($token->[2]->{'id'})) { 
                   10169: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10170: 		    }
1.599     albertel 10171: 		    if ($metaentry{':packages'}) {
                   10172: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10173: 		    } else {
1.599     albertel 10174: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10175: 		    }
1.736     albertel 10176: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10177: 			my $part=$keyroot;
                   10178: 			$part=~s/^\_//;
1.736     albertel 10179: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10180: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10181: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10182: 			    # ignore package.tab specified default values
                   10183:                             # here &package_tab_default() will fetch those
                   10184: 			    if ($subp eq 'default') { next; }
1.736     albertel 10185: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10186: 			    my $unikey;
                   10187: 			    if ($pack =~ /_0$/) {
                   10188: 				$unikey='parameter_0_'.$name;
                   10189: 				$part=0;
                   10190: 			    } else {
                   10191: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10192: 			    }
1.339     albertel 10193: 			    if ($subp eq 'display') {
                   10194: 				$value.=' [Part: '.$part.']';
                   10195: 			    }
1.599     albertel 10196: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10197: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10198: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10199: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10200: 			    }
1.599     albertel 10201: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10202: 				$metaentry{':'.$unikey}=
                   10203: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10204: 			    }
1.339     albertel 10205: 			}
                   10206: 		    }
                   10207: 		} else {
1.172     www      10208: #
                   10209: # This is not a package - some other kind of start tag
1.339     albertel 10210: #
                   10211: 		    my $entry=$token->[1];
1.1068    www      10212: 		    my $unikey='';
1.175     www      10213: 
1.339     albertel 10214: 		    if ($entry eq 'import') {
1.175     www      10215: #
                   10216: # Importing a library here
1.339     albertel 10217: #
1.1067    www      10218:                         my $location=$parser->get_text('/import');
                   10219:                         my $dir=$filename;
                   10220:                         $dir=~s|[^/]*$||;
                   10221:                         $location=&filelocation($dir,$location);
1.1069    www      10222:                        
1.1068    www      10223:                         my $importmode=$token->[2]->{'importmode'};
                   10224:                         if ($importmode eq 'problem') {
1.1069    www      10225: # Import as problem/response
1.1068    www      10226:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10227:                         } elsif ($importmode eq 'part') {
                   10228: # Import as part(s)
1.1069    www      10229:                            $importedparts=1;
                   10230: # We need to get the original file and the imported file to get the part order correct
                   10231: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10232: # Load and inspect original file
1.1070    www      10233:                            if ($#origfileimportpartids<0) {
                   10234:                               undef(%importedpartids);
                   10235:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10236:                               my $origfile=&getfile($origfilelocation);
                   10237:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10238:                            }
                   10239: 
1.1069    www      10240: # Load and inspect imported file
                   10241:                            my $impfile=&getfile($location);
                   10242:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10243:                            if ($#impfilepartids>=0) {
                   10244: # This problem had parts
1.1070    www      10245:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10246:                            } else {
                   10247: # Importing by turning a single problem into a problem part
                   10248: # It gets the import-tags ID as part-ID
                   10249:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10250:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10251:                            }
1.1068    www      10252:                         } else {
                   10253: # Normal import
                   10254:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10255:                            if (defined($token->[2]->{'id'})) {
                   10256:                               $unikey.='_'.$token->[2]->{'id'};
                   10257:                            }
1.1067    www      10258:                         }
                   10259: 
1.339     albertel 10260: 			if ($depthcount<20) {
1.736     albertel 10261: 			    my $metadata = 
                   10262: 				&metadata($uri,'keys', $location,$unikey,
                   10263: 					  $depthcount+1);
                   10264: 			    foreach my $meta (split(',',$metadata)) {
                   10265: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10266: 				$metathesekeys{$meta}=1;
1.339     albertel 10267: 			    }
1.1068    www      10268: 			
                   10269:                         }
1.1067    www      10270: 		    } else {
                   10271: #
                   10272: # Not importing, some other kind of non-package, non-library start tag
                   10273: # 
                   10274:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10275:                         if (defined($token->[2]->{'id'})) {
                   10276:                             $unikey.='_'.$token->[2]->{'id'};
                   10277:                         }
1.339     albertel 10278: 			if (defined($token->[2]->{'name'})) { 
                   10279: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10280: 			}
                   10281: 			$metathesekeys{$unikey}=1;
1.736     albertel 10282: 			foreach my $param (@{$token->[3]}) {
                   10283: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10284: 				$token->[2]->{$param};
1.339     albertel 10285: 			}
                   10286: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10287: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10288: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10289: 		 # only ws inside the tag, and not in default, so use default
                   10290: 		 # as value
1.599     albertel 10291: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10292: 			} elsif ( $internaltext =~ /\S/ ) {
                   10293: 		  # something interesting inside the tag
                   10294: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10295: 			} else {
1.908     albertel 10296: 		  # no interesting values, don't set a default
1.339     albertel 10297: 			}
1.172     www      10298: # end of not-a-package not-a-library import
1.339     albertel 10299: 		    }
1.172     www      10300: # end of not-a-package start tag
1.339     albertel 10301: 		}
1.172     www      10302: # the next is the end of "start tag"
1.339     albertel 10303: 	    }
                   10304: 	}
1.483     albertel 10305: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10306: 	$extension = lc($extension);
                   10307: 	if ($extension eq 'htm') { $extension='html'; }
                   10308: 
1.737     albertel 10309: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10310: 	    #no specific packages #how's our extension
                   10311: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10312: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10313: 					 \%metathesekeys);
                   10314: 	}
1.883     albertel 10315: 
                   10316: 	if (!exists($metaentry{':packages'})
                   10317: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10318: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10319: 		#no specific packages well let's get default then
                   10320: 		if ($key!~/^default&/) { next; }
1.488     albertel 10321: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10322: 					     \%metathesekeys);
                   10323: 	    }
                   10324: 	}
1.338     www      10325: # are there custom rights to evaluate
1.599     albertel 10326: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10327: 
1.338     www      10328:     #
                   10329:     # Importing a rights file here
1.339     albertel 10330:     #
                   10331: 	    unless ($depthcount) {
1.599     albertel 10332: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10333: 		my $dir=$filename;
                   10334: 		$dir=~s|[^/]*$||;
                   10335: 		$location=&filelocation($dir,$location);
1.736     albertel 10336: 		my $rights_metadata =
                   10337: 		    &metadata($uri,'keys',$location,'_rights',
                   10338: 			      $depthcount+1);
                   10339: 		foreach my $rights (split(',',$rights_metadata)) {
                   10340: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10341: 		    $metathesekeys{$rights}=1;
1.339     albertel 10342: 		}
                   10343: 	    }
                   10344: 	}
1.737     albertel 10345: 	# uniqifiy package listing
                   10346: 	my %seen;
                   10347: 	my @uniq_packages =
                   10348: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10349: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10350: 
1.1070    www      10351:         if ($importedparts) {
                   10352: # We had imported parts and need to rebuild partorder
                   10353:            $metaentry{':partorder'}='';
                   10354:            $metathesekeys{'partorder'}=1;
                   10355:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10356:                if ($origfileimportpartids[$index] eq 'part') {
                   10357: # original part, part of the problem
                   10358:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10359:                } else {
                   10360: # we have imported parts at this position
                   10361:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10362:                }
                   10363:            }
                   10364:            $metaentry{':partorder'}=~s/^\,//;
                   10365:         }
                   10366: 
1.737     albertel 10367: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10368: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10369: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10370: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10371: # this is the end of "was not already recently cached
1.71      www      10372:     }
1.599     albertel 10373:     return $metaentry{':'.$what};
1.261     albertel 10374: }
                   10375: 
1.488     albertel 10376: sub metadata_create_package_def {
1.483     albertel 10377:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10378:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10379:     if ($subp eq 'default') { next; }
                   10380:     
1.599     albertel 10381:     if (defined($metaentry{':packages'})) {
                   10382: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10383:     } else {
1.599     albertel 10384: 	$metaentry{':packages'}=$package;
1.483     albertel 10385:     }
                   10386:     my $value=$packagetab{$key};
                   10387:     my $unikey;
                   10388:     $unikey='parameter_0_'.$name;
1.599     albertel 10389:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10390:     $$metathesekeys{$unikey}=1;
1.599     albertel 10391:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10392: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10393:     }
1.599     albertel 10394:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10395: 	$metaentry{':'.$unikey}=
                   10396: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10397:     }
                   10398: }
                   10399: 
1.261     albertel 10400: sub metadata_generate_part0 {
                   10401:     my ($metadata,$metacache,$uri) = @_;
                   10402:     my %allnames;
1.737     albertel 10403:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10404: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10405: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10406: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10407: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10408: 	    $allnames{$name}=$part;
                   10409: 	  }
                   10410: 	}
                   10411:     }
                   10412:     foreach my $name (keys(%allnames)) {
                   10413:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10414:       my $key=":parameter_0_$name";
1.261     albertel 10415:       $$metacache{"$key.part"}='0';
                   10416:       $$metacache{"$key.name"}=$name;
1.428     albertel 10417:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10418: 					   $allnames{$name}.'_'.$name.
                   10419: 					   '.type'};
1.428     albertel 10420:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10421: 			     '.display'};
1.644     www      10422:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10423:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10424:       $$metacache{"$key.display"}=$olddis;
                   10425:     }
1.71      www      10426: }
                   10427: 
1.764     albertel 10428: # ------------------------------------------------------ Devalidate title cache
                   10429: 
                   10430: sub devalidate_title_cache {
                   10431:     my ($url)=@_;
                   10432:     if (!$env{'request.course.id'}) { return; }
                   10433:     my $symb=&symbread($url);
                   10434:     if (!$symb) { return; }
                   10435:     my $key=$env{'request.course.id'}."\0".$symb;
                   10436:     &devalidate_cache_new('title',$key);
                   10437: }
                   10438: 
1.1014    droeschl 10439: # ------------------------------------------------- Get the title of a course
                   10440: 
                   10441: sub current_course_title {
                   10442:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10443: }
1.301     www      10444: # ------------------------------------------------- Get the title of a resource
                   10445: 
                   10446: sub gettitle {
                   10447:     my $urlsymb=shift;
                   10448:     my $symb=&symbread($urlsymb);
1.534     albertel 10449:     if ($symb) {
1.620     albertel 10450: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10451: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10452: 	if (defined($cached)) { 
                   10453: 	    return $result;
                   10454: 	}
1.534     albertel 10455: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10456: 	my $title='';
1.907     albertel 10457: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10458: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10459: 	} else {
                   10460: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10461: 		    &GDBM_READER(),0640)) {
                   10462: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10463: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10464: 		untie(%bighash);
                   10465: 	    }
1.534     albertel 10466: 	}
                   10467: 	$title=~s/\&colon\;/\:/gs;
                   10468: 	if ($title) {
1.1159    www      10469: # Remember both $symb and $title for dynamic metadata
                   10470:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10471:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10472: # Cache this title and then return it
1.599     albertel 10473: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10474: 	}
                   10475: 	$urlsymb=$url;
                   10476:     }
                   10477:     my $title=&metadata($urlsymb,'title');
                   10478:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10479:     return $title;
1.301     www      10480: }
1.613     albertel 10481: 
1.614     albertel 10482: sub get_slot {
                   10483:     my ($which,$cnum,$cdom)=@_;
                   10484:     if (!$cnum || !$cdom) {
1.790     albertel 10485: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10486: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10487: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10488:     }
1.703     albertel 10489:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10490:     my %slotinfo;
                   10491:     if (exists($remembered{$key})) {
                   10492: 	$slotinfo{$which} = $remembered{$key};
                   10493:     } else {
                   10494: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10495: 	&Apache::lonhomework::showhash(%slotinfo);
                   10496: 	my ($tmp)=keys(%slotinfo);
                   10497: 	if ($tmp=~/^error:/) { return (); }
                   10498: 	$remembered{$key} = $slotinfo{$which};
                   10499:     }
1.616     albertel 10500:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10501: 	return %{$slotinfo{$which}};
                   10502:     }
                   10503:     return $slotinfo{$which};
1.614     albertel 10504: }
1.1150    raeburn  10505: 
                   10506: sub get_reservable_slots {
                   10507:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10508:     my $now = time;
                   10509:     my $reservable_info;
                   10510:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10511:     if (exists($remembered{$key})) {
                   10512:         $reservable_info = $remembered{$key};
                   10513:     } else {
                   10514:         my %resv;
                   10515:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10516:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10517:         $reservable_info = \%resv;
                   10518:         $remembered{$key} = $reservable_info;
                   10519:     }
                   10520:     return $reservable_info;
                   10521: }
                   10522: 
                   10523: sub get_course_slots {
                   10524:     my ($cnum,$cdom) = @_;
                   10525:     my $hashid=$cnum.':'.$cdom;
                   10526:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10527:     if (defined($cached)) {
                   10528:         if (ref($result) eq 'HASH') {
                   10529:             return %{$result};
                   10530:         }
                   10531:     } else {
                   10532:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10533:         my ($tmp) = keys(%slots);
                   10534:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10535:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10536:             return %slots;
                   10537:         }
                   10538:     }
                   10539:     return;
                   10540: }
                   10541: 
                   10542: sub devalidate_slots_cache {
                   10543:     my ($cnum,$cdom)=@_;
                   10544:     my $hashid=$cnum.':'.$cdom;
                   10545:     &devalidate_cache_new('allslots',$hashid);
                   10546: }
                   10547: 
1.1181    raeburn  10548: sub get_coursechange {
                   10549:     my ($cdom,$cnum) = @_;
                   10550:     if ($cdom eq '' || $cnum eq '') {
                   10551:         return unless ($env{'request.course.id'});
                   10552:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10553:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10554:     }
                   10555:     my $hashid=$cdom.'_'.$cnum;
                   10556:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10557:     if ((defined($cached)) && ($change ne '')) {
                   10558:         return $change;
                   10559:     } else {
                   10560:         my %crshash;
                   10561:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10562:         if ($crshash{'internal.contentchange'} eq '') {
                   10563:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10564:             if ($change eq '') {
                   10565:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10566:                 $change = $crshash{'internal.created'};
                   10567:             }
                   10568:         } else {
                   10569:             $change = $crshash{'internal.contentchange'};
                   10570:         }
                   10571:         my $cachetime = 600;
                   10572:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10573:     }
                   10574:     return $change;
                   10575: }
                   10576: 
                   10577: sub devalidate_coursechange_cache {
                   10578:     my ($cnum,$cdom)=@_;
                   10579:     my $hashid=$cnum.':'.$cdom;
                   10580:     &devalidate_cache_new('crschange',$hashid);
                   10581: }
                   10582: 
1.31      www      10583: # ------------------------------------------------- Update symbolic store links
                   10584: 
                   10585: sub symblist {
                   10586:     my ($mapname,%newhash)=@_;
1.438     www      10587:     $mapname=&deversion(&declutter($mapname));
1.31      www      10588:     my %hash;
1.620     albertel 10589:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10590:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10591:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10592: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10593: 		next if ($url eq 'last_known'
                   10594: 			 && $env{'form.no_update_last_known'});
                   10595: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10596: 						    $newhash{$url}->[1],
                   10597: 						    $newhash{$url}->[0]);
1.191     harris41 10598:             }
1.31      www      10599:             if (untie(%hash)) {
                   10600: 		return 'ok';
                   10601:             }
                   10602:         }
                   10603:     }
                   10604:     return 'error';
1.212     www      10605: }
                   10606: 
                   10607: # --------------------------------------------------------------- Verify a symb
                   10608: 
                   10609: sub symbverify {
1.1190    raeburn  10610:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10611:     my $thisfn=$thisurl;
1.439     www      10612:     $thisfn=&declutter($thisfn);
1.215     www      10613: # direct jump to resource in page or to a sequence - will construct own symbs
                   10614:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10615: # check URL part
1.409     www      10616:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10617: 
1.431     www      10618:     unless ($url eq $thisfn) { return 0; }
1.213     www      10619: 
1.216     www      10620:     $symb=&symbclean($symb);
1.510     www      10621:     $thisurl=&deversion($thisurl);
1.439     www      10622:     $thisfn=&deversion($thisfn);
1.213     www      10623: 
                   10624:     my %bighash;
                   10625:     my $okay=0;
1.431     www      10626: 
1.620     albertel 10627:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10628:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10629:         my $noclutter;
1.1032    raeburn  10630:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10631:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10632:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10633:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10634:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10635:                 $noclutter = 1;
                   10636:             }
                   10637:         }
                   10638:         my $ids;
                   10639:         if ($noclutter) {
                   10640:             $ids=$bighash{'ids_'.$thisurl};
                   10641:         } else {
                   10642:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10643:         }
1.1102    raeburn  10644:         unless ($ids) {
                   10645:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10646:             $ids=$bighash{$idkey};
1.216     www      10647:         }
                   10648:         if ($ids) {
                   10649: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10650:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10651:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10652:             }
1.800     albertel 10653: 	    foreach my $id (split(/\,/,$ids)) {
                   10654: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10655:                if (
                   10656:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10657:    eq $symb) {
                   10658:                    if (ref($encstate)) {
                   10659:                        $$encstate = $bighash{'encrypted_'.$id};
                   10660:                    }
1.620     albertel 10661: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10662: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10663:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10664: 		       $okay=1;
1.1202    raeburn  10665:                        last;
1.582     albertel 10666: 		   }
                   10667: 	       }
1.216     www      10668: 	   }
                   10669:         }
1.213     www      10670: 	untie(%bighash);
                   10671:     }
                   10672:     return $okay;
1.31      www      10673: }
                   10674: 
1.210     www      10675: # --------------------------------------------------------------- Clean-up symb
                   10676: 
                   10677: sub symbclean {
                   10678:     my $symb=shift;
1.568     albertel 10679:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10680: # remove version from map
                   10681:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10682: 
1.210     www      10683: # remove version from URL
                   10684:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10685: 
1.507     www      10686: # remove wrapper
                   10687: 
1.510     www      10688:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10689:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10690:     return $symb;
1.409     www      10691: }
                   10692: 
                   10693: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10694: 
                   10695: sub encode_symb {
                   10696:     my ($map,$resid,$url)=@_;
                   10697:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10698: }
1.409     www      10699: 
                   10700: sub decode_symb {
1.568     albertel 10701:     my $symb=shift;
                   10702:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10703:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10704:     return (&fixversion($map),$resid,&fixversion($url));
                   10705: }
                   10706: 
                   10707: sub fixversion {
                   10708:     my $fn=shift;
1.609     banghart 10709:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10710:     my %bighash;
                   10711:     my $uri=&clutter($fn);
1.620     albertel 10712:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10713: # is this cached?
1.599     albertel 10714:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10715:     if (defined($cached)) { return $result; }
                   10716: # unfortunately not cached, or expired
1.620     albertel 10717:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10718: 	    &GDBM_READER(),0640)) {
                   10719:  	if ($bighash{'version_'.$uri}) {
                   10720:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10721:  	    unless (($version eq 'mostrecent') || 
                   10722: 		    ($version==&getversion($uri))) {
1.440     www      10723:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10724:  	    }
                   10725:  	}
                   10726:  	untie %bighash;
1.413     www      10727:     }
1.599     albertel 10728:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10729: }
                   10730: 
                   10731: sub deversion {
                   10732:     my $url=shift;
                   10733:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10734:     return $url;
1.210     www      10735: }
                   10736: 
1.31      www      10737: # ------------------------------------------------------ Return symb list entry
                   10738: 
                   10739: sub symbread {
1.249     www      10740:     my ($thisfn,$donotrecurse)=@_;
1.1206    raeburn  10741:     my $cache_str;
                   10742:     if ($thisfn ne '') {
                   10743:         $cache_str='request.symbread.cached.'.$thisfn;
                   10744:         if ($env{$cache_str} ne '') {
1.1179    raeburn  10745:             return $env{$cache_str};
                   10746:         }
1.1206    raeburn  10747:     } else {
1.242     www      10748: # no filename provided? try from environment
1.620     albertel 10749:         if ($env{'request.symb'}) {
                   10750: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10751: 	}
1.620     albertel 10752: 	$thisfn=$env{'request.filename'};
1.44      www      10753:     }
1.569     albertel 10754:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10755: # is that filename actually a symb? Verify, clean, and return
                   10756:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10757: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10758: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10759: 	}
1.242     www      10760:     }
1.44      www      10761:     $thisfn=declutter($thisfn);
1.31      www      10762:     my %hash;
1.37      www      10763:     my %bighash;
                   10764:     my $syval='';
1.620     albertel 10765:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10766:         my $targetfn = $thisfn;
1.609     banghart 10767:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10768:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10769:         }
1.687     albertel 10770: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10771: 	    $targetfn=$1;
                   10772: 	}
1.620     albertel 10773:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10774:                       &GDBM_READER(),0640)) {
1.481     raeburn  10775: 	    $syval=$hash{$targetfn};
1.37      www      10776:             untie(%hash);
                   10777:         }
                   10778: # ---------------------------------------------------------- There was an entry
                   10779:         if ($syval) {
1.601     albertel 10780: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10781: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10782: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10783: 		    #return $env{$cache_str}='';
1.601     albertel 10784: 		#}    
                   10785: 		#$syval.=$1;
                   10786: 	    #}
1.37      www      10787:         } else {
                   10788: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10789:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10790:                             &GDBM_READER(),0640)) {
1.37      www      10791: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10792:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10793:               unless ($ids) { 
                   10794:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10795:               }
                   10796:               unless ($ids) {
                   10797: # alias?
                   10798: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10799:               }
1.37      www      10800:               if ($ids) {
                   10801: # ------------------------------------------------------------------- Has ID(s)
                   10802:                  my @possibilities=split(/\,/,$ids);
1.39      www      10803:                  if ($#possibilities==0) {
                   10804: # ----------------------------------------------- There is only one possibility
1.37      www      10805: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10806: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10807: 						    $resid,$thisfn);
1.249     www      10808:                  } elsif (!$donotrecurse) {
1.39      www      10809: # ------------------------------------------ There is more than one possibility
                   10810:                      my $realpossible=0;
1.800     albertel 10811:                      foreach my $id (@possibilities) {
                   10812: 			 my $file=$bighash{'src_'.$id};
1.39      www      10813:                          if (&allowed('bre',$file)) {
1.800     albertel 10814:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10815:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10816: 				$realpossible++;
1.626     albertel 10817:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10818: 						    $resid,$thisfn);
1.39      www      10819:                             }
                   10820: 			 }
1.191     harris41 10821:                      }
1.39      www      10822: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10823:                  } else {
                   10824:                      $syval='';
1.37      www      10825:                  }
                   10826: 	      }
                   10827:               untie(%bighash)
1.481     raeburn  10828:            }
1.31      www      10829:         }
1.62      www      10830:         if ($syval) {
1.620     albertel 10831: 	    return $env{$cache_str}=$syval;
1.62      www      10832:         }
1.31      www      10833:     }
1.949     raeburn  10834:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10835:     return $env{$cache_str}='';
1.31      www      10836: }
                   10837: 
                   10838: # ---------------------------------------------------------- Return random seed
                   10839: 
1.32      www      10840: sub numval {
                   10841:     my $txt=shift;
                   10842:     $txt=~tr/A-J/0-9/;
                   10843:     $txt=~tr/a-j/0-9/;
                   10844:     $txt=~tr/K-T/0-9/;
                   10845:     $txt=~tr/k-t/0-9/;
                   10846:     $txt=~tr/U-Z/0-5/;
                   10847:     $txt=~tr/u-z/0-5/;
                   10848:     $txt=~s/\D//g;
1.564     albertel 10849:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10850:     return int($txt);
1.368     albertel 10851: }
                   10852: 
1.484     albertel 10853: sub numval2 {
                   10854:     my $txt=shift;
                   10855:     $txt=~tr/A-J/0-9/;
                   10856:     $txt=~tr/a-j/0-9/;
                   10857:     $txt=~tr/K-T/0-9/;
                   10858:     $txt=~tr/k-t/0-9/;
                   10859:     $txt=~tr/U-Z/0-5/;
                   10860:     $txt=~tr/u-z/0-5/;
                   10861:     $txt=~s/\D//g;
                   10862:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10863:     my $total;
                   10864:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10865:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10866:     return int($total);
                   10867: }
                   10868: 
1.575     albertel 10869: sub numval3 {
                   10870:     use integer;
                   10871:     my $txt=shift;
                   10872:     $txt=~tr/A-J/0-9/;
                   10873:     $txt=~tr/a-j/0-9/;
                   10874:     $txt=~tr/K-T/0-9/;
                   10875:     $txt=~tr/k-t/0-9/;
                   10876:     $txt=~tr/U-Z/0-5/;
                   10877:     $txt=~tr/u-z/0-5/;
                   10878:     $txt=~s/\D//g;
                   10879:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10880:     my $total;
                   10881:     foreach my $val (@txts) { $total+=$val; }
                   10882:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10883:     return $total;
                   10884: }
                   10885: 
1.675     albertel 10886: sub digest {
                   10887:     my ($data)=@_;
                   10888:     my $digest=&Digest::MD5::md5($data);
                   10889:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10890:     my ($e,$f);
                   10891:     {
                   10892:         use integer;
                   10893:         $e=($a+$b);
                   10894:         $f=($c+$d);
                   10895:         if ($_64bit) {
                   10896:             $e=(($e<<32)>>32);
                   10897:             $f=(($f<<32)>>32);
                   10898:         }
                   10899:     }
                   10900:     if (wantarray) {
                   10901: 	return ($e,$f);
                   10902:     } else {
                   10903: 	my $g;
                   10904: 	{
                   10905: 	    use integer;
                   10906: 	    $g=($e+$f);
                   10907: 	    if ($_64bit) {
                   10908: 		$g=(($g<<32)>>32);
                   10909: 	    }
                   10910: 	}
                   10911: 	return $g;
                   10912:     }
                   10913: }
                   10914: 
1.368     albertel 10915: sub latest_rnd_algorithm_id {
1.675     albertel 10916:     return '64bit5';
1.366     albertel 10917: }
1.32      www      10918: 
1.503     albertel 10919: sub get_rand_alg {
                   10920:     my ($courseid)=@_;
1.790     albertel 10921:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10922:     if ($courseid) {
1.620     albertel 10923: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10924:     }
                   10925:     return &latest_rnd_algorithm_id();
                   10926: }
                   10927: 
1.562     albertel 10928: sub validCODE {
                   10929:     my ($CODE)=@_;
                   10930:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10931:     return 0;
                   10932: }
                   10933: 
1.491     albertel 10934: sub getCODE {
1.620     albertel 10935:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10936:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10937: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10938: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10939: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10940:     }
                   10941:     return undef;
                   10942: }
1.1133    foxr     10943: #
                   10944: #  Determines the random seed for a specific context:
                   10945: #
                   10946: # parameters:
                   10947: #   symb      - in course context the symb for the seed.
                   10948: #   course_id - The course id of the form domain_coursenum.
                   10949: #   domain    - Domain for the user.
                   10950: #   course    - Course for the user.
                   10951: #   cenv      - environment of the course.
                   10952: #
                   10953: # NOTE:
                   10954: #   All parameters are picked out of the environment if missing
                   10955: #   or not defined.
                   10956: #   If a symb cannot be determined the current time is used instead.
                   10957: #
                   10958: #  For a given well defined symb, courside, domain, username,
                   10959: #  and course environment, the seed is reproducible.
                   10960: #
1.31      www      10961: sub rndseed {
1.1133    foxr     10962:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10963:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10964:     if (!defined($symb)) {
1.366     albertel 10965: 	unless ($symb=$wsymb) { return time; }
                   10966:     }
1.1146    foxr     10967:     if (!defined $courseid) { 
                   10968: 	$courseid=$wcourseid; 
                   10969:     }
                   10970:     if (!defined $domain) { $domain=$wdomain; }
                   10971:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10972: 
                   10973:     my $which;
                   10974:     if (defined($cenv->{'rndseed'})) {
                   10975: 	$which = $cenv->{'rndseed'};
                   10976:     } else {
                   10977: 	$which =&get_rand_alg($courseid);
                   10978:     }
1.491     albertel 10979:     if (defined(&getCODE())) {
1.1133    foxr     10980: 
1.675     albertel 10981: 	if ($which eq '64bit5') {
                   10982: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10983: 	} elsif ($which eq '64bit4') {
1.575     albertel 10984: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10985: 	} else {
                   10986: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10987: 	}
1.675     albertel 10988:     } elsif ($which eq '64bit5') {
                   10989: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10990:     } elsif ($which eq '64bit4') {
                   10991: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10992:     } elsif ($which eq '64bit3') {
                   10993: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10994:     } elsif ($which eq '64bit2') {
                   10995: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10996:     } elsif ($which eq '64bit') {
                   10997: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10998:     }
                   10999:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11000: }
                   11001: 
                   11002: sub rndseed_32bit {
                   11003:     my ($symb,$courseid,$domain,$username)=@_;
                   11004:     {
                   11005: 	use integer;
                   11006: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11007: 	my $symbseed=numval($symb) << 22;
                   11008: 	my $namechck=unpack("%32C*",$username) << 17;
                   11009: 	my $nameseed=numval($username) << 12;
                   11010: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11011: 	my $courseseed=unpack("%32C*",$courseid);
                   11012: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11013: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11014: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11015: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11016: 	return $num;
                   11017:     }
                   11018: }
                   11019: 
                   11020: sub rndseed_64bit {
                   11021:     my ($symb,$courseid,$domain,$username)=@_;
                   11022:     {
                   11023: 	use integer;
                   11024: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11025: 	my $symbseed=numval($symb) << 10;
                   11026: 	my $namechck=unpack("%32S*",$username);
                   11027: 	
                   11028: 	my $nameseed=numval($username) << 21;
                   11029: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11030: 	my $courseseed=unpack("%32S*",$courseid);
                   11031: 	
                   11032: 	my $num1=$symbchck+$symbseed+$namechck;
                   11033: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11034: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11035: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11036: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11037: 	return "$num1,$num2";
1.155     albertel 11038:     }
1.366     albertel 11039: }
                   11040: 
1.443     albertel 11041: sub rndseed_64bit2 {
                   11042:     my ($symb,$courseid,$domain,$username)=@_;
                   11043:     {
                   11044: 	use integer;
                   11045: 	# strings need to be an even # of cahracters long, it it is odd the
                   11046:         # last characters gets thrown away
                   11047: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11048: 	my $symbseed=numval($symb) << 10;
                   11049: 	my $namechck=unpack("%32S*",$username.' ');
                   11050: 	
                   11051: 	my $nameseed=numval($username) << 21;
1.501     albertel 11052: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11053: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11054: 	
                   11055: 	my $num1=$symbchck+$symbseed+$namechck;
                   11056: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11057: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11058: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11059: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11060: 	return "$num1,$num2";
                   11061:     }
                   11062: }
                   11063: 
                   11064: sub rndseed_64bit3 {
                   11065:     my ($symb,$courseid,$domain,$username)=@_;
                   11066:     {
                   11067: 	use integer;
                   11068: 	# strings need to be an even # of cahracters long, it it is odd the
                   11069:         # last characters gets thrown away
                   11070: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11071: 	my $symbseed=numval2($symb) << 10;
                   11072: 	my $namechck=unpack("%32S*",$username.' ');
                   11073: 	
                   11074: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11075: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11076: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11077: 	
                   11078: 	my $num1=$symbchck+$symbseed+$namechck;
                   11079: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11080: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11081: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11082: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11083: 	
1.503     albertel 11084: 	return "$num1:$num2";
1.443     albertel 11085:     }
                   11086: }
                   11087: 
1.575     albertel 11088: sub rndseed_64bit4 {
                   11089:     my ($symb,$courseid,$domain,$username)=@_;
                   11090:     {
                   11091: 	use integer;
                   11092: 	# strings need to be an even # of cahracters long, it it is odd the
                   11093:         # last characters gets thrown away
                   11094: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11095: 	my $symbseed=numval3($symb) << 10;
                   11096: 	my $namechck=unpack("%32S*",$username.' ');
                   11097: 	
                   11098: 	my $nameseed=numval3($username) << 21;
                   11099: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11100: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11101: 	
                   11102: 	my $num1=$symbchck+$symbseed+$namechck;
                   11103: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11104: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11105: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11106: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11107: 	
1.575     albertel 11108: 	return "$num1:$num2";
                   11109:     }
                   11110: }
                   11111: 
1.675     albertel 11112: sub rndseed_64bit5 {
                   11113:     my ($symb,$courseid,$domain,$username)=@_;
                   11114:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11115:     return "$num1:$num2";
                   11116: }
                   11117: 
1.366     albertel 11118: sub rndseed_CODE_64bit {
                   11119:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11120:     {
1.366     albertel 11121: 	use integer;
1.443     albertel 11122: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11123: 	my $symbseed=numval2($symb);
1.491     albertel 11124: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11125: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11126: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11127: 	my $num1=$symbseed+$CODEchck;
                   11128: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11129: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11130: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11131: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11132: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11133: 	return "$num1:$num2";
1.366     albertel 11134:     }
                   11135: }
                   11136: 
1.575     albertel 11137: sub rndseed_CODE_64bit4 {
                   11138:     my ($symb,$courseid,$domain,$username)=@_;
                   11139:     {
                   11140: 	use integer;
                   11141: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11142: 	my $symbseed=numval3($symb);
                   11143: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11144: 	my $CODEseed=numval3(&getCODE());
                   11145: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11146: 	my $num1=$symbseed+$CODEchck;
                   11147: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11148: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11149: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11150: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11151: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11152: 	return "$num1:$num2";
                   11153:     }
                   11154: }
                   11155: 
1.675     albertel 11156: sub rndseed_CODE_64bit5 {
                   11157:     my ($symb,$courseid,$domain,$username)=@_;
                   11158:     my $code = &getCODE();
                   11159:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11160:     return "$num1:$num2";
                   11161: }
                   11162: 
1.366     albertel 11163: sub setup_random_from_rndseed {
                   11164:     my ($rndseed)=@_;
1.503     albertel 11165:     if ($rndseed =~/([,:])/) {
                   11166: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11167: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11168:     } else {
                   11169: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11170:     }
1.36      albertel 11171: }
                   11172: 
1.474     albertel 11173: sub latest_receipt_algorithm_id {
1.835     albertel 11174:     return 'receipt3';
1.474     albertel 11175: }
                   11176: 
1.480     www      11177: sub recunique {
                   11178:     my $fucourseid=shift;
                   11179:     my $unique;
1.835     albertel 11180:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11181: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11182: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11183:     } else {
                   11184: 	$unique=$perlvar{'lonReceipt'};
                   11185:     }
                   11186:     return unpack("%32C*",$unique);
                   11187: }
                   11188: 
                   11189: sub recprefix {
                   11190:     my $fucourseid=shift;
                   11191:     my $prefix;
1.835     albertel 11192:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11193: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11194: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11195:     } else {
                   11196: 	$prefix=$perlvar{'lonHostID'};
                   11197:     }
                   11198:     return unpack("%32C*",$prefix);
                   11199: }
                   11200: 
1.76      www      11201: sub ireceipt {
1.474     albertel 11202:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11203: 
                   11204:     my $return =&recprefix($fucourseid).'-';
                   11205: 
                   11206:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11207: 	$env{'request.state'} eq 'construct') {
                   11208: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11209: 	return $return;
                   11210:     }
                   11211: 
1.76      www      11212:     my $cuname=unpack("%32C*",$funame);
                   11213:     my $cudom=unpack("%32C*",$fudom);
                   11214:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11215:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11216:     my $cunique=&recunique($fucourseid);
1.474     albertel 11217:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11218:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11219: 
1.790     albertel 11220: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11221: 			       
                   11222: 	$return.= ($cunique%$cuname+
                   11223: 		   $cunique%$cudom+
                   11224: 		   $cusymb%$cuname+
                   11225: 		   $cusymb%$cudom+
                   11226: 		   $cucourseid%$cuname+
                   11227: 		   $cucourseid%$cudom+
                   11228: 		   $cpart%$cuname+
                   11229: 		   $cpart%$cudom);
                   11230:     } else {
                   11231: 	$return.= ($cunique%$cuname+
                   11232: 		   $cunique%$cudom+
                   11233: 		   $cusymb%$cuname+
                   11234: 		   $cusymb%$cudom+
                   11235: 		   $cucourseid%$cuname+
                   11236: 		   $cucourseid%$cudom);
                   11237:     }
                   11238:     return $return;
1.76      www      11239: }
                   11240: 
                   11241: sub receipt {
1.474     albertel 11242:     my ($part)=@_;
1.790     albertel 11243:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11244:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11245: }
1.260     ng       11246: 
1.790     albertel 11247: sub whichuser {
                   11248:     my ($passedsymb)=@_;
                   11249:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11250:     if (defined($env{'form.grade_symb'})) {
                   11251: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11252: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11253: 	if (!$allowed &&
                   11254: 	    exists($env{'request.course.sec'}) &&
                   11255: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11256: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11257: 			      '/'.$env{'request.course.sec'});
                   11258: 	}
                   11259: 	if ($allowed) {
                   11260: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11261: 	    $courseid=$tmp_courseid;
                   11262: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11263: 	    ($name)=&get_env_multiple('form.grade_username');
                   11264: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11265: 	}
                   11266:     }
                   11267:     if (!$passedsymb) {
                   11268: 	$symb=&symbread();
                   11269:     } else {
                   11270: 	$symb=$passedsymb;
                   11271:     }
                   11272:     $courseid=$env{'request.course.id'};
                   11273:     $domain=$env{'user.domain'};
                   11274:     $name=$env{'user.name'};
                   11275:     if ($name eq 'public' && $domain eq 'public') {
                   11276: 	if (!defined($env{'form.username'})) {
                   11277: 	    $env{'form.username'}.=time.rand(10000000);
                   11278: 	}
                   11279: 	$name.=$env{'form.username'};
                   11280:     }
                   11281:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11282: 
                   11283: }
                   11284: 
1.36      albertel 11285: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11286: # returns either the contents of the file or 
                   11287: # -1 if the file doesn't exist
1.481     raeburn  11288: #
                   11289: # if the target is a file that was uploaded via DOCS, 
                   11290: # a check will be made to see if a current copy exists on the local server,
                   11291: # if it does this will be served, otherwise a copy will be retrieved from
                   11292: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11293: # the local server.   
1.472     albertel 11294: 
1.36      albertel 11295: sub getfile {
1.538     albertel 11296:     my ($file) = @_;
1.609     banghart 11297:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11298:     &repcopy($file);
                   11299:     return &readfile($file);
                   11300: }
                   11301: 
                   11302: sub repcopy_userfile {
                   11303:     my ($file)=@_;
1.1142    raeburn  11304:     my $londocroot = $perlvar{'lonDocRoot'};
                   11305:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11306:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11307:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11308: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11309:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11310:     if (-e "$file") {
1.828     www      11311: # we already have a local copy, check it out
1.538     albertel 11312: 	my @fileinfo = stat($file);
1.828     www      11313: 	my $rtncode;
                   11314: 	my $info;
1.538     albertel 11315: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11316: 	if ($lwpresp ne 'ok') {
1.828     www      11317: # there is no such file anymore, even though we had a local copy
1.482     albertel 11318: 	    if ($rtncode eq '404') {
1.538     albertel 11319: 		unlink($file);
1.482     albertel 11320: 	    }
                   11321: 	    return -1;
                   11322: 	}
                   11323: 	if ($info < $fileinfo[9]) {
1.828     www      11324: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11325: 	    return 'ok';
1.828     www      11326: 	} else {
                   11327: # the file is outdated, get rid of it
                   11328: 	    unlink($file);
1.482     albertel 11329: 	}
1.828     www      11330:     }
                   11331: # one way or the other, at this point, we don't have the file
                   11332: # construct the correct path for the file
                   11333:     my @parts = ($cdom,$cnum); 
                   11334:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11335: 	push @parts, split(/\//,$1);
                   11336:     }
                   11337:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11338:     foreach my $part (@parts) {
                   11339: 	$path .= '/'.$part;
                   11340: 	if (!-e $path) {
                   11341: 	    mkdir($path,0770);
1.482     albertel 11342: 	}
                   11343:     }
1.828     www      11344: # now the path exists for sure
                   11345: # get a user agent
                   11346:     my $ua=new LWP::UserAgent;
                   11347:     my $transferfile=$file.'.in.transfer';
                   11348: # FIXME: this should flock
                   11349:     if (-e $transferfile) { return 'ok'; }
                   11350:     my $request;
                   11351:     $uri=~s/^\///;
1.980     raeburn  11352:     my $homeserver = &homeserver($cnum,$cdom);
                   11353:     my $protocol = $protocol{$homeserver};
                   11354:     $protocol = 'http' if ($protocol ne 'https');
                   11355:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11356:     my $response=$ua->request($request,$transferfile);
                   11357: # did it work?
                   11358:     if ($response->is_error()) {
                   11359: 	unlink($transferfile);
                   11360: 	&logthis("Userfile repcopy failed for $uri");
                   11361: 	return -1;
                   11362:     }
                   11363: # worked, rename the transfer file
                   11364:     rename($transferfile,$file);
1.607     raeburn  11365:     return 'ok';
1.481     raeburn  11366: }
                   11367: 
1.517     albertel 11368: sub tokenwrapper {
                   11369:     my $uri=shift;
1.980     raeburn  11370:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11371:     $uri=~s|^/||;
1.620     albertel 11372:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11373:     my $token=$1;
1.552     albertel 11374:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11375:     if ($udom && $uname && $file) {
                   11376: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11377:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11378:         my $homeserver = &homeserver($uname,$udom);
                   11379:         my $protocol = $protocol{$homeserver};
                   11380:         $protocol = 'http' if ($protocol ne 'https');
                   11381:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11382:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11383:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11384:     } else {
                   11385:         return '/adm/notfound.html';
                   11386:     }
                   11387: }
                   11388: 
1.828     www      11389: # call with reqtype HEAD: get last modification time
                   11390: # call with reqtype GET: get the file contents
                   11391: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11392: #
1.481     raeburn  11393: sub getuploaded {
                   11394:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11395:     $uri=~s/^\///;
1.980     raeburn  11396:     my $homeserver = &homeserver($cnum,$cdom);
                   11397:     my $protocol = $protocol{$homeserver};
                   11398:     $protocol = 'http' if ($protocol ne 'https');
                   11399:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11400:     my $ua=new LWP::UserAgent;
                   11401:     my $request=new HTTP::Request($reqtype,$uri);
                   11402:     my $response=$ua->request($request);
                   11403:     $$rtncode = $response->code;
1.482     albertel 11404:     if (! $response->is_success()) {
                   11405: 	return 'failed';
                   11406:     }      
                   11407:     if ($reqtype eq 'HEAD') {
1.486     www      11408: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11409:     } elsif ($reqtype eq 'GET') {
                   11410: 	$$info = $response->content;
1.472     albertel 11411:     }
1.482     albertel 11412:     return 'ok';
1.36      albertel 11413: }
                   11414: 
1.481     raeburn  11415: sub readfile {
                   11416:     my $file = shift;
                   11417:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11418:     my $fh;
                   11419:     open($fh,"<$file");
                   11420:     my $a='';
1.800     albertel 11421:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11422:     return $a;
                   11423: }
                   11424: 
1.36      albertel 11425: sub filelocation {
1.590     banghart 11426:     my ($dir,$file) = @_;
                   11427:     my $location;
                   11428:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11429: 
                   11430:     if ($file =~ m-^/adm/-) {
                   11431: 	$file=~s-^/adm/wrapper/-/-;
                   11432: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11433:     }
1.882     albertel 11434: 
1.1139    www      11435:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11436:         $location = $file;
1.609     banghart 11437:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11438:         my ($udom,$uname,$filename)=
1.811     albertel 11439:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11440:         my $home=&homeserver($uname,$udom);
                   11441:         my $is_me=0;
                   11442:         my @ids=&current_machine_ids();
                   11443:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11444:         if ($is_me) {
1.1117    foxr     11445:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11446:         } else {
                   11447:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11448:   	      $udom.'/'.$uname.'/'.$filename;
                   11449:         }
1.882     albertel 11450:     } elsif ($file =~ m-^/adm/-) {
                   11451: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11452:     } else {
                   11453:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11454:         $file=~s:^/(res|priv)/:/:;
                   11455:         my $space=$1;
1.590     banghart 11456:         if ( !( $file =~ m:^/:) ) {
                   11457:             $location = $dir. '/'.$file;
                   11458:         } else {
1.1142    raeburn  11459:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11460:         }
1.59      albertel 11461:     }
1.590     banghart 11462:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11463:     while ($location=~m{/\.\./}) {
                   11464: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11465: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11466: 	} else {
                   11467: 	    $location=~ s{/\.\./}{/}g;
                   11468: 	}
                   11469:     } #remove dir/..
1.590     banghart 11470:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11471:     return $location;
1.46      www      11472: }
1.36      albertel 11473: 
1.46      www      11474: sub hreflocation {
                   11475:     my ($dir,$file)=@_;
1.980     raeburn  11476:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11477: 	$file=filelocation($dir,$file);
1.700     albertel 11478:     } elsif ($file=~m-^/adm/-) {
                   11479: 	$file=~s-^/adm/wrapper/-/-;
                   11480: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11481:     }
                   11482:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11483: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11484:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11485: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11486: 	        {/uploaded/$1/$2/}x;
1.46      www      11487:     }
1.913     albertel 11488:     if ($file=~ m{^/userfiles/}) {
                   11489: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11490:     }
1.462     albertel 11491:     return $file;
1.465     albertel 11492: }
                   11493: 
1.1139    www      11494: 
                   11495: 
                   11496: 
                   11497: 
1.465     albertel 11498: sub current_machine_domains {
1.853     albertel 11499:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11500: }
                   11501: 
                   11502: sub machine_domains {
                   11503:     my ($hostname) = @_;
1.465     albertel 11504:     my @domains;
1.838     albertel 11505:     my %hostname = &all_hostnames();
1.465     albertel 11506:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11507: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11508: 	if ($hostname eq $name) {
1.844     albertel 11509: 	    push(@domains,&host_domain($id));
1.465     albertel 11510: 	}
                   11511:     }
                   11512:     return @domains;
                   11513: }
                   11514: 
                   11515: sub current_machine_ids {
1.853     albertel 11516:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11517: }
                   11518: 
                   11519: sub machine_ids {
                   11520:     my ($hostname) = @_;
                   11521:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11522:     my @ids;
1.888     albertel 11523:     my %name_to_host = &all_names();
1.889     albertel 11524:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11525: 	return @{ $name_to_host{$hostname} };
                   11526:     }
                   11527:     return;
1.31      www      11528: }
                   11529: 
1.824     raeburn  11530: sub additional_machine_domains {
                   11531:     my @domains;
                   11532:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11533:     while( my $line = <$fh>) {
                   11534:         $line =~ s/\s//g;
                   11535:         push(@domains,$line);
                   11536:     }
                   11537:     return @domains;
                   11538: }
                   11539: 
                   11540: sub default_login_domain {
                   11541:     my $domain = $perlvar{'lonDefDomain'};
                   11542:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11543:     foreach my $posdom (&current_machine_domains(),
                   11544:                         &additional_machine_domains()) {
                   11545:         if (lc($posdom) eq lc($testdomain)) {
                   11546:             $domain=$posdom;
                   11547:             last;
                   11548:         }
                   11549:     }
                   11550:     return $domain;
                   11551: }
                   11552: 
1.31      www      11553: # ------------------------------------------------------------- Declutters URLs
                   11554: 
                   11555: sub declutter {
                   11556:     my $thisfn=shift;
1.569     albertel 11557:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11558:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11559:     $thisfn=~s/^\///;
1.697     albertel 11560:     $thisfn=~s|^adm/wrapper/||;
                   11561:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11562:     $thisfn=~s/^res\///;
1.1172    bisitz   11563:     $thisfn=~s/^priv\///;
1.1032    raeburn  11564:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11565:         $thisfn=~s/\?.+$//;
                   11566:     }
1.268     www      11567:     return $thisfn;
                   11568: }
                   11569: 
                   11570: # ------------------------------------------------------------- Clutter up URLs
                   11571: 
                   11572: sub clutter {
                   11573:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11574:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11575: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11576:        $thisfn='/res'.$thisfn; 
                   11577:     }
1.1031    raeburn  11578:     if ($thisfn !~m|^/adm|) {
                   11579: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11580: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11581: 	} else {
                   11582: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11583: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11584: 	    if ($embstyle eq 'ssi'
                   11585: 		|| ($embstyle eq 'hdn')
                   11586: 		|| ($embstyle eq 'rat')
                   11587: 		|| ($embstyle eq 'prv')
                   11588: 		|| ($embstyle eq 'ign')) {
                   11589: 		#do nothing with these
                   11590: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11591: 		|| ($embstyle eq 'emb')
                   11592: 		|| ($embstyle eq 'wrp')) {
                   11593: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11594: 	    } elsif ($embstyle eq 'unk'
                   11595: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11596: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11597: 	    } else {
1.718     www      11598: #		&logthis("Got a blank emb style");
1.695     albertel 11599: 	    }
1.694     albertel 11600: 	}
                   11601:     }
1.31      www      11602:     return $thisfn;
1.12      www      11603: }
                   11604: 
1.787     albertel 11605: sub clutter_with_no_wrapper {
                   11606:     my $uri = &clutter(shift);
                   11607:     if ($uri =~ m-^/adm/-) {
                   11608: 	$uri =~ s-^/adm/wrapper/-/-;
                   11609: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11610:     }
                   11611:     return $uri;
                   11612: }
                   11613: 
1.557     albertel 11614: sub freeze_escape {
                   11615:     my ($value)=@_;
                   11616:     if (ref($value)) {
                   11617: 	$value=&nfreeze($value);
                   11618: 	return '__FROZEN__'.&escape($value);
                   11619:     }
                   11620:     return &escape($value);
                   11621: }
                   11622: 
1.11      www      11623: 
1.557     albertel 11624: sub thaw_unescape {
                   11625:     my ($value)=@_;
                   11626:     if ($value =~ /^__FROZEN__/) {
                   11627: 	substr($value,0,10,undef);
                   11628: 	$value=&unescape($value);
                   11629: 	return &thaw($value);
                   11630:     }
                   11631:     return &unescape($value);
                   11632: }
                   11633: 
1.436     albertel 11634: sub correct_line_ends {
                   11635:     my ($result)=@_;
                   11636:     $$result =~s/\r\n/\n/mg;
                   11637:     $$result =~s/\r/\n/mg;
1.415     albertel 11638: }
1.1       albertel 11639: # ================================================================ Main Program
                   11640: 
1.184     www      11641: sub goodbye {
1.204     albertel 11642:    &logthis("Starting Shut down");
1.443     albertel 11643: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11644:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11645: #converted
1.599     albertel 11646: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11647:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11648: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11649: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11650: #1.1 only
1.870     albertel 11651: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11652: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11653: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11654: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11655:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11656:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11657:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11658:    &flushcourselogs();
                   11659:    &logthis("Shutting down");
                   11660: }
                   11661: 
1.852     albertel 11662: sub get_dns {
1.1210    raeburn  11663:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11664:     if (!$ignore_cache) {
                   11665: 	my ($content,$cached)=
                   11666: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11667: 	if ($cached) {
1.1210    raeburn  11668: 	    &$func($content,$hashref);
1.869     albertel 11669: 	    return;
                   11670: 	}
                   11671:     }
                   11672: 
                   11673:     my %alldns;
1.852     albertel 11674:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11675:     foreach my $dns (<$config>) {
                   11676: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11677:         my $line = $1;
                   11678:         my ($host,$protocol) = split(/:/,$line);
                   11679:         if ($protocol ne 'https') {
                   11680:             $protocol = 'http';
                   11681:         }
                   11682: 	$alldns{$host} = $protocol;
1.869     albertel 11683:     }
                   11684:     while (%alldns) {
                   11685: 	my ($dns) = keys(%alldns);
1.852     albertel 11686: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11687:         $ua->timeout(30);
1.979     raeburn  11688: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11689: 	my $response=$ua->request($request);
1.979     raeburn  11690:         delete($alldns{$dns});
1.852     albertel 11691: 	next if ($response->is_error());
                   11692: 	my @content = split("\n",$response->content);
1.1210    raeburn  11693: 	unless ($nocache) {
1.1219    raeburn  11694: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  11695: 	}
                   11696: 	&$func(\@content,$hashref);
1.869     albertel 11697: 	return;
1.852     albertel 11698:     }
                   11699:     close($config);
1.871     albertel 11700:     my $which = (split('/',$url))[3];
                   11701:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11702:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11703:     my @content = <$config>;
1.1210    raeburn  11704:     &$func(\@content,$hashref);
                   11705:     return;
                   11706: }
                   11707: 
                   11708: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11709: sub parse_dns_checksums_tab {
1.1210    raeburn  11710:     my ($lines,$hashref) = @_;
                   11711:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11712:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11713:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11714:     my (%chksum,%revnum);
                   11715:     if (ref($lines) eq 'ARRAY') {
                   11716:         chomp(@{$lines});
1.1238    raeburn  11717:         my $version = shift(@{$lines});
                   11718:         if ($version eq $release) {  
1.1210    raeburn  11719:             foreach my $line (@{$lines}) {
1.1238    raeburn  11720:                 my ($file,$version,$shasum) = split(/,/,$line);
                   11721:                 $chksum{$file} = $shasum;
                   11722:                 $revnum{$file} = $version;
1.1210    raeburn  11723:             }
                   11724:             if (ref($hashref) eq 'HASH') {
                   11725:                 %{$hashref} = (
                   11726:                                 sums     => \%chksum,
                   11727:                                 versions => \%revnum,
                   11728:                               );
                   11729:             }
                   11730:         }
                   11731:     }
1.869     albertel 11732:     return;
1.852     albertel 11733: }
1.1210    raeburn  11734: 
                   11735: sub fetch_dns_checksums {
1.1238    raeburn  11736:     my %checksums;
                   11737:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11738:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11739:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11740:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  11741:              \%checksums);
1.1210    raeburn  11742:     return \%checksums;
                   11743: }
                   11744: 
1.327     albertel 11745: # ------------------------------------------------------------ Read domain file
                   11746: {
1.852     albertel 11747:     my $loaded;
1.846     albertel 11748:     my %domain;
                   11749: 
1.852     albertel 11750:     sub parse_domain_tab {
                   11751: 	my ($lines) = @_;
                   11752: 	foreach my $line (@$lines) {
                   11753: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11754: 
1.846     albertel 11755: 	    chomp($line);
1.852     albertel 11756: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11757: 	    my %this_domain;
                   11758: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11759: 			       'lang_def', 'city', 'longi', 'lati',
                   11760: 			       'primary') {
                   11761: 		$this_domain{$field} = shift(@elements);
                   11762: 	    }
                   11763: 	    $domain{$name} = \%this_domain;
1.852     albertel 11764: 	}
                   11765:     }
1.864     albertel 11766: 
                   11767:     sub reset_domain_info {
                   11768: 	undef($loaded);
                   11769: 	undef(%domain);
                   11770:     }
                   11771: 
1.852     albertel 11772:     sub load_domain_tab {
1.869     albertel 11773: 	my ($ignore_cache) = @_;
                   11774: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11775: 	my $fh;
                   11776: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11777: 	    my @lines = <$fh>;
                   11778: 	    &parse_domain_tab(\@lines);
1.448     albertel 11779: 	}
1.852     albertel 11780: 	close($fh);
                   11781: 	$loaded = 1;
1.327     albertel 11782:     }
1.846     albertel 11783: 
                   11784:     sub domain {
1.852     albertel 11785: 	&load_domain_tab() if (!$loaded);
                   11786: 
1.846     albertel 11787: 	my ($name,$what) = @_;
                   11788: 	return if ( !exists($domain{$name}) );
                   11789: 
                   11790: 	if (!$what) {
                   11791: 	    return $domain{$name}{'description'};
                   11792: 	}
                   11793: 	return $domain{$name}{$what};
                   11794:     }
1.974     raeburn  11795: 
                   11796:     sub domain_info {
                   11797:         &load_domain_tab() if (!$loaded);
                   11798:         return %domain;
                   11799:     }
                   11800: 
1.327     albertel 11801: }
                   11802: 
                   11803: 
1.1       albertel 11804: # ------------------------------------------------------------- Read hosts file
                   11805: {
1.838     albertel 11806:     my %hostname;
1.844     albertel 11807:     my %hostdom;
1.845     albertel 11808:     my %libserv;
1.852     albertel 11809:     my $loaded;
1.888     albertel 11810:     my %name_to_host;
1.1074    raeburn  11811:     my %internetdom;
1.1107    raeburn  11812:     my %LC_dns_serv;
1.852     albertel 11813: 
                   11814:     sub parse_hosts_tab {
                   11815: 	my ($file) = @_;
                   11816: 	foreach my $configline (@$file) {
                   11817: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11818:             chomp($configline);
                   11819: 	    if ($configline =~ /^\^/) {
                   11820:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11821:                     $LC_dns_serv{$1} = 1;
                   11822:                 }
                   11823:                 next;
                   11824:             }
1.1074    raeburn  11825: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11826: 	    $name=~s/\s//g;
                   11827: 	    if ($id && $domain && $role && $name) {
                   11828: 		$hostname{$id}=$name;
1.888     albertel 11829: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11830: 		$hostdom{$id}=$domain;
                   11831: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11832:                 if (defined($protocol)) {
                   11833:                     if ($protocol eq 'https') {
                   11834:                         $protocol{$id} = $protocol;
                   11835:                     } else {
                   11836:                         $protocol{$id} = 'http'; 
                   11837:                     }
1.968     raeburn  11838:                 } else {
1.969     raeburn  11839:                     $protocol{$id} = 'http';
1.968     raeburn  11840:                 }
1.1074    raeburn  11841:                 if (defined($intdom)) {
                   11842:                     $internetdom{$id} = $intdom;
                   11843:                 }
1.852     albertel 11844: 	    }
                   11845: 	}
                   11846:     }
1.864     albertel 11847:     
                   11848:     sub reset_hosts_info {
1.897     albertel 11849: 	&purge_remembered();
1.864     albertel 11850: 	&reset_domain_info();
                   11851: 	&reset_hosts_ip_info();
1.892     albertel 11852: 	undef(%name_to_host);
1.864     albertel 11853: 	undef(%hostname);
                   11854: 	undef(%hostdom);
                   11855: 	undef(%libserv);
                   11856: 	undef($loaded);
                   11857:     }
1.1       albertel 11858: 
1.852     albertel 11859:     sub load_hosts_tab {
1.869     albertel 11860: 	my ($ignore_cache) = @_;
                   11861: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11862: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11863: 	my @config = <$config>;
                   11864: 	&parse_hosts_tab(\@config);
                   11865: 	close($config);
                   11866: 	$loaded=1;
1.1       albertel 11867:     }
1.852     albertel 11868: 
1.838     albertel 11869:     sub hostname {
1.852     albertel 11870: 	&load_hosts_tab() if (!$loaded);
                   11871: 
1.838     albertel 11872: 	my ($lonid) = @_;
                   11873: 	return $hostname{$lonid};
                   11874:     }
1.845     albertel 11875: 
1.838     albertel 11876:     sub all_hostnames {
1.852     albertel 11877: 	&load_hosts_tab() if (!$loaded);
                   11878: 
1.838     albertel 11879: 	return %hostname;
                   11880:     }
1.845     albertel 11881: 
1.888     albertel 11882:     sub all_names {
                   11883: 	&load_hosts_tab() if (!$loaded);
                   11884: 
                   11885: 	return %name_to_host;
                   11886:     }
                   11887: 
1.974     raeburn  11888:     sub all_host_domain {
                   11889:         &load_hosts_tab() if (!$loaded);
                   11890:         return %hostdom;
                   11891:     }
                   11892: 
1.845     albertel 11893:     sub is_library {
1.852     albertel 11894: 	&load_hosts_tab() if (!$loaded);
                   11895: 
1.845     albertel 11896: 	return exists($libserv{$_[0]});
                   11897:     }
                   11898: 
                   11899:     sub all_library {
1.852     albertel 11900: 	&load_hosts_tab() if (!$loaded);
                   11901: 
1.845     albertel 11902: 	return %libserv;
                   11903:     }
                   11904: 
1.1062    droeschl 11905:     sub unique_library {
                   11906: 	#2x reverse removes all hostnames that appear more than once
                   11907:         my %unique = reverse &all_library();
                   11908:         return reverse %unique;
                   11909:     }
                   11910: 
1.841     albertel 11911:     sub get_servers {
1.852     albertel 11912: 	&load_hosts_tab() if (!$loaded);
                   11913: 
1.841     albertel 11914: 	my ($domain,$type) = @_;
                   11915: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11916: 	                                          : %hostname;
                   11917: 	my %result;
1.842     albertel 11918: 	if (ref($domain) eq 'ARRAY') {
                   11919: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11920: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11921: 		    $result{$host} = $hostname;
                   11922: 		}
                   11923: 	    }
                   11924: 	} else {
                   11925: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11926: 		if ($hostdom{$host} eq $domain) {
                   11927: 		    $result{$host} = $hostname;
                   11928: 		}
1.841     albertel 11929: 	    }
                   11930: 	}
                   11931: 	return %result;
                   11932:     }
1.845     albertel 11933: 
1.1062    droeschl 11934:     sub get_unique_servers {
                   11935:         my %unique = reverse &get_servers(@_);
                   11936: 	return reverse %unique;
                   11937:     }
                   11938: 
1.844     albertel 11939:     sub host_domain {
1.852     albertel 11940: 	&load_hosts_tab() if (!$loaded);
                   11941: 
1.844     albertel 11942: 	my ($lonid) = @_;
                   11943: 	return $hostdom{$lonid};
                   11944:     }
                   11945: 
1.841     albertel 11946:     sub all_domains {
1.852     albertel 11947: 	&load_hosts_tab() if (!$loaded);
                   11948: 
1.841     albertel 11949: 	my %seen;
                   11950: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11951: 	return @uniq;
                   11952:     }
1.1074    raeburn  11953: 
                   11954:     sub internet_dom {
                   11955:         &load_hosts_tab() if (!$loaded);
                   11956: 
                   11957:         my ($lonid) = @_;
                   11958:         return $internetdom{$lonid};
                   11959:     }
1.1107    raeburn  11960: 
                   11961:     sub is_LC_dns {
                   11962:         &load_hosts_tab() if (!$loaded);
                   11963: 
                   11964:         my ($hostname) = @_;
                   11965:         return exists($LC_dns_serv{$hostname});
                   11966:     }
                   11967: 
1.1       albertel 11968: }
                   11969: 
1.847     albertel 11970: { 
                   11971:     my %iphost;
1.856     albertel 11972:     my %name_to_ip;
                   11973:     my %lonid_to_ip;
1.869     albertel 11974: 
1.847     albertel 11975:     sub get_hosts_from_ip {
                   11976: 	my ($ip) = @_;
                   11977: 	my %iphosts = &get_iphost();
                   11978: 	if (ref($iphosts{$ip})) {
                   11979: 	    return @{$iphosts{$ip}};
                   11980: 	}
                   11981: 	return;
1.839     albertel 11982:     }
1.864     albertel 11983:     
                   11984:     sub reset_hosts_ip_info {
                   11985: 	undef(%iphost);
                   11986: 	undef(%name_to_ip);
                   11987: 	undef(%lonid_to_ip);
                   11988:     }
1.856     albertel 11989: 
                   11990:     sub get_host_ip {
                   11991: 	my ($lonid) = @_;
                   11992: 	if (exists($lonid_to_ip{$lonid})) {
                   11993: 	    return $lonid_to_ip{$lonid};
                   11994: 	}
                   11995: 	my $name=&hostname($lonid);
                   11996:    	my $ip = gethostbyname($name);
                   11997: 	return if (!$ip || length($ip) ne 4);
                   11998: 	$ip=inet_ntoa($ip);
                   11999: 	$name_to_ip{$name}   = $ip;
                   12000: 	$lonid_to_ip{$lonid} = $ip;
                   12001: 	return $ip;
                   12002:     }
1.847     albertel 12003:     
                   12004:     sub get_iphost {
1.869     albertel 12005: 	my ($ignore_cache) = @_;
1.894     albertel 12006: 
1.869     albertel 12007: 	if (!$ignore_cache) {
                   12008: 	    if (%iphost) {
                   12009: 		return %iphost;
                   12010: 	    }
                   12011: 	    my ($ip_info,$cached)=
                   12012: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12013: 	    if ($cached) {
                   12014: 		%iphost      = %{$ip_info->[0]};
                   12015: 		%name_to_ip  = %{$ip_info->[1]};
                   12016: 		%lonid_to_ip = %{$ip_info->[2]};
                   12017: 		return %iphost;
                   12018: 	    }
                   12019: 	}
1.894     albertel 12020: 
                   12021: 	# get yesterday's info for fallback
                   12022: 	my %old_name_to_ip;
                   12023: 	my ($ip_info,$cached)=
                   12024: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12025: 	if ($cached) {
                   12026: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12027: 	}
                   12028: 
1.888     albertel 12029: 	my %name_to_host = &all_names();
                   12030: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12031: 	    my $ip;
                   12032: 	    if (!exists($name_to_ip{$name})) {
                   12033: 		$ip = gethostbyname($name);
                   12034: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12035: 		    if (defined($old_name_to_ip{$name})) {
                   12036: 			$ip = $old_name_to_ip{$name};
                   12037: 			&logthis("Can't find $name defaulting to old $ip");
                   12038: 		    } else {
                   12039: 			&logthis("Name $name no IP found");
                   12040: 			next;
                   12041: 		    }
                   12042: 		} else {
                   12043: 		    $ip=inet_ntoa($ip);
1.847     albertel 12044: 		}
                   12045: 		$name_to_ip{$name} = $ip;
                   12046: 	    } else {
                   12047: 		$ip = $name_to_ip{$name};
1.653     albertel 12048: 	    }
1.888     albertel 12049: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12050: 		$lonid_to_ip{$id} = $ip;
                   12051: 	    }
                   12052: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12053: 	}
1.1219    raeburn  12054: 	&do_cache_new('iphost','iphost',
                   12055: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12056: 		      48*60*60);
1.869     albertel 12057: 
1.847     albertel 12058: 	return %iphost;
1.598     albertel 12059:     }
                   12060: 
1.992     raeburn  12061:     #
                   12062:     #  Given a DNS returns the loncapa host name for that DNS 
                   12063:     # 
                   12064:     sub host_from_dns {
                   12065:         my ($dns) = @_;
                   12066:         my @hosts;
                   12067:         my $ip;
                   12068: 
1.993     raeburn  12069:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12070:             $ip = $name_to_ip{$dns};
                   12071:         }
                   12072:         if (!$ip) {
                   12073:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12074:             if (length($ip) == 4) { 
                   12075: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12076:             }
                   12077:         }
                   12078:         if ($ip) {
                   12079: 	    @hosts = get_hosts_from_ip($ip);
                   12080: 	    return $hosts[0];
                   12081:         }
                   12082:         return undef;
1.986     foxr     12083:     }
1.992     raeburn  12084: 
1.1074    raeburn  12085:     sub get_internet_names {
                   12086:         my ($lonid) = @_;
                   12087:         return if ($lonid eq '');
                   12088:         my ($idnref,$cached)=
                   12089:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12090:         if ($cached) {
                   12091:             return $idnref;
                   12092:         }
                   12093:         my $ip = &get_host_ip($lonid);
                   12094:         my @hosts = &get_hosts_from_ip($ip);
                   12095:         my %iphost = &get_iphost();
                   12096:         my (@idns,%seen);
                   12097:         foreach my $id (@hosts) {
                   12098:             my $dom = &host_domain($id);
                   12099:             my $prim_id = &domain($dom,'primary');
                   12100:             my $prim_ip = &get_host_ip($prim_id);
                   12101:             next if ($seen{$prim_ip});
                   12102:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12103:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12104:                     my $intdom = &internet_dom($id);
                   12105:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12106:                         push(@idns,$intdom);
                   12107:                     }
                   12108:                 }
                   12109:             }
                   12110:             $seen{$prim_ip} = 1;
                   12111:         }
1.1219    raeburn  12112:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12113:     }
                   12114: 
1.986     foxr     12115: }
                   12116: 
1.1079    raeburn  12117: sub all_loncaparevs {
                   12118:     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);
                   12119: }
                   12120: 
1.1227    raeburn  12121: # ---------------------------------------------------------- Read loncaparev table
                   12122: {
                   12123:     sub load_loncaparevs { 
                   12124:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12125:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12126:                 while (my $configline=<$config>) {
                   12127:                     chomp($configline);
                   12128:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12129:                     $loncaparevs{$hostid}=$loncaparev;
                   12130:                 }
                   12131:                 close($config);
                   12132:             }
                   12133:         }
                   12134:     }
                   12135: }
                   12136: 
                   12137: # ---------------------------------------------------------- Read serverhostID table
                   12138: {
                   12139:     sub load_serverhomeIDs {
                   12140:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12141:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12142:                 while (my $configline=<$config>) {
                   12143:                     chomp($configline);
                   12144:                     my ($name,$id)=split(/:/,$configline);
                   12145:                     $serverhomeIDs{$name}=$id;
                   12146:                 }
                   12147:                 close($config);
                   12148:             }
                   12149:         }
                   12150:     }
                   12151: }
                   12152: 
                   12153: 
1.862     albertel 12154: BEGIN {
                   12155: 
                   12156: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12157:     unless ($readit) {
                   12158: {
                   12159:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12160:     %perlvar = (%perlvar,%{$configvars});
                   12161: }
                   12162: 
                   12163: 
1.1       albertel 12164: # ------------------------------------------------------ Read spare server file
                   12165: {
1.448     albertel 12166:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12167: 
                   12168:     while (my $configline=<$config>) {
                   12169:        chomp($configline);
1.284     matthew  12170:        if ($configline) {
1.784     albertel 12171: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12172: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12173: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12174:        }
                   12175:     }
1.448     albertel 12176:     close($config);
1.1       albertel 12177: }
1.11      www      12178: # ------------------------------------------------------------ Read permissions
                   12179: {
1.448     albertel 12180:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12181: 
                   12182:     while (my $configline=<$config>) {
1.448     albertel 12183: 	chomp($configline);
                   12184: 	if ($configline) {
                   12185: 	    my ($role,$perm)=split(/ /,$configline);
                   12186: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12187: 	}
1.11      www      12188:     }
1.448     albertel 12189:     close($config);
1.11      www      12190: }
                   12191: 
                   12192: # -------------------------------------------- Read plain texts for permissions
                   12193: {
1.448     albertel 12194:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12195: 
                   12196:     while (my $configline=<$config>) {
1.448     albertel 12197: 	chomp($configline);
                   12198: 	if ($configline) {
1.742     raeburn  12199: 	    my ($short,@plain)=split(/:/,$configline);
                   12200:             %{$prp{$short}} = ();
                   12201: 	    if (@plain > 0) {
                   12202:                 $prp{$short}{'std'} = $plain[0];
                   12203:                 for (my $i=1; $i<@plain; $i++) {
                   12204:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12205:                 }
                   12206:             }
1.448     albertel 12207: 	}
1.135     www      12208:     }
1.448     albertel 12209:     close($config);
1.135     www      12210: }
                   12211: 
                   12212: # ---------------------------------------------------------- Read package table
                   12213: {
1.448     albertel 12214:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12215: 
                   12216:     while (my $configline=<$config>) {
1.483     albertel 12217: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12218: 	chomp($configline);
                   12219: 	my ($short,$plain)=split(/:/,$configline);
                   12220: 	my ($pack,$name)=split(/\&/,$short);
                   12221: 	if ($plain ne '') {
                   12222: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12223: 	    $packagetab{$short}=$plain; 
                   12224: 	}
1.11      www      12225:     }
1.448     albertel 12226:     close($config);
1.329     matthew  12227: }
                   12228: 
1.1073    raeburn  12229: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12230: 
                   12231: &load_loncaparevs();
1.1073    raeburn  12232: 
1.1074    raeburn  12233: # ---------------------------------------------------------- Read serverhostID table
                   12234: 
1.1227    raeburn  12235: &load_serverhomeIDs();
                   12236: 
                   12237: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12238: {
                   12239:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12240:     if (-e $file) {
                   12241:         my $parser = HTML::LCParser->new($file);
                   12242:         while (my $token = $parser->get_token()) {
                   12243:             if ($token->[0] eq 'S') {
                   12244:                 my $item = $token->[1];
                   12245:                 my $name = $token->[2]{'name'};
                   12246:                 my $value = $token->[2]{'value'};
                   12247:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12248:                     my $release = $parser->get_text();
                   12249:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12250:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12251:                 }
                   12252:             }
                   12253:         }
                   12254:     }
1.1073    raeburn  12255: }
                   12256: 
1.1138    raeburn  12257: # ---------------------------------------------------------- Read managers table
                   12258: {
                   12259:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12260:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12261:             while (my $configline=<$config>) {
                   12262:                 chomp($configline);
                   12263:                 next if ($configline =~ /^\#/);
                   12264:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12265:                     $managerstab{$configline} = 1;
                   12266:                 }
                   12267:             }
                   12268:             close($config);
                   12269:         }
                   12270:     }
                   12271: }
                   12272: 
1.329     matthew  12273: # ------------- set up temporary directory
                   12274: {
1.1117    foxr     12275:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12276: 
1.11      www      12277: }
                   12278: 
1.794     albertel 12279: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12280: 				'compress_threshold'=> 20_000,
                   12281:  			        });
1.185     www      12282: 
1.281     www      12283: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12284: $dumpcount=0;
1.958     www      12285: $locknum=0;
1.22      www      12286: 
1.163     harris41 12287: &logtouch();
1.672     albertel 12288: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12289: $readit=1;
1.564     albertel 12290:     {
                   12291: 	use integer;
                   12292: 	my $test=(2**32)+1;
1.568     albertel 12293: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12294: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12295:     }
1.1214    raeburn  12296: 
                   12297:     {
                   12298:         eval {
                   12299:             ($apache) =
                   12300:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12301:         };
                   12302:         if ($@) {
                   12303:            $apache = 1.3;
1.1213    raeburn  12304:         }
                   12305:     }
1.1214    raeburn  12306: 
1.195     www      12307: }
1.1       albertel 12308: }
1.179     www      12309: 
1.1       albertel 12310: 1;
1.191     harris41 12311: __END__
                   12312: 
1.243     albertel 12313: =pod
                   12314: 
1.191     harris41 12315: =head1 NAME
                   12316: 
1.243     albertel 12317: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12318: 
                   12319: =head1 SYNOPSIS
                   12320: 
1.243     albertel 12321: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12322: 
                   12323:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12324: 
1.243     albertel 12325: Common parameters:
                   12326: 
                   12327: =over 4
                   12328: 
                   12329: =item *
                   12330: 
                   12331: $uname : an internal username (if $cname expecting a course Id specifically)
                   12332: 
                   12333: =item *
                   12334: 
                   12335: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12336: 
                   12337: =item *
                   12338: 
                   12339: $symb : a resource instance identifier
                   12340: 
                   12341: =item *
                   12342: 
                   12343: $namespace : the name of a .db file that contains the data needed or
                   12344: being set.
                   12345: 
                   12346: =back
                   12347: 
1.394     bowersj2 12348: =head1 OVERVIEW
1.191     harris41 12349: 
1.394     bowersj2 12350: lonnet provides subroutines which interact with the
                   12351: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12352: about classes, users, and resources.
1.243     albertel 12353: 
                   12354: For many of these objects you can also use this to store data about
                   12355: them or modify them in various ways.
1.191     harris41 12356: 
1.394     bowersj2 12357: =head2 Symbs
1.191     harris41 12358: 
1.394     bowersj2 12359: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12360: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12361: map, the resource number of the resource in the map, and the URL of
                   12362: the resource itself. The latter is somewhat redundant, but might help
                   12363: if maps change.
                   12364: 
                   12365: An example is
                   12366: 
                   12367:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12368: 
                   12369: The respective map entry is
                   12370: 
                   12371:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12372:   title="Problem 2">
                   12373:  </resource>
                   12374: 
                   12375: Symbs are used by the random number generator, as well as to store and
                   12376: restore data specific to a certain instance of for example a problem.
                   12377: 
                   12378: =head2 Storing And Retrieving Data
                   12379: 
                   12380: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12381: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12382: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12383: is is the non-critical message twin of cstore. These functions are for
                   12384: handlers to store a perl hash to a user's permanent data space in an
                   12385: easy manner, and to retrieve it again on another call. It is expected
                   12386: that a handler would use this once at the beginning to retrieve data,
                   12387: and then again once at the end to send only the new data back.
                   12388: 
                   12389: The data is stored in the user's data directory on the user's
                   12390: homeserver under the ID of the course.
                   12391: 
                   12392: The hash that is returned by restore will have all of the previous
                   12393: value for all of the elements of the hash.
                   12394: 
                   12395: Example:
                   12396: 
                   12397:  #creating a hash
                   12398:  my %hash;
                   12399:  $hash{'foo'}='bar';
                   12400: 
                   12401:  #storing it
                   12402:  &Apache::lonnet::cstore(\%hash);
                   12403: 
                   12404:  #changing a value
                   12405:  $hash{'foo'}='notbar';
                   12406: 
                   12407:  #adding a new value
                   12408:  $hash{'bar'}='foo';
                   12409:  &Apache::lonnet::cstore(\%hash);
                   12410: 
                   12411:  #retrieving the hash
                   12412:  my %history=&Apache::lonnet::restore();
                   12413: 
                   12414:  #print the hash
                   12415:  foreach my $key (sort(keys(%history))) {
                   12416:    print("\%history{$key} = $history{$key}");
                   12417:  }
                   12418: 
                   12419: Will print out:
1.191     harris41 12420: 
1.394     bowersj2 12421:  %history{1:foo} = bar
                   12422:  %history{1:keys} = foo:timestamp
                   12423:  %history{1:timestamp} = 990455579
                   12424:  %history{2:bar} = foo
                   12425:  %history{2:foo} = notbar
                   12426:  %history{2:keys} = foo:bar:timestamp
                   12427:  %history{2:timestamp} = 990455580
                   12428:  %history{bar} = foo
                   12429:  %history{foo} = notbar
                   12430:  %history{timestamp} = 990455580
                   12431:  %history{version} = 2
                   12432: 
                   12433: Note that the special hash entries C<keys>, C<version> and
                   12434: C<timestamp> were added to the hash. C<version> will be equal to the
                   12435: total number of versions of the data that have been stored. The
                   12436: C<timestamp> attribute will be the UNIX time the hash was
                   12437: stored. C<keys> is available in every historical section to list which
                   12438: keys were added or changed at a specific historical revision of a
                   12439: hash.
                   12440: 
                   12441: B<Warning>: do not store the hash that restore returns directly. This
                   12442: will cause a mess since it will restore the historical keys as if the
                   12443: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12444: 
1.394     bowersj2 12445: Calling convention:
1.191     harris41 12446: 
1.1225    raeburn  12447:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12448:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12449: 
1.394     bowersj2 12450: For more detailed information, see lonnet specific documentation.
1.191     harris41 12451: 
1.394     bowersj2 12452: =head1 RETURN MESSAGES
1.191     harris41 12453: 
1.394     bowersj2 12454: =over 4
1.191     harris41 12455: 
1.394     bowersj2 12456: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12457: 
1.394     bowersj2 12458: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12459: when the connection is brought back up
1.191     harris41 12460: 
1.394     bowersj2 12461: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12462: for later delivery
1.191     harris41 12463: 
1.967     bisitz   12464: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12465: 
1.394     bowersj2 12466: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12467: that was requested
1.191     harris41 12468: 
1.243     albertel 12469: =back
1.191     harris41 12470: 
1.243     albertel 12471: =head1 PUBLIC SUBROUTINES
1.191     harris41 12472: 
1.243     albertel 12473: =head2 Session Environment Functions
1.191     harris41 12474: 
1.243     albertel 12475: =over 4
1.191     harris41 12476: 
1.394     bowersj2 12477: =item * 
                   12478: X<appenv()>
1.949     raeburn  12479: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12480: the user envirnoment file, and will be restored for each access this
1.620     albertel 12481: user makes during this session, also modifies the %env for the current
1.949     raeburn  12482: process. Optional rolesarrayref - if defined contains a reference to an array
                   12483: of roles which are exempt from the restriction on modifying user.role entries 
                   12484: in the user's environment.db and in %env.    
1.191     harris41 12485: 
                   12486: =item *
1.394     bowersj2 12487: X<delenv()>
1.987     raeburn  12488: B<delenv($delthis,$regexp)>: removes all items from the session
                   12489: environment file that begin with $delthis. If the 
                   12490: optional second arg - $regexp - is true, $delthis is treated as a 
                   12491: regular expression, otherwise \Q$delthis\E is used. 
                   12492: The values are also deleted from the current processes %env.
1.191     harris41 12493: 
1.795     albertel 12494: =item * get_env_multiple($name) 
                   12495: 
                   12496: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12497: values may be defined and end up as an array ref.
                   12498: 
                   12499: returns an array of values
                   12500: 
1.243     albertel 12501: =back
                   12502: 
                   12503: =head2 User Information
1.191     harris41 12504: 
1.243     albertel 12505: =over 4
1.191     harris41 12506: 
                   12507: =item *
1.394     bowersj2 12508: X<queryauthenticate()>
                   12509: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12510: authentication scheme
                   12511: 
                   12512: =item *
1.394     bowersj2 12513: X<authenticate()>
1.1073    raeburn  12514: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12515: authenticate user from domain's lib servers (first use the current
                   12516: one). C<$upass> should be the users password.
1.1073    raeburn  12517: $checkdefauth is optional (value is 1 if a check should be made to
                   12518:    authenticate user using default authentication method, and allow
                   12519:    account creation if username does not have account in the domain).
                   12520: $clientcancheckhost is optional (value is 1 if checking whether the
                   12521:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12522: 
                   12523: =item *
1.394     bowersj2 12524: X<homeserver()>
                   12525: B<homeserver($uname,$udom)>: find the server which has
                   12526: the user's directory and files (there must be only one), this caches
                   12527: the answer, and also caches if there is a borken connection.
1.191     harris41 12528: 
                   12529: =item *
1.394     bowersj2 12530: X<idget()>
                   12531: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12532: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12533: username, and only 1 username per ID in a specific domain) (returns
                   12534: hash: id=>name,id=>name)
1.191     harris41 12535: 
                   12536: =item *
1.394     bowersj2 12537: X<idrget()>
                   12538: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12539: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12540: 
                   12541: =item *
1.394     bowersj2 12542: X<idput()>
                   12543: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12544: 
                   12545: =item *
1.394     bowersj2 12546: X<rolesinit()>
1.1169    droeschl 12547: B<rolesinit($udom,$username)>: get user privileges.
                   12548: returns user role, first access and timer interval hashes
1.243     albertel 12549: 
                   12550: =item *
1.1171    droeschl 12551: X<privileged()>
                   12552: B<privileged($username,$domain)>: returns a true if user has a
                   12553: privileged and active role (i.e. su or dc), false otherwise.
                   12554: 
                   12555: =item *
1.551     albertel 12556: X<getsection()>
                   12557: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12558: course $cname, return section name/number or '' for "not in course"
                   12559: and '-1' for "no section"
                   12560: 
                   12561: =item *
1.394     bowersj2 12562: X<userenvironment()>
                   12563: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12564: passed in @what from the requested user's environment, returns a hash
                   12565: 
1.858     raeburn  12566: =item * 
                   12567: X<userlog_query()>
1.859     albertel 12568: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12569: activity.log file. %filters defines filters applied when parsing the
                   12570: log file. These can be start or end timestamps, or the type of action
                   12571: - log to look for Login or Logout events, check for Checkin or
                   12572: Checkout, role for role selection. The response is in the form
                   12573: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12574: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12575: 
1.243     albertel 12576: =back
                   12577: 
                   12578: =head2 User Roles
                   12579: 
                   12580: =over 4
                   12581: 
                   12582: =item *
                   12583: 
1.810     raeburn  12584: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12585:  F: full access
                   12586:  U,I,K: authentication modes (cxx only)
                   12587:  '': forbidden
                   12588:  1: user needs to choose course
                   12589:  2: browse allowed
1.766     albertel 12590:  A: passphrase authentication needed
1.243     albertel 12591: 
                   12592: =item *
                   12593: 
1.1192    raeburn  12594: constructaccess($url,$setpriv) : check for access to construction space URL
                   12595: 
                   12596: See if the owner domain and name in the URL match those in the
                   12597: expected environment.  If so, return three element list
                   12598: ($ownername,$ownerdomain,$ownerhome).
                   12599: 
                   12600: Otherwise return the null string.
                   12601: 
                   12602: If second argument 'setpriv' is true, it assigns the privileges,
                   12603: and returns the same three element list, unless the owner has
                   12604: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12605: in which case the null string is returned.
                   12606: 
                   12607: =item *
                   12608: 
1.243     albertel 12609: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12610: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12611: and course level
                   12612: 
                   12613: =item *
                   12614: 
1.988     raeburn  12615: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12616: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12617: $type is Course (default) or Community.
1.988     raeburn  12618: If $forcedefault evaluates to true, text returned will be default 
                   12619: text for $type. Otherwise, if this is a course, the text returned 
                   12620: will be a custom name for the role (if defined in the course's 
                   12621: environment).  If no custom name is defined the default is returned.
                   12622:    
1.832     raeburn  12623: =item *
                   12624: 
1.1219    raeburn  12625: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12626: All arguments are optional. Returns a hash of a roles, either for
                   12627: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12628: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12629: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12630: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12631: For each key, value is set to colon-separated start and end times for
                   12632: the role.  If no username and domain are specified, will default to
1.934     raeburn  12633: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12634: of role statuses (active, future or previous), roles 
                   12635: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12636: to restrict the list of roles reported. If no array ref is 
                   12637: provided for types, will default to return only active roles.
1.834     albertel 12638: 
1.1195    raeburn  12639: =item *
                   12640: 
                   12641: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12642: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12643: 
                   12644: Additional optional arguments are: $type (if role checking is to be restricted 
                   12645: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12646: available roles) or future (roles available in the future), and
                   12647: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  12648: have active Domain Coordinator role in course's domain or in additional
                   12649: domains (specified in 'Domains to check for privileged users' in course
                   12650: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12651: 
                   12652: =item *
                   12653: 
                   12654: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12655: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12656: $possdomains and $possroles are optional array refs -- to domains to check and
                   12657: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12658: users' roles.db to check for a dc or su role in any domain. This can be
                   12659: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12660: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12661: this then allows &privileged_by_domain() to be used, which caches the identity
                   12662: of privileged users, eliminating the need for repeated calls to &dump().
                   12663: 
                   12664: =item *
                   12665: 
                   12666: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12667: where the outer hash keys are domains specified in the $possdomains array ref,
                   12668: next inner hash keys are privileged roles specified in the $roles array ref,
                   12669: and the innermost hash contains key = value pairs for username:domain = end:start
                   12670: for active or future "privileged" users with that role in that domain. To avoid
                   12671: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12672: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  12673: 
1.243     albertel 12674: =back
                   12675: 
                   12676: =head2 User Modification
                   12677: 
                   12678: =over 4
                   12679: 
                   12680: =item *
                   12681: 
1.957     raeburn  12682: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12683: user for the level given by URL.  Optional start and end dates (leave empty
                   12684: string or zero for "no date")
1.191     harris41 12685: 
                   12686: =item *
                   12687: 
1.243     albertel 12688: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12689: change a users, password, possible return values are: ok,
                   12690: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12691: refused
1.191     harris41 12692: 
                   12693: =item *
                   12694: 
1.243     albertel 12695: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12696: 
                   12697: =item *
                   12698: 
1.1058    raeburn  12699: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12700:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12701: 
                   12702: will update user information (firstname,middlename,lastname,generation,
                   12703: permanentemail), and if forceid is true, student/employee ID also.
                   12704: A user's institutional affiliation(s) can also be updated.
                   12705: User information fields will not be overwritten with empty entries 
                   12706: unless the field is included in the $candelete array reference.
                   12707: This array is included when a single user is modified via "Manage Users",
                   12708: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12709: 
                   12710: =item *
                   12711: 
1.286     matthew  12712: modifystudent
                   12713: 
1.957     raeburn  12714: modify a student's enrollment and identification information.
1.1235    raeburn  12715: The course id is resolved based on the current user's environment.  
                   12716: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12717: associated with a course.
                   12718: 
1.297     matthew  12719: This call is essentially a wrapper for lonnet::modifyuser and
                   12720: lonnet::modify_student_enrollment
1.286     matthew  12721: 
                   12722: Inputs: 
                   12723: 
                   12724: =over 4
                   12725: 
1.957     raeburn  12726: =item B<$udom> Student's loncapa domain
1.286     matthew  12727: 
1.957     raeburn  12728: =item B<$uname> Student's loncapa login name
1.286     matthew  12729: 
1.964     bisitz   12730: =item B<$uid> Student/Employee ID
1.286     matthew  12731: 
1.957     raeburn  12732: =item B<$umode> Student's authentication mode
1.286     matthew  12733: 
1.957     raeburn  12734: =item B<$upass> Student's password
1.286     matthew  12735: 
1.957     raeburn  12736: =item B<$first> Student's first name
1.286     matthew  12737: 
1.957     raeburn  12738: =item B<$middle> Student's middle name
1.286     matthew  12739: 
1.957     raeburn  12740: =item B<$last> Student's last name
1.286     matthew  12741: 
1.957     raeburn  12742: =item B<$gene> Student's generation
1.286     matthew  12743: 
1.957     raeburn  12744: =item B<$usec> Student's section in course
1.286     matthew  12745: 
                   12746: =item B<$end> Unix time of the roles expiration
                   12747: 
                   12748: =item B<$start> Unix time of the roles start date
                   12749: 
                   12750: =item B<$forceid> If defined, allow $uid to be changed
                   12751: 
                   12752: =item B<$desiredhome> server to use as home server for student
                   12753: 
1.957     raeburn  12754: =item B<$email> Student's permanent e-mail address
                   12755: 
                   12756: =item B<$type> Type of enrollment (auto or manual)
                   12757: 
1.963     raeburn  12758: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12759: 
                   12760: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12761: 
1.963     raeburn  12762: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12763: 
1.963     raeburn  12764: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12765: 
1.1216    raeburn  12766: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12767: 
                   12768: =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  12769: 
1.286     matthew  12770: =back
1.297     matthew  12771: 
                   12772: =item *
                   12773: 
                   12774: modify_student_enrollment
                   12775: 
1.1235    raeburn  12776: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12777: 'role.request.course' must be defined for this function to proceed.
                   12778: 
                   12779: Inputs:
                   12780: 
                   12781: =over 4
                   12782: 
1.1235    raeburn  12783: =item $udom, student's domain
1.297     matthew  12784: 
1.1235    raeburn  12785: =item $uname, student's name
1.297     matthew  12786: 
1.1235    raeburn  12787: =item $uid, student's user id
1.297     matthew  12788: 
1.1235    raeburn  12789: =item $first, student's first name
1.297     matthew  12790: 
                   12791: =item $middle
                   12792: 
                   12793: =item $last
                   12794: 
                   12795: =item $gene
                   12796: 
                   12797: =item $usec
                   12798: 
                   12799: =item $end
                   12800: 
                   12801: =item $start
                   12802: 
1.957     raeburn  12803: =item $type
                   12804: 
                   12805: =item $locktype
                   12806: 
                   12807: =item $cid
                   12808: 
                   12809: =item $selfenroll
                   12810: 
                   12811: =item $context
                   12812: 
1.1216    raeburn  12813: =item $credits, number of credits student will earn from this class
                   12814: 
1.297     matthew  12815: =back
                   12816: 
1.191     harris41 12817: 
                   12818: =item *
                   12819: 
1.243     albertel 12820: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12821: custom role; give a custom role to a user for the level given by URL.  Specify
                   12822: name and domain of role author, and role name
1.191     harris41 12823: 
                   12824: =item *
                   12825: 
1.243     albertel 12826: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12827: 
                   12828: =item *
                   12829: 
1.243     albertel 12830: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12831: 
                   12832: =back
                   12833: 
                   12834: =head2 Course Infomation
                   12835: 
                   12836: =over 4
1.191     harris41 12837: 
                   12838: =item *
                   12839: 
1.1118    foxr     12840: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12841: specified course id, including all environment settings for the
                   12842: course, the description of the course will be in the hash under the
                   12843: key 'description'
1.191     harris41 12844: 
1.1118    foxr     12845: $options is an optional parameter that if supplied is a hash reference that controls
                   12846: what how this function works.  It has the following key/values:
                   12847: 
                   12848: =over 4
                   12849: 
                   12850: =item freshen_cache
                   12851: 
                   12852: If defined, and the environment cache for the course is valid, it is 
                   12853: returned in the returned hash.
                   12854: 
                   12855: =item one_time
                   12856: 
                   12857: If defined, the last cache time is set to _now_
                   12858: 
                   12859: =item user
                   12860: 
                   12861: If defined, the supplied username is used instead of the current user.
                   12862: 
                   12863: 
                   12864: =back
                   12865: 
1.191     harris41 12866: =item *
                   12867: 
1.624     albertel 12868: resdata($name,$domain,$type,@which) : request for current parameter
                   12869: setting for a specific $type, where $type is either 'course' or 'user',
                   12870: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  12871: answers for 10 minutes.
1.243     albertel 12872: 
1.877     foxr     12873: =item *
                   12874: 
                   12875: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12876: data base, returning a hash that is keyed by the resource name and has
                   12877: values that are the resource value.  I believe that the timestamps and
                   12878: versions are also returned.
                   12879: 
1.1236    raeburn  12880: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   12881: supplemental content area. This routine caches the number of files for 
                   12882: 10 minutes.
                   12883: 
1.243     albertel 12884: =back
                   12885: 
                   12886: =head2 Course Modification
                   12887: 
                   12888: =over 4
1.191     harris41 12889: 
                   12890: =item *
                   12891: 
1.243     albertel 12892: writecoursepref($courseid,%prefs) : write preferences (environment
                   12893: database) for a course
1.191     harris41 12894: 
                   12895: =item *
                   12896: 
1.1011    raeburn  12897: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12898: 
                   12899: =item *
                   12900: 
1.1038    raeburn  12901: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12902: 
1.1167    droeschl 12903: =item *
                   12904: 
                   12905: is_course($courseid), is_course($cdom, $cnum)
                   12906: 
                   12907: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12908: two component version $cdom, $cnum. It checks if the specified course exists.
                   12909: 
                   12910: Returns:
                   12911:     undef if the course doesn't exist, otherwise
                   12912:     in scalar context the combined courseid.
                   12913:     in list context the two components of the course identifier, domain and 
                   12914:     courseid.    
                   12915: 
1.243     albertel 12916: =back
                   12917: 
                   12918: =head2 Resource Subroutines
                   12919: 
                   12920: =over 4
1.191     harris41 12921: 
                   12922: =item *
                   12923: 
1.243     albertel 12924: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12925: 
                   12926: =item *
                   12927: 
1.243     albertel 12928: repcopy($filename) : subscribes to the requested file, and attempts to
                   12929: replicate from the owning library server, Might return
1.607     raeburn  12930: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12931: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12932: resource. Expects the local filesystem pathname
                   12933: (/home/httpd/html/res/....)
                   12934: 
                   12935: =back
                   12936: 
                   12937: =head2 Resource Information
                   12938: 
                   12939: =over 4
1.191     harris41 12940: 
                   12941: =item *
                   12942: 
1.1228    raeburn  12943: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   12944: and returns the value of a variety of different possible values,
                   12945: $varname should be a request string, and the other parameters can be
                   12946: used to specify who and what one is asking about. Ordinarily, $cid 
                   12947: does not need to be specified, as it is retrived from 
                   12948: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   12949: within lonuserstate::loadmap() when initializing a course, before
                   12950: $env{'request.course.id'} has been set, so it needs to be provided
                   12951: in that one case.
1.243     albertel 12952: 
                   12953: Possible values for $varname are environment.lastname (or other item
                   12954: from the envirnment hash), user.name (or someother aspect about the
                   12955: user), resource.0.maxtries (or some other part and parameter of a
                   12956: resource)
1.204     albertel 12957: 
                   12958: =item *
                   12959: 
1.243     albertel 12960: directcondval($number) : get current value of a condition; reads from a state
                   12961: string
1.204     albertel 12962: 
                   12963: =item *
                   12964: 
1.243     albertel 12965: condval($condidx) : value of condition index based on state
1.204     albertel 12966: 
                   12967: =item *
                   12968: 
1.243     albertel 12969: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12970: resource's metadata, $what should be either a specific key, or either
                   12971: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12972: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12973: 
                   12974: this function automatically caches all requests
1.191     harris41 12975: 
                   12976: =item *
                   12977: 
1.243     albertel 12978: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12979: network of library servers; returns file handle of where SQL and regex results
                   12980: will be stored for query
1.191     harris41 12981: 
                   12982: =item *
                   12983: 
1.243     albertel 12984: symbread($filename) : return symbolic list entry (filename argument optional);
                   12985: returns the data handle
1.191     harris41 12986: 
                   12987: =item *
                   12988: 
1.1190    raeburn  12989: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12990: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12991: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12992: on failure, user must be in a course, as it assumes the existence of
                   12993: the course initial hash, and uses $env('request.course.id'}.  The third
                   12994: arg is an optional reference to a scalar.  If this arg is passed in the 
                   12995: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12996: encrypted; otherwise it will be null.  
1.191     harris41 12997: 
                   12998: =item *
                   12999: 
1.243     albertel 13000: symbclean($symb) : removes versions numbers from a symb, returns the
                   13001: cleaned symb
1.191     harris41 13002: 
                   13003: =item *
                   13004: 
1.243     albertel 13005: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13006: course map, user must be in a course for it to work.
1.191     harris41 13007: 
                   13008: =item *
                   13009: 
1.243     albertel 13010: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13011: 
                   13012: =item *
                   13013: 
1.243     albertel 13014: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13015: a random seed, all arguments are optional, if they aren't sent it uses the
                   13016: environment to derive them. Note: if symb isn't sent and it can't get one
                   13017: from &symbread it will use the current time as its return value
1.191     harris41 13018: 
                   13019: =item *
                   13020: 
1.243     albertel 13021: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13022: unfakeable, receipt
1.191     harris41 13023: 
                   13024: =item *
                   13025: 
1.620     albertel 13026: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13027: 
                   13028: =item *
                   13029: 
1.243     albertel 13030: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13031: 
                   13032: =item *
                   13033: 
1.243     albertel 13034: 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 13035: 
                   13036: =item *
                   13037: 
1.243     albertel 13038: 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 13039: 
                   13040: =item *
                   13041: 
1.243     albertel 13042: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13043: 
                   13044: =item *
                   13045: 
1.243     albertel 13046: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13047: forcing spreadsheet to reevaluate the resource scores next time.
                   13048: 
1.1195    raeburn  13049: =item * 
                   13050: 
1.1196    raeburn  13051: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13052: when viewing in course context.
1.1195    raeburn  13053: 
1.1196    raeburn  13054:  input: six args -- filename (decluttered), course number, course domain,
                   13055:                     url, symb (if registered) and group (if this is a 
                   13056:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13057: 
1.1196    raeburn  13058:  output: array of five scalars --
1.1195    raeburn  13059:          $cfile -- url for file editing if editable on current server
                   13060:          $home -- homeserver of resource (i.e., for author if published,
                   13061:                                           or course if uploaded.).
                   13062:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13063:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13064:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13065: 
                   13066: =item *
                   13067: 
                   13068: is_course_upload($file,$cnum,$cdom)
                   13069: 
                   13070: Used in course context to determine if current file was uploaded to 
                   13071: the course (i.e., would be found in /userfiles/docs on the course's 
                   13072: homeserver.
                   13073: 
                   13074:   input: 3 args -- filename (decluttered), course number and course domain.
                   13075:   output: boolean -- 1 if file was uploaded.
                   13076: 
1.243     albertel 13077: =back
                   13078: 
                   13079: =head2 Storing/Retreiving Data
                   13080: 
                   13081: =over 4
1.191     harris41 13082: 
                   13083: =item *
                   13084: 
1.243     albertel 13085: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13086: for this url; hashref needs to be given and should be a \%hashname; the
                   13087: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13088: be derived from the env
1.191     harris41 13089: 
                   13090: =item *
                   13091: 
1.243     albertel 13092: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13093: uses critical subroutine
1.191     harris41 13094: 
                   13095: =item *
                   13096: 
1.243     albertel 13097: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13098: all args are optional
1.191     harris41 13099: 
                   13100: =item *
                   13101: 
1.717     albertel 13102: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13103: dumps the complete (or key matching regexp) namespace into a hash
                   13104: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13105: normally &store()ed into
                   13106: 
                   13107: $range should be either an integer '100' (give me the first 100
                   13108:                                            matching records)
                   13109:               or be  two integers sperated by a - with no spaces
                   13110:                  '30-50' (give me the 30th through the 50th matching
                   13111:                           records)
                   13112: 
                   13113: 
                   13114: =item *
                   13115: 
                   13116: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13117: replaces a &store() version of data with a replacement set of data
                   13118: for a particular resource in a namespace passed in the $storehash hash 
                   13119: reference
                   13120: 
                   13121: =item *
                   13122: 
1.243     albertel 13123: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13124: works very similar to store/cstore, but all data is stored in a
                   13125: temporary location and can be reset using tmpreset, $storehash should
                   13126: be a hash reference, returns nothing on success
1.191     harris41 13127: 
                   13128: =item *
                   13129: 
1.243     albertel 13130: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13131: similar to restore, but all data is stored in a temporary location and
                   13132: can be reset using tmpreset. Returns a hash of values on success,
                   13133: error string otherwise.
1.191     harris41 13134: 
                   13135: =item *
                   13136: 
1.243     albertel 13137: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13138: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13139: 
                   13140: =item *
                   13141: 
1.243     albertel 13142: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13143: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13144: 
                   13145: =item *
                   13146: 
1.243     albertel 13147: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13148: namesp ($udom and $uname are optional)
1.191     harris41 13149: 
                   13150: =item *
                   13151: 
1.702     albertel 13152: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13153: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13154: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13155: 
1.702     albertel 13156: $range should be either an integer '100' (give me the first 100
                   13157:                                            matching records)
                   13158:               or be  two integers sperated by a - with no spaces
                   13159:                  '30-50' (give me the 30th through the 50th matching
                   13160:                           records)
1.449     matthew  13161: =item *
                   13162: 
                   13163: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13164: $store can be a scalar, an array reference, or if the amount to be 
                   13165: incremented is > 1, a hash reference.
                   13166: 
                   13167: ($udom and $uname are optional)
1.191     harris41 13168: 
                   13169: =item *
                   13170: 
1.243     albertel 13171: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13172: ($udom and $uname are optional)
1.191     harris41 13173: 
                   13174: =item *
                   13175: 
1.243     albertel 13176: cput($namespace,$storehash,$udom,$uname) : critical put
                   13177: ($udom and $uname are optional)
1.191     harris41 13178: 
                   13179: =item *
                   13180: 
1.748     albertel 13181: newput($namespace,$storehash,$udom,$uname) :
                   13182: 
                   13183: Attempts to store the items in the $storehash, but only if they don't
                   13184: currently exist, if this succeeds you can be certain that you have 
                   13185: successfully created a new key value pair in the $namespace db.
                   13186: 
                   13187: 
                   13188: Args:
                   13189:  $namespace: name of database to store values to
                   13190:  $storehash: hashref to store to the db
                   13191:  $udom: (optional) domain of user containing the db
                   13192:  $uname: (optional) name of user caontaining the db
                   13193: 
                   13194: Returns:
                   13195:  'ok' -> succeeded in storing all keys of $storehash
                   13196:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13197:                         least <key> already existed in the db (other
                   13198:                         requested keys may also already exist)
1.967     bisitz   13199:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13200:  'con_lost' -> unable to contact request server
                   13201:  'refused' -> action was not allowed by remote machine
                   13202: 
                   13203: 
                   13204: =item *
                   13205: 
1.243     albertel 13206: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13207: reference filled in from namesp (encrypts the return communication)
                   13208: ($udom and $uname are optional)
1.191     harris41 13209: 
                   13210: =item *
                   13211: 
1.243     albertel 13212: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13213: critical subroutine
                   13214: 
1.806     raeburn  13215: =item *
                   13216: 
1.860     raeburn  13217: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13218: array reference filled in from namespace found in domain level on either
                   13219: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13220: 
                   13221: =item *
                   13222: 
1.860     raeburn  13223: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13224: domain level either on specified domain server ($uhome) or primary domain 
                   13225: server ($udom and $uhome are optional)
1.806     raeburn  13226: 
1.943     raeburn  13227: =item * 
                   13228: 
1.1240    raeburn  13229: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13230: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13231: the target domain.
                   13232: 
                   13233: May also include additional key => value pairs for the following groups:
                   13234: 
                   13235: =over
                   13236: 
                   13237: =item
                   13238: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13239: 
                   13240: =over
                   13241: 
                   13242: =item defaultquota, authorquota
                   13243: 
                   13244: =back
                   13245: 
                   13246: =item
                   13247: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13248: portfolio for users).
                   13249: 
                   13250: =over
                   13251: 
                   13252: =item
                   13253: aboutme, blog, webdav, portfolio
                   13254: 
                   13255: =back
                   13256: 
                   13257: =item
                   13258: requestcourses: ability to request courses, and how requests are processed.
                   13259: 
                   13260: =over
                   13261: 
                   13262: =item
                   13263: official, unofficial, community
                   13264: 
                   13265: =back
                   13266: 
                   13267: =item
                   13268: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13269: 
                   13270: =over
                   13271: 
                   13272: =item
                   13273: inststatustypes, inststatusorder
                   13274: 
                   13275: =back
                   13276: 
                   13277: =item
                   13278: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13279: for course's uploaded content.
                   13280: 
                   13281: =over
                   13282: 
                   13283: =item
                   13284: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
                   13285: 
                   13286: =back
                   13287: 
                   13288: =item
                   13289: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13290: on your servers.
                   13291: 
                   13292: =over
                   13293: 
                   13294: =item 
                   13295: remotesessions, hostedsessions
                   13296: 
                   13297: =back
                   13298: 
                   13299: =back
                   13300: 
                   13301: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13302: utility to create a configuration.db file on a domain's primary library server 
                   13303: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13304: -- corresponding values are authentication type (internal, krb4, krb5,
                   13305: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13306: will be available. Values are retrieved from cache (if current), unless the
                   13307: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13308: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13309: 
                   13310: Typical usage:
1.943     raeburn  13311: 
1.1240    raeburn  13312: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13313: 
1.243     albertel 13314: =back
                   13315: 
                   13316: =head2 Network Status Functions
                   13317: 
                   13318: =over 4
1.191     harris41 13319: 
                   13320: =item *
                   13321: 
1.1137    raeburn  13322: dirlist() : return directory list based on URI (first arg).
                   13323: 
                   13324: Inputs: 1 required, 5 optional.
                   13325: 
                   13326: =over
                   13327: 
                   13328: =item 
                   13329: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13330: 
                   13331: =item
                   13332: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13333: 
                   13334: =item
                   13335: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13336: 
                   13337: =item
                   13338: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13339: 
                   13340: =item
                   13341: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13342: 
                   13343: =item 
                   13344: $alternateRoot - path to prepend in place of path from $uri.
                   13345: 
                   13346: =back
                   13347: 
                   13348: Returns: Array of up to two items.
                   13349: 
                   13350: =over
                   13351: 
                   13352: a reference to an array of files/subdirectories
                   13353: 
                   13354: =over
                   13355: 
                   13356: Each element in the array of files/subdirectories is a & separated list of
                   13357: item name and the result of running stat on the item.  If dirlist was requested
                   13358: for a file instead of a directory, the item name will be ''. For a directory 
                   13359: listing, if the item is a metadata file, the element will end &N&M 
                   13360: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13361: default copyright set (1).  
                   13362: 
                   13363: =back
                   13364: 
                   13365: a scalar containing error condition (if encountered).
                   13366: 
                   13367: =over
                   13368: 
                   13369: =item 
                   13370: no_host (no homeserver identified for $username:$domain).
                   13371: 
                   13372: =item 
                   13373: no_such_host (server contacted for listing not identified as valid host).
                   13374: 
                   13375: =item 
                   13376: con_lost (connection to remote server failed).
                   13377: 
                   13378: =item 
                   13379: refused (invalid $username:$domain received on lond side).
                   13380: 
                   13381: =item 
                   13382: no_such_dir (directory at specified path on lond side does not exist). 
                   13383: 
                   13384: =item 
                   13385: empty (directory at specified path on lond side is empty).
                   13386: 
                   13387: =over
                   13388: 
                   13389: This is currently not encountered because the &ls3, &ls2, 
                   13390: &ls (_handler) routines on the lond side do not filter out
                   13391: . and .. from a directory listing. 
                   13392: 
                   13393: =back
                   13394: 
                   13395: =back
                   13396: 
                   13397: =back
1.191     harris41 13398: 
                   13399: =item *
                   13400: 
1.243     albertel 13401: spareserver() : find server with least workload from spare.tab
                   13402: 
1.986     foxr     13403: 
                   13404: =item *
                   13405: 
                   13406: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13407: if there is no corresponding loncapa host.
                   13408: 
1.243     albertel 13409: =back
                   13410: 
1.986     foxr     13411: 
1.243     albertel 13412: =head2 Apache Request
                   13413: 
                   13414: =over 4
1.191     harris41 13415: 
                   13416: =item *
                   13417: 
1.243     albertel 13418: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13419: localhost, posts hash
                   13420: 
                   13421: =back
                   13422: 
                   13423: =head2 Data to String to Data
                   13424: 
                   13425: =over 4
1.191     harris41 13426: 
                   13427: =item *
                   13428: 
1.243     albertel 13429: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13430: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13431: 
                   13432: =item *
                   13433: 
1.243     albertel 13434: hashref2str($hashref) : convert a hashref into a string complete with
                   13435: escaping and '=' and '&' separators, supports elements that are
                   13436: arrayrefs and hashrefs
1.191     harris41 13437: 
                   13438: =item *
                   13439: 
1.243     albertel 13440: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13441: with escaping and '&' separators, supports elements that are arrayrefs
                   13442: and hashrefs
1.191     harris41 13443: 
                   13444: =item *
                   13445: 
1.243     albertel 13446: str2hash($string) : convert string to hash using unescaping and
                   13447: splitting on '=' and '&', supports elements that are arrayrefs and
                   13448: hashrefs
1.191     harris41 13449: 
                   13450: =item *
                   13451: 
1.243     albertel 13452: str2array($string) : convert string to hash using unescaping and
                   13453: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13454: 
                   13455: =back
                   13456: 
                   13457: =head2 Logging Routines
                   13458: 
                   13459: 
                   13460: These routines allow one to make log messages in the lonnet.log and
                   13461: lonnet.perm logfiles.
1.191     harris41 13462: 
1.1119    foxr     13463: =over 4
                   13464: 
1.191     harris41 13465: =item *
                   13466: 
1.243     albertel 13467: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13468: 
                   13469: =item *
                   13470: 
1.243     albertel 13471: logthis() : append message to the normal lonnet.log file, it gets
                   13472: preiodically rolled over and deleted.
1.191     harris41 13473: 
                   13474: =item *
                   13475: 
1.243     albertel 13476: logperm() : append a permanent message to lonnet.perm.log, this log
                   13477: file never gets deleted by any automated portion of the system, only
                   13478: messages of critical importance should go in here.
                   13479: 
1.1119    foxr     13480: 
1.243     albertel 13481: =back
                   13482: 
                   13483: =head2 General File Helper Routines
                   13484: 
                   13485: =over 4
1.191     harris41 13486: 
                   13487: =item *
                   13488: 
1.481     raeburn  13489: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13490: (a) files in /uploaded
                   13491:   (i) If a local copy of the file exists - 
                   13492:       compares modification date of local copy with last-modified date for 
                   13493:       definitive version stored on home server for course. If local copy is 
                   13494:       stale, requests a new version from the home server and stores it. 
                   13495:       If the original has been removed from the home server, then local copy 
                   13496:       is unlinked.
                   13497:   (ii) If local copy does not exist -
                   13498:       requests the file from the home server and stores it. 
                   13499:   
                   13500:   If $caller is 'uploadrep':  
                   13501:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13502:     for request for files originally uploaded via DOCS. 
                   13503:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13504:   
                   13505:   Otherwise:
                   13506:      This indicates a call from the content generation phase of the request.
                   13507:      -  returns the entire contents of the file or -1.
                   13508:      
                   13509: (b) files in /res
                   13510:    - returns the entire contents of a file or -1; 
                   13511:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13512: 
1.712     albertel 13513: 
                   13514: =item *
                   13515: 
                   13516: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13517:                   reference
                   13518: 
                   13519: returns either a stat() list of data about the file or an empty list
                   13520: if the file doesn't exist or couldn't find out about it (connection
                   13521: problems or user unknown)
                   13522: 
1.191     harris41 13523: =item *
                   13524: 
1.243     albertel 13525: filelocation($dir,$file) : returns file system location of a file
                   13526: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13527: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13528: and a file of ../bob will become /a/bob)
1.191     harris41 13529: 
                   13530: =item *
                   13531: 
                   13532: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13533: filelocation except for hrefs
                   13534: 
                   13535: =item *
                   13536: 
                   13537: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13538: 
1.243     albertel 13539: =back
                   13540: 
1.608     albertel 13541: =head2 Usererfile file routines (/uploaded*)
                   13542: 
                   13543: =over 4
                   13544: 
                   13545: =item *
                   13546: 
                   13547: userfileupload(): main rotine for putting a file in a user or course's
                   13548:                   filespace, arguments are,
                   13549: 
1.620     albertel 13550:  formname - required - this is the name of the element in $env where the
1.608     albertel 13551:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13552:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13553:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13554:  context - if coursedoc, store the file in the course of the active role
                   13555:              of the current user; 
                   13556:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13557:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13558:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13559:          if undefined, it will be placed in "unknown"
                   13560: 
                   13561:  (This routine calls clean_filename() to remove any dangerous
                   13562:  characters from the filename, and then calls finuserfileupload() to
                   13563:  complete the transaction)
                   13564: 
                   13565:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13566:  and /adm/notfound.html if unsuccessful
                   13567: 
                   13568: =item *
                   13569: 
                   13570: clean_filename(): routine for cleaing a filename up for storage in
                   13571:                  userfile space, argument is:
                   13572: 
                   13573:  filename - proposed filename
                   13574: 
                   13575: returns: the new clean filename
                   13576: 
                   13577: =item *
                   13578: 
1.1090    raeburn  13579: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13580: userspace, probably shouldn't be called directly
                   13581: 
                   13582:   docuname: username or courseid of destination for the file
                   13583:   docudom: domain of user/course of destination for the file
                   13584:   formname: same as for userfileupload()
1.1090    raeburn  13585:   fname: filename (including subdirectories) for the file
                   13586:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13587:   allfiles: reference to hash used to store objects found by parser
                   13588:   codebase: reference to hash used for codebases of java objects found by parser
                   13589:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13590:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13591:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13592:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13593:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13594:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13595:   mimetype: reference to scalar to accommodate mime type determined
                   13596:             from File::MMagic if $parser = parse.
1.608     albertel 13597: 
                   13598:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13599:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13600:  was 'overwrite').
                   13601:  
1.608     albertel 13602: 
                   13603: =item *
                   13604: 
                   13605: renameuserfile(): renames an existing userfile to a new name
                   13606: 
                   13607:   Args:
                   13608:    docuname: username or courseid of destination for the file
                   13609:    docudom: domain of user/course of destination for the file
                   13610:    old: current file name (including any subdirs under userfiles)
                   13611:    new: desired file name (including any subdirs under userfiles)
                   13612: 
                   13613: =item *
                   13614: 
                   13615: mkdiruserfile(): creates a directory is a userfiles dir
                   13616: 
                   13617:   Args:
                   13618:    docuname: username or courseid of destination for the file
                   13619:    docudom: domain of user/course of destination for the file
                   13620:    dir: dir to create (including any subdirs under userfiles)
                   13621: 
                   13622: =item *
                   13623: 
                   13624: removeuserfile(): removes a file that exists in userfiles
                   13625: 
                   13626:   Args:
                   13627:    docuname: username or courseid of destination for the file
                   13628:    docudom: domain of user/course of destination for the file
                   13629:    fname: filname to delete (including any subdirs under userfiles)
                   13630: 
                   13631: =item *
                   13632: 
                   13633: removeuploadedurl(): convience function for removeuserfile()
                   13634: 
                   13635:   Args:
                   13636:    url:  a full /uploaded/... url to delete
                   13637: 
1.747     albertel 13638: =item * 
                   13639: 
                   13640: get_portfile_permissions():
                   13641:   Args:
                   13642:     domain: domain of user or course contain the portfolio files
                   13643:     user: name of user or num of course contain the portfolio files
                   13644:   Returns:
                   13645:     hashref of a dump of the proper file_permissions.db
                   13646:    
                   13647: 
                   13648: =item * 
                   13649: 
                   13650: get_access_controls():
                   13651: 
                   13652: Args:
                   13653:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13654:   group: (optional) the group you want the files associated with
                   13655:   file: (optional) the file you want access info on
                   13656: 
                   13657: Returns:
1.749     raeburn  13658:     a hash (keys are file names) of hashes containing
                   13659:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13660:         values are XML containing access control settings (see below) 
1.747     albertel 13661: 
                   13662: Internal notes:
                   13663: 
1.749     raeburn  13664:  access controls are stored in file_permissions.db as key=value pairs.
                   13665:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13666:         where scope -> public,guest,course,group,domains or users.
                   13667:               end -> UNIX time for end of access (0 -> no end date)
                   13668:               start -> UNIX time for start of access
                   13669: 
                   13670:     value -> XML description of access control
                   13671:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13672:             <start></start>
                   13673:             <end></end>
                   13674: 
                   13675:             <password></password>  for scope type = guest
                   13676: 
                   13677:             <domain></domain>     for scope type = course or group
                   13678:             <number></number>
                   13679:             <roles id="">
                   13680:              <role></role>
                   13681:              <access></access>
                   13682:              <section></section>
                   13683:              <group></group>
                   13684:             </roles>
                   13685: 
                   13686:             <dom></dom>         for scope type = domains
                   13687: 
                   13688:             <users>             for scope type = users
                   13689:              <user>
                   13690:               <uname></uname>
                   13691:               <udom></udom>
                   13692:              </user>
                   13693:             </users>
                   13694:            </scope> 
                   13695:               
                   13696:  Access data is also aggregated for each file in an additional key=value pair:
                   13697:  key -> path to file/file_name\0accesscontrol 
                   13698:  value -> reference to hash
                   13699:           hash contains key = value pairs
                   13700:           where key = uniqueID:scope_end_start
                   13701:                 value = UNIX time record was last updated
                   13702: 
                   13703:           Used to improve speed of look-ups of access controls for each file.  
                   13704:  
                   13705:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13706: 
1.1198    raeburn  13707: =item *
                   13708: 
1.749     raeburn  13709: modify_access_controls():
                   13710: 
                   13711: Modifies access controls for a portfolio file
                   13712: Args
                   13713: 1. file name
                   13714: 2. reference to hash of required changes,
                   13715: 3. domain
                   13716: 4. username
                   13717:   where domain,username are the domain of the portfolio owner 
                   13718:   (either a user or a course) 
                   13719: 
                   13720: Returns:
                   13721: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13722: 2. result of deletions ('ok' or 'error', with error message).
                   13723: 3. reference to hash of any new or updated access controls.
                   13724: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13725:    key = integer (inbound ID)
1.1198    raeburn  13726:    value = uniqueID
                   13727: 
                   13728: =item *
                   13729: 
                   13730: get_timebased_id():
                   13731: 
                   13732: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13733: course via the Course Editor (e.g., folders, composite pages, 
                   13734: group bulletin boards).
                   13735: 
                   13736: Args: (first three required; six others optional)
                   13737: 
                   13738: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13739:    docssequence, or name of group
                   13740: 
                   13741: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13742:    e.g., num, boardids
                   13743: 
                   13744: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   13745:    file will be named nohist_namespace.db
                   13746: 
                   13747: 4. cdom: domain of course; default is current course domain from %env
                   13748: 
                   13749: 5. cnum: course number; default is current course number from %env
                   13750: 
                   13751: 6. idtype: set to concat if an additional digit is to be appended to the 
                   13752:    unix timestamp to form the suffix, if the plain timestamp is already
                   13753:    in use.  Default is to not do this, but simply increment the unix 
                   13754:    timestamp by 1 until a unique key is obtained.
                   13755: 
                   13756: 7. who: holder of locking key; defaults to user:domain for user.
                   13757: 
                   13758: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   13759:    retrying); default is 3.
                   13760: 
                   13761: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   13762: 
                   13763: Returns:
                   13764: 
                   13765: 1. suffix obtained (numeric)
                   13766: 
                   13767: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13768: 
                   13769: 3. error: contains (localized) error message if an error occurred.
                   13770: 
1.747     albertel 13771: 
1.608     albertel 13772: =back
                   13773: 
1.243     albertel 13774: =head2 HTTP Helper Routines
                   13775: 
                   13776: =over 4
                   13777: 
1.191     harris41 13778: =item *
                   13779: 
                   13780: escape() : unpack non-word characters into CGI-compatible hex codes
                   13781: 
                   13782: =item *
                   13783: 
                   13784: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13785: 
1.243     albertel 13786: =back
                   13787: 
                   13788: =head1 PRIVATE SUBROUTINES
                   13789: 
                   13790: =head2 Underlying communication routines (Shouldn't call)
                   13791: 
                   13792: =over 4
                   13793: 
                   13794: =item *
                   13795: 
                   13796: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13797: 
                   13798: =item *
                   13799: 
                   13800: reply() : uses subreply to send a message to remote machine, logs all failures
                   13801: 
                   13802: =item *
                   13803: 
                   13804: critical() : passes a critical message to another server; if cannot
                   13805: get through then place message in connection buffer directory and
                   13806: returns con_delayed, if incapable of saving message, returns
                   13807: con_failed
                   13808: 
                   13809: =item *
                   13810: 
                   13811: reconlonc() : tries to reconnect lonc client processes.
                   13812: 
                   13813: =back
                   13814: 
                   13815: =head2 Resource Access Logging
                   13816: 
                   13817: =over 4
                   13818: 
                   13819: =item *
                   13820: 
                   13821: flushcourselogs() : flush (save) buffer logs and access logs
                   13822: 
                   13823: =item *
                   13824: 
                   13825: courselog($what) : save message for course in hash
                   13826: 
                   13827: =item *
                   13828: 
                   13829: courseacclog($what) : save message for course using &courselog().  Perform
                   13830: special processing for specific resource types (problems, exams, quizzes, etc).
                   13831: 
1.191     harris41 13832: =item *
                   13833: 
                   13834: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13835: as a PerlChildExitHandler
1.243     albertel 13836: 
                   13837: =back
                   13838: 
                   13839: =head2 Other
                   13840: 
                   13841: =over 4
                   13842: 
                   13843: =item *
                   13844: 
                   13845: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13846: 
                   13847: =back
                   13848: 
                   13849: =cut
1.877     foxr     13850: 

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