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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1279  ! raeburn     4: # $Id: lonnet.pm,v 1.1278 2015/03/30 21:13:24 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.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
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.1245    raeburn   609:     my ($r,$name,$userhashref) = @_;
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.1245    raeburn   640: 
                    641:     if (ref($userhashref) eq 'HASH') {
                    642:         $userhashref->{'name'} = $disk_env{'user.name'};
                    643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   644:     }
1.1245    raeburn   645: 
1.916     albertel  646:     return $handle;
                    647: }
                    648: 
1.830     albertel  649: sub timed_flock {
                    650:     my ($file,$lock_type) = @_;
                    651:     my $failed=0;
                    652:     eval {
                    653: 	local $SIG{__DIE__}='DEFAULT';
                    654: 	local $SIG{ALRM}=sub {
                    655: 	    $failed=1;
                    656: 	    die("failed lock");
                    657: 	};
                    658: 	alarm(13);
                    659: 	flock($file,$lock_type);
                    660: 	alarm(0);
                    661:     };
                    662:     if ($failed) {
                    663: 	return undef;
                    664:     } else {
                    665: 	return 1;
                    666:     }
                    667: }
                    668: 
1.5       www       669: # ---------------------------------------------------------- Append Environment
                    670: 
                    671: sub appenv {
1.949     raeburn   672:     my ($newenv,$roles) = @_;
                    673:     if (ref($newenv) eq 'HASH') {
                    674:         foreach my $key (keys(%{$newenv})) {
                    675:             my $refused = 0;
                    676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    677:                 $refused = 1;
                    678:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    681:                         $refused = 0;
                    682:                     }
                    683:                 }
                    684:             }
                    685:             if ($refused) {
                    686:                 &logthis("<font color=\"blue\">WARNING: ".
                    687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    688:                          .'</font>');
                    689: 	        delete($newenv->{$key});
                    690:             } else {
                    691:                 $env{$key}=$newenv->{$key};
                    692:             }
                    693:         }
                    694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    695:         if ($opened
                    696: 	    && &timed_flock($env_file,LOCK_EX)
                    697: 	    &&
                    698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    700: 	    while (my ($key,$value) = each(%{$newenv})) {
                    701: 	        $disk_env{$key} = $value;
                    702: 	    }
                    703: 	    untie(%disk_env);
1.35      www       704:         }
1.191     harris41  705:     }
1.56      www       706:     return 'ok';
                    707: }
                    708: # ----------------------------------------------------- Delete from Environment
                    709: 
                    710: sub delenv {
1.1104    raeburn   711:     my ($delthis,$regexp,$roles) = @_;
                    712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    713:         my $refused = 1;
                    714:         if (ref($roles) eq 'ARRAY') {
                    715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    716:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    717:                 $refused = 0;
                    718:             }
                    719:         }
                    720:         if ($refused) {
                    721:             &logthis("<font color=\"blue\">WARNING: ".
                    722:                      "Attempt to delete from environment ".$delthis);
                    723:             return 'error';
                    724:         }
1.56      www       725:     }
1.917     albertel  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    727:     if ($opened
1.915     albertel  728: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  729: 	&&
                    730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  732: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   733: 	    if ($regexp) {
                    734:                 if ($key=~/^$delthis/) {
                    735:                     delete($env{$key});
                    736:                     delete($disk_env{$key});
                    737:                 } 
                    738:             } else {
                    739:                 if ($key=~/^\Q$delthis\E/) {
                    740: 		    delete($env{$key});
                    741: 		    delete($disk_env{$key});
                    742: 	        }
                    743:             }
1.448     albertel  744: 	}
1.783     albertel  745: 	untie(%disk_env);
1.5       www       746:     }
                    747:     return 'ok';
1.369     albertel  748: }
                    749: 
1.790     albertel  750: sub get_env_multiple {
                    751:     my ($name) = @_;
                    752:     my @values;
                    753:     if (defined($env{$name})) {
                    754:         # exists is it an array
                    755:         if (ref($env{$name})) {
                    756:             @values=@{ $env{$name} };
                    757:         } else {
                    758:             $values[0]=$env{$name};
                    759:         }
                    760:     }
                    761:     return(@values);
                    762: }
                    763: 
1.958     www       764: # ------------------------------------------------------------------- Locking
                    765: 
                    766: sub set_lock {
                    767:     my ($text)=@_;
                    768:     $locknum++;
                    769:     my $id=$$.'-'.$locknum;
                    770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    771:              'session.lock.'.$id => $text});
                    772:     return $id;
                    773: }
                    774: 
                    775: sub get_locks {
                    776:     my $num=0;
                    777:     my %texts=();
                    778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    779:        if ($lock=~/\w/) {
                    780:           $num++;
                    781:           $texts{$lock}=$env{'session.lock.'.$lock};
                    782:        }
                    783:    }
                    784:    return ($num,%texts);
                    785: }
                    786: 
                    787: sub remove_lock {
                    788:     my ($id)=@_;
                    789:     my $newlocks='';
                    790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    791:        if (($lock=~/\w/) && ($lock ne $id)) {
                    792:           $newlocks.=','.$lock;
                    793:        }
                    794:     }
                    795:     &appenv({'session.locks' => $newlocks});
                    796:     &delenv('session.lock.'.$id);
                    797: }
                    798: 
                    799: sub remove_all_locks {
                    800:     my $activelocks=$env{'session.locks'};
                    801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    802:        if ($lock=~/\w/) {
                    803:           &remove_lock($lock);
                    804:        }
                    805:     }
                    806: }
                    807: 
                    808: 
1.369     albertel  809: # ------------------------------------------ Find out current server userload
                    810: sub userload {
                    811:     my $numusers=0;
                    812:     {
                    813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    814: 	my $filename;
                    815: 	my $curtime=time;
                    816: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  817: 	    next if ($filename eq '.' || $filename eq '..');
                    818: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  821: 	}
                    822: 	closedir(LONIDS);
                    823:     }
                    824:     my $userloadpercent=0;
                    825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    826:     if ($maxuserload) {
1.371     albertel  827: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  828:     }
1.372     albertel  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  830:     return $userloadpercent;
1.283     www       831: }
                    832: 
1.1       albertel  833: # ------------------------------ Find server with least workload from spare.tab
1.11      www       834: 
1.1       albertel  835: sub spareserver {
1.1083    raeburn   836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  837:     my $spare_server;
1.370     albertel  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    840:                                                      :  $userloadpercent;
1.1083    raeburn   841:     my ($uint_dom,$remotesessions);
                    842:     if (($udom ne '') && (&domain($udom) ne '')) {
                    843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    846:         $remotesessions = $udomdefaults{'remotesessions'};
                    847:     }
1.1123    raeburn   848:     my $spareshash = &this_host_spares($udom);
                    849:     if (ref($spareshash) eq 'HASH') {
                    850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279  ! raeburn   852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
        !           853:                                              $try_server));
1.1123    raeburn   854: 	        ($spare_server, $lowest_load) =
                    855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:             }
1.1083    raeburn   857:         }
1.784     albertel  858: 
1.1123    raeburn   859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    860: 
                    861:         if (!$found_server) {
                    862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279  ! raeburn   864:                     next unless (&spare_can_host($udom,$uint_dom,
        !           865:                                                  $remotesessions,$try_server));
1.1123    raeburn   866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
1.1253    raeburn   889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    890: 
                    891:     if ($required) {
                    892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    895:         if (($major eq '' && $minor eq '') ||
                    896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    897:             return ($spare_server,$lowest_load);
                    898:         }
                    899:     }
1.784     albertel  900: 
                    901:     my $loadans     = &reply('load',    $try_server);
                    902:     my $userloadans = &reply('userload',$try_server);
                    903: 
                    904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  906:     }
                    907: 
                    908:     my $load;
                    909:     if ($loadans =~ /\d/) {
                    910: 	if ($userloadans =~ /\d/) {
                    911: 	    #both are numbers, pick the bigger one
                    912: 	    $load = ($loadans > $userloadans) ? $loadans 
                    913: 		                              : $userloadans;
1.411     albertel  914: 	} else {
1.784     albertel  915: 	    $load = $loadans;
1.411     albertel  916: 	}
1.784     albertel  917:     } else {
                    918: 	$load = $userloadans;
                    919:     }
                    920: 
                    921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    922: 	$spare_server = $try_server;
                    923: 	$lowest_load  = $load;
1.370     albertel  924:     }
1.784     albertel  925:     return ($spare_server,$lowest_load);
1.202     matthew   926: }
1.914     albertel  927: 
                    928: # --------------------------- ask offload servers if user already has a session
                    929: sub find_existing_session {
                    930:     my ($udom,$uname) = @_;
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
                    938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    941:             }
                    942:         }
1.914     albertel  943:     }
                    944:     return;
                    945: }
                    946: 
                    947: # -------------------------------- ask if server already has a session for user
                    948: sub has_user_session {
                    949:     my ($lonid,$udom,$uname) = @_;
                    950:     my $result = &reply(join(':','userhassession',
                    951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    952:     return 1 if ($result eq 'ok');
                    953: 
                    954:     return 0;
                    955: }
                    956: 
1.1076    raeburn   957: # --------- determine least loaded server in a user's domain which allows login
                    958: 
                    959: sub choose_server {
1.1259    raeburn   960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   962:     my %servers = &get_servers($udom);
1.1076    raeburn   963:     my $lowest_load = 30000;
1.1259    raeburn   964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    965:     if ($skiploadbal) {
                    966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    967:         unless (defined($cached)) {
                    968:             my $cachetime = 60*60*24;
                    969:             my %domconfig =
                    970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    973:                                            $cachetime);
                    974:             }
                    975:         }
                    976:     }
1.1076    raeburn   977:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn   978:         if ($skiploadbal) {
                    979:             if (ref($balancers) eq 'HASH') {
                    980:                 next if (exists($balancers->{$lonhost}));
                    981:             }
                    982:         }   
1.1115    raeburn   983:         my $loginvia;
                    984:         if ($checkloginvia) {
                    985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   986:             if ($loginvia) {
                    987:                 my ($server,$path) = split(/:/,$loginvia);
                    988:                 ($login_host, $lowest_load) =
1.1253    raeburn   989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   990:                 if ($login_host eq $server) {
                    991:                     $portal_path = $path;
1.1151    raeburn   992:                     $isredirect = 1;
1.1116    raeburn   993:                 }
                    994:             } else {
                    995:                 ($login_host, $lowest_load) =
1.1253    raeburn   996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $lonhost) {
                    998:                     $portal_path = '';
1.1151    raeburn   999:                     $isredirect = ''; 
1.1116    raeburn  1000:                 }
                   1001:             }
                   1002:         } else {
1.1076    raeburn  1003:             ($login_host, $lowest_load) =
1.1253    raeburn  1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1005:         }
                   1006:     }
                   1007:     if ($login_host ne '') {
1.1116    raeburn  1008:         $hostname = &hostname($login_host);
1.1076    raeburn  1009:     }
1.1151    raeburn  1010:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1011: }
                   1012: 
1.202     matthew  1013: # --------------------------------------------- Try to change a user's password
                   1014: 
                   1015: sub changepass {
1.799     raeburn  1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1017:     $currentpass = &escape($currentpass);
                   1018:     $newpass     = &escape($newpass);
1.1030    raeburn  1019:     my $lonhost = $perlvar{'lonHostID'};
                   1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1021: 		       $server);
                   1022:     if (! $answer) {
                   1023: 	&logthis("No reply on password change request to $server ".
                   1024: 		 "by $uname in domain $udom.");
                   1025:     } elsif ($answer =~ "^ok") {
                   1026:         &logthis("$uname in $udom successfully changed their password ".
                   1027: 		 "on $server.");
                   1028:     } elsif ($answer =~ "^pwchange_failure") {
                   1029: 	&logthis("$uname in $udom was unable to change their password ".
                   1030: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1031: 		 "or pwchange");
                   1032:     } elsif ($answer =~ "^non_authorized") {
                   1033:         &logthis("$uname in $udom did not get their password correct when ".
                   1034: 		 "attempting to change it on $server.");
                   1035:     } elsif ($answer =~ "^auth_mode_error") {
                   1036:         &logthis("$uname in $udom attempted to change their password despite ".
                   1037: 		 "not being locally or internally authenticated on $server.");
                   1038:     } elsif ($answer =~ "^unknown_user") {
                   1039:         &logthis("$uname in $udom attempted to change their password ".
                   1040: 		 "on $server but were unable to because $server is not ".
                   1041: 		 "their home server.");
                   1042:     } elsif ($answer =~ "^refused") {
                   1043: 	&logthis("$server refused to change $uname in $udom password because ".
                   1044: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1045:     } elsif ($answer =~ "invalid_client") {
                   1046:         &logthis("$server refused to change $uname in $udom password because ".
                   1047:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1048:     }
                   1049:     return $answer;
1.1       albertel 1050: }
                   1051: 
1.169     harris41 1052: # ----------------------- Try to determine user's current authentication scheme
                   1053: 
                   1054: sub queryauthenticate {
                   1055:     my ($uname,$udom)=@_;
1.456     albertel 1056:     my $uhome=&homeserver($uname,$udom);
                   1057:     if (!$uhome) {
                   1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1059: 	return 'no_host';
                   1060:     }
                   1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1064:     }
1.456     albertel 1065:     return $answer;
1.169     harris41 1066: }
                   1067: 
1.1       albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1069: 
1.1       albertel 1070: sub authenticate {
1.1073    raeburn  1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1072:     $upass=&escape($upass);
                   1073:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1074:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1075:     my $newhome;
1.836     www      1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1077: # Maybe the machine was offline and only re-appeared again recently?
                   1078:         &reconlonc();
                   1079: # One more
1.952     raeburn  1080: 	$uhome=&homeserver($uname,$udom,1);
                   1081:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1082:             if (defined(&domain($udom,'primary'))) {
                   1083:                 $newhome=&domain($udom,'primary');
                   1084:             }
                   1085:             if ($newhome ne '') {
                   1086:                 $uhome = $newhome;
                   1087:             }
                   1088:         }
1.836     www      1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1091: 	    return 'no_host';
                   1092:         }
1.1       albertel 1093:     }
1.1073    raeburn  1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1095:     if ($answer eq 'authorized') {
1.952     raeburn  1096:         if ($newhome) {
                   1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1098:             return 'no_account_on_host'; 
                   1099:         } else {
                   1100:             &logthis("User $uname at $udom authorized by $uhome");
                   1101:             return $uhome;
                   1102:         }
1.471     albertel 1103:     }
                   1104:     if ($answer eq 'non_authorized') {
                   1105: 	&logthis("User $uname at $udom rejected by $uhome");
                   1106: 	return 'no_host'; 
1.9       www      1107:     }
1.471     albertel 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1109:     return 'no_host';
                   1110: }
                   1111: 
1.1073    raeburn  1112: sub can_host_session {
1.1074    raeburn  1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1114:     my $canhost = 1;
1.1074    raeburn  1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1116:     if (ref($remotesessions) eq 'HASH') {
                   1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1119:                 $canhost = 0;
                   1120:             } else {
                   1121:                 $canhost = 1;
                   1122:             }
                   1123:         }
                   1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 1;
                   1127:             } else {
                   1128:                 $canhost = 0;
                   1129:             }
                   1130:         }
                   1131:         if ($canhost) {
                   1132:             if ($remotesessions->{'version'} ne '') {
                   1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1134:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1136:                         my $major = $1;
                   1137:                         my $minor = $2;
                   1138:                         if (($major < $reqmajor ) ||
                   1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1140:                             $canhost = 0;
                   1141:                         }
                   1142:                     } else {
                   1143:                         $canhost = 0;
                   1144:                     }
                   1145:                 }
                   1146:             }
                   1147:         }
                   1148:     }
                   1149:     if ($canhost) {
                   1150:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1154:                 if (($uint_dom ne '') && 
                   1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1156:                     $canhost = 0;
                   1157:                 } else {
                   1158:                     $canhost = 1;
                   1159:                 }
                   1160:             }
                   1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1162:                 if (($uint_dom ne '') && 
                   1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1164:                     $canhost = 1;
                   1165:                 } else {
                   1166:                     $canhost = 0;
                   1167:                 }
                   1168:             }
                   1169:         }
                   1170:     }
                   1171:     return $canhost;
                   1172: }
                   1173: 
1.1083    raeburn  1174: sub spare_can_host {
                   1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1176:     my $canhost=1;
1.1279  ! raeburn  1177:     my $try_server_hostname = &hostname($try_server);
        !          1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
        !          1179:     my $serverhomedom = &host_domain($serverhomeID);
        !          1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
        !          1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
        !          1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
        !          1183:             $canhost = 0;
        !          1184:         }
        !          1185:     }
        !          1186:     if (($canhost) && ($uint_dom)) {
        !          1187:         my @intdoms;
        !          1188:         my $internet_names = &get_internet_names($try_server);
        !          1189:         if (ref($internet_names) eq 'ARRAY') {
        !          1190:             @intdoms = @{$internet_names};
        !          1191:         }
        !          1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
        !          1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
        !          1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
        !          1195:                                          $remotesessions,
        !          1196:                                          $defdomdefaults{'hostedsessions'});
        !          1197:         }
1.1083    raeburn  1198:     }
                   1199:     return $canhost;
                   1200: }
                   1201: 
1.1123    raeburn  1202: sub this_host_spares {
                   1203:     my ($dom) = @_;
1.1126    raeburn  1204:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1205:     my @hosts = &current_machine_ids();
                   1206:     foreach my $lonhost (@hosts) {
                   1207:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1208:             $dom_in_use = $dom;
                   1209:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1210:             last;
                   1211:         }
                   1212:     }
1.1126    raeburn  1213:     if ($dom_in_use ne '') {
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:     }
                   1216:     if (ref($result) ne 'HASH') {
                   1217:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1218:         $dom_in_use = &host_domain($lonhost_in_use);
                   1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1220:         if (ref($result) ne 'HASH') {
                   1221:             $result = \%spareid;
                   1222:         }
                   1223:     }
                   1224:     return $result;
                   1225: }
                   1226: 
                   1227: sub spares_for_offload  {
                   1228:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1230:     if (defined($cached)) {
                   1231:         return $result;
                   1232:     } else {
1.1126    raeburn  1233:         my $cachetime = 60*60*24;
                   1234:         my %domconfig =
                   1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1240:                 }
                   1241:             }
                   1242:         }
                   1243:     }
1.1126    raeburn  1244:     return;
1.1123    raeburn  1245: }
                   1246: 
1.1129    raeburn  1247: sub get_lonbalancer_config {
                   1248:     my ($servers) = @_;
                   1249:     my ($currbalancer,$currtargets);
                   1250:     if (ref($servers) eq 'HASH') {
                   1251:         foreach my $server (keys(%{$servers})) {
                   1252:             my %what = (
                   1253:                          spareid => 1,
                   1254:                          perlvar => 1,
                   1255:                        );
                   1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1257:             if ($result eq 'ok') {
                   1258:                 if (ref($returnhash) eq 'HASH') {
                   1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1261:                             $currbalancer = $server;
                   1262:                             $currtargets = {};
                   1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1266:                                 }
                   1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1269:                                 }
                   1270:                             }
                   1271:                             last;
                   1272:                         }
                   1273:                     }
                   1274:                 }
                   1275:             }
                   1276:         }
                   1277:     }
                   1278:     return ($currbalancer,$currtargets);
                   1279: }
                   1280: 
                   1281: sub check_loadbalancing {
                   1282:     my ($uname,$udom) = @_;
1.1191    raeburn  1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1284:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1285:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1286:     my @hosts = &current_machine_ids();
1.1129    raeburn  1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1290:     my $serverhomedom = &host_domain($lonhost);
                   1291: 
                   1292:     my $cachetime = 60*60*24;
                   1293: 
                   1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1295:         $dom_in_use = $udom;
                   1296:         $homeintdom = 1;
                   1297:     } else {
                   1298:         $dom_in_use = $serverhomedom;
                   1299:     }
                   1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1301:     unless (defined($cached)) {
                   1302:         my %domconfig =
                   1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1306:         }
                   1307:     }
                   1308:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1309:         ($is_balancer,$currtargets,$currrules) = 
                   1310:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1311:         if ($is_balancer) {
                   1312:             if (ref($currrules) eq 'HASH') {
                   1313:                 if ($homeintdom) {
                   1314:                     if ($uname ne '') {
                   1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1321:                             }
                   1322:                         }
                   1323:                         if ($rule_in_effect eq '') {
                   1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1325:                             if ($userenv{'inststatus'} ne '') {
                   1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1327:                                 my ($othertitle,$usertypes,$types) =
                   1328:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1329:                                 if (ref($types) eq 'ARRAY') {
                   1330:                                     foreach my $type (@{$types}) {
                   1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1332:                                             if (exists($currrules->{$type})) {
                   1333:                                                 $rule_in_effect = $currrules->{$type};
                   1334:                                             }
                   1335:                                         }
                   1336:                                     }
                   1337:                                 }
                   1338:                             } else {
                   1339:                                 if (exists($currrules->{'default'})) {
                   1340:                                     $rule_in_effect = $currrules->{'default'};
                   1341:                                 }
                   1342:                             }
                   1343:                         }
                   1344:                     } else {
                   1345:                         if (exists($currrules->{'default'})) {
                   1346:                             $rule_in_effect = $currrules->{'default'};
                   1347:                         }
                   1348:                     }
                   1349:                 } else {
                   1350:                     if ($currrules->{'_LC_external'} ne '') {
                   1351:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1352:                     }
                   1353:                 }
                   1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1355:                                                        $uname,$udom);
                   1356:             }
                   1357:         }
                   1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1360:         unless (defined($cached)) {
                   1361:             my %domconfig =
                   1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1365:             }
                   1366:         }
                   1367:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1368:             ($is_balancer,$currtargets,$currrules) = 
                   1369:                 &check_balancer_result($result,@hosts);
                   1370:             if ($is_balancer) {
1.1129    raeburn  1371:                 if (ref($currrules) eq 'HASH') {
                   1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1374:                     }
                   1375:                 }
                   1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1377:                                                        $uname,$udom);
                   1378:             }
                   1379:         } else {
                   1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1381:                 $is_balancer = 1;
                   1382:                 $offloadto = &this_host_spares($dom_in_use);
                   1383:             }
                   1384:         }
                   1385:     } else {
                   1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1387:             $is_balancer = 1;
                   1388:             $offloadto = &this_host_spares($dom_in_use);
                   1389:         }
                   1390:     }
1.1176    raeburn  1391:     if ($is_balancer) {
                   1392:         my $lowest_load = 30000;
                   1393:         if (ref($offloadto) eq 'HASH') {
                   1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1396:                     ($otherserver,$lowest_load) =
                   1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1398:                 }
1.1129    raeburn  1399:             }
1.1176    raeburn  1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1401: 
1.1176    raeburn  1402:             if (!$found_server) {
                   1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1405:                         ($otherserver,$lowest_load) =
                   1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1407:                     }
                   1408:                 }
                   1409:             }
                   1410:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1411:             if (@{$offloadto} == 1) {
                   1412:                 $otherserver = $offloadto->[0];
                   1413:             } elsif (@{$offloadto} > 1) {
                   1414:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1415:                     ($otherserver,$lowest_load) =
                   1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1417:                 }
                   1418:             }
                   1419:         }
1.1176    raeburn  1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1421:             $is_balancer = 0;
                   1422:             if ($uname ne '' && $udom ne '') {
                   1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1424:                     
                   1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1426:                              'user.loadbalcheck.time' => time});
                   1427:                 }
1.1129    raeburn  1428:             }
                   1429:         }
                   1430:     }
                   1431:     return ($is_balancer,$otherserver);
                   1432: }
                   1433: 
1.1191    raeburn  1434: sub check_balancer_result {
                   1435:     my ($result,@hosts) = @_;
                   1436:     my ($is_balancer,$currtargets,$currrules);
                   1437:     if (ref($result) eq 'HASH') {
                   1438:         if ($result->{'lonhost'} ne '') {
                   1439:             my $currbalancer = $result->{'lonhost'};
                   1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1441:                 $is_balancer = 1;
                   1442:                 $currtargets = $result->{'targets'};
                   1443:                 $currrules = $result->{'rules'};
                   1444:             }
                   1445:         } else {
                   1446:             foreach my $key (keys(%{$result})) {
                   1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1448:                     (ref($result->{$key}) eq 'HASH')) {
                   1449:                     $is_balancer = 1;
                   1450:                     $currrules = $result->{$key}{'rules'};
                   1451:                     $currtargets = $result->{$key}{'targets'};
                   1452:                     last;
                   1453:                 }
                   1454:             }
                   1455:         }
                   1456:     }
                   1457:     return ($is_balancer,$currtargets,$currrules);
                   1458: }
                   1459: 
1.1129    raeburn  1460: sub get_loadbalancer_targets {
                   1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1462:     my $offloadto;
1.1175    raeburn  1463:     if ($rule_in_effect eq 'none') {
                   1464:         return [$perlvar{'lonHostID'}];
                   1465:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1466:         $offloadto = $currtargets;
                   1467:     } else {
                   1468:         if ($rule_in_effect eq 'homeserver') {
                   1469:             my $homeserver = &homeserver($uname,$udom);
                   1470:             if ($homeserver ne 'no_host') {
                   1471:                 $offloadto = [$homeserver];
                   1472:             }
                   1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1474:             my %domconfig =
                   1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1480:                     }
                   1481:                 }
                   1482:             } else {
1.1178    raeburn  1483:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1485:                 if (&hostname($remotebalancer) ne '') {
                   1486:                     $offloadto = [$remotebalancer];
                   1487:                 }
                   1488:             }
                   1489:         } elsif (&hostname($rule_in_effect) ne '') {
                   1490:             $offloadto = [$rule_in_effect];
                   1491:         }
                   1492:     }
                   1493:     return $offloadto;
                   1494: }
                   1495: 
1.1127    raeburn  1496: sub internet_dom_servers {
                   1497:     my ($dom) = @_;
                   1498:     my (%uniqservers,%servers);
                   1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1500:     my @machinedoms = &machine_domains($primaryserver);
                   1501:     foreach my $mdom (@machinedoms) {
                   1502:         my %currservers = %servers;
                   1503:         my %server = &get_servers($mdom);
                   1504:         %servers = (%currservers,%server);
                   1505:     }
                   1506:     my %by_hostname;
                   1507:     foreach my $id (keys(%servers)) {
                   1508:         push(@{$by_hostname{$servers{$id}}},$id);
                   1509:     }
                   1510:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1511:         if (@{$by_hostname{$hostname}} > 1) {
                   1512:             my $match = 0;
                   1513:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1514:                 if (&host_domain($id) eq $dom) {
                   1515:                     $uniqservers{$id} = $hostname;
                   1516:                     $match = 1;
                   1517:                 }
                   1518:             }
                   1519:             unless ($match) {
                   1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1521:             }
                   1522:         } else {
                   1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1524:         }
                   1525:     }
                   1526:     return %uniqservers;
                   1527: }
                   1528: 
1.1       albertel 1529: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1530: 
1.599     albertel 1531: my %homecache;
1.1       albertel 1532: sub homeserver {
1.230     stredwic 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1534:     my $index="$uname:$udom";
1.426     albertel 1535: 
1.599     albertel 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1537: 
                   1538:     my %servers = &get_servers($udom,'library');
                   1539:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1540:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1541: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1542: 
                   1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1544: 	if ($answer eq 'found') {
                   1545: 	    delete($badServerCache{$tryserver}); 
                   1546: 	    return $homecache{$index}=$tryserver;
                   1547: 	} elsif ($answer eq 'no_host') {
                   1548: 	    $badServerCache{$tryserver}=1;
                   1549: 	}
1.1       albertel 1550:     }    
                   1551:     return 'no_host';
1.70      www      1552: }
                   1553: 
                   1554: # ------------------------------------- Find the usernames behind a list of IDs
                   1555: 
                   1556: sub idget {
                   1557:     my ($udom,@ids)=@_;
                   1558:     my %returnhash=();
                   1559:     
1.841     albertel 1560:     my %servers = &get_servers($udom,'library');
                   1561:     foreach my $tryserver (keys(%servers)) {
                   1562: 	my $idlist=join('&',@ids);
                   1563: 	$idlist=~tr/A-Z/a-z/; 
                   1564: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1565: 	my @answer=();
                   1566: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1567: 	    @answer=split(/\&/,$reply);
                   1568: 	}                    ;
                   1569: 	my $i;
                   1570: 	for ($i=0;$i<=$#ids;$i++) {
                   1571: 	    if ($answer[$i]) {
                   1572: 		$returnhash{$ids[$i]}=$answer[$i];
                   1573: 	    } 
                   1574: 	}
                   1575:     } 
1.70      www      1576:     return %returnhash;
                   1577: }
                   1578: 
                   1579: # ------------------------------------- Find the IDs behind a list of usernames
                   1580: 
                   1581: sub idrget {
                   1582:     my ($udom,@unames)=@_;
                   1583:     my %returnhash=();
1.800     albertel 1584:     foreach my $uname (@unames) {
                   1585:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1586:     }
1.70      www      1587:     return %returnhash;
                   1588: }
                   1589: 
                   1590: # ------------------------------- Store away a list of names and associated IDs
                   1591: 
                   1592: sub idput {
                   1593:     my ($udom,%ids)=@_;
                   1594:     my %servers=();
1.800     albertel 1595:     foreach my $uname (keys(%ids)) {
                   1596: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1597:         my $uhom=&homeserver($uname,$udom);
1.70      www      1598:         if ($uhom ne 'no_host') {
1.800     albertel 1599:             my $id=&escape($ids{$uname});
1.70      www      1600:             $id=~tr/A-Z/a-z/;
1.800     albertel 1601:             my $esc_unam=&escape($uname);
1.70      www      1602: 	    if ($servers{$uhom}) {
1.800     albertel 1603: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1604:             } else {
1.800     albertel 1605:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1606:             }
                   1607:         }
1.191     harris41 1608:     }
1.800     albertel 1609:     foreach my $server (keys(%servers)) {
                   1610:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1611:     }
1.344     www      1612: }
                   1613: 
1.1231    raeburn  1614: # ---------------------------------------- Delete unwanted IDs from ids.db file 
                   1615: 
                   1616: sub iddel {
                   1617:     my ($udom,$idshashref,$uhome)=@_;
                   1618:     my %result=();
                   1619:     unless (ref($idshashref) eq 'HASH') {
                   1620:         return %result;
                   1621:     }
                   1622:     my %servers=();
                   1623:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1624:         my $uhom;
                   1625:         if ($uhome) {
                   1626:             $uhom = $uhome;
                   1627:         } else {
                   1628:             $uhom=&homeserver($uname,$udom);
                   1629:         }
                   1630:         if ($uhom ne 'no_host') {
                   1631:             if ($servers{$uhom}) {
                   1632:                 $servers{$uhom}.='&'.&escape($id);
                   1633:             } else {
                   1634:                 $servers{$uhom}=&escape($id);
                   1635:             }
                   1636:         }
                   1637:     }
                   1638:     foreach my $server (keys(%servers)) {
                   1639:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1640:     }
                   1641:     return %result;
                   1642: }
                   1643: 
1.1023    raeburn  1644: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1645: sub dump_dom {
1.1165    droeschl 1646:     my ($namespace, $udom, $regexp) = @_;
                   1647: 
                   1648:     $udom ||= $env{'user.domain'};
                   1649: 
                   1650:     return () unless $udom;
                   1651: 
                   1652:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1653: }
                   1654: 
1.1023    raeburn  1655: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1656: 
                   1657: sub get_dom {
1.860     raeburn  1658:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1659:     return if ($udom eq 'public');
1.806     raeburn  1660:     my $items='';
                   1661:     foreach my $item (@$storearr) {
                   1662:         $items.=&escape($item).'&';
                   1663:     }
                   1664:     $items=~s/\&$//;
1.860     raeburn  1665:     if (!$udom) {
                   1666:         $udom=$env{'user.domain'};
1.1267    raeburn  1667:         return if ($udom eq 'public');
1.860     raeburn  1668:         if (defined(&domain($udom,'primary'))) {
                   1669:             $uhome=&domain($udom,'primary');
                   1670:         } else {
1.874     albertel 1671:             undef($uhome);
1.860     raeburn  1672:         }
                   1673:     } else {
                   1674:         if (!$uhome) {
                   1675:             if (defined(&domain($udom,'primary'))) {
                   1676:                 $uhome=&domain($udom,'primary');
                   1677:             }
                   1678:         }
                   1679:     }
                   1680:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1681:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1682:         my %returnhash;
1.875     albertel 1683:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1684:             return %returnhash;
                   1685:         }
1.806     raeburn  1686:         my @pairs=split(/\&/,$rep);
                   1687:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1688:             return @pairs;
                   1689:         }
                   1690:         my $i=0;
                   1691:         foreach my $item (@$storearr) {
                   1692:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1693:             $i++;
                   1694:         }
                   1695:         return %returnhash;
                   1696:     } else {
1.880     banghart 1697:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1698:     }
                   1699: }
                   1700: 
                   1701: # -------------------------------------------- put items in domain db files 
                   1702: 
                   1703: sub put_dom {
1.860     raeburn  1704:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1705:     if (!$udom) {
                   1706:         $udom=$env{'user.domain'};
                   1707:         if (defined(&domain($udom,'primary'))) {
                   1708:             $uhome=&domain($udom,'primary');
                   1709:         } else {
1.874     albertel 1710:             undef($uhome);
1.860     raeburn  1711:         }
                   1712:     } else {
                   1713:         if (!$uhome) {
                   1714:             if (defined(&domain($udom,'primary'))) {
                   1715:                 $uhome=&domain($udom,'primary');
                   1716:             }
                   1717:         }
                   1718:     } 
                   1719:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1720:         my $items='';
                   1721:         foreach my $item (keys(%$storehash)) {
                   1722:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1723:         }
                   1724:         $items=~s/\&$//;
                   1725:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1726:     } else {
1.860     raeburn  1727:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1728:     }
                   1729: }
                   1730: 
1.1023    raeburn  1731: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1732: sub newput_dom {
1.1023    raeburn  1733:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1734:     my $result;
                   1735:     if (!$udom) {
                   1736:         $udom=$env{'user.domain'};
                   1737:     }
1.1023    raeburn  1738:     if ($udom) {
                   1739:         my $uname = &get_domainconfiguser($udom);
                   1740:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1741:     }
                   1742:     return $result;
                   1743: }
                   1744: 
1.1023    raeburn  1745: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1746: sub del_dom {
1.1023    raeburn  1747:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1748:     if (ref($storearr) eq 'ARRAY') {
                   1749:         if (!$udom) {
                   1750:             $udom=$env{'user.domain'};
                   1751:         }
1.1023    raeburn  1752:         if ($udom) {
                   1753:             my $uname = &get_domainconfiguser($udom); 
                   1754:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1755:         }
                   1756:     }
                   1757: }
                   1758: 
1.1023    raeburn  1759: # ----------------------------------construct domainconfig user for a domain 
                   1760: sub get_domainconfiguser {
                   1761:     my ($udom) = @_;
                   1762:     return $udom.'-domainconfig';
                   1763: }
                   1764: 
1.837     raeburn  1765: sub retrieve_inst_usertypes {
                   1766:     my ($udom) = @_;
                   1767:     my (%returnhash,@order);
1.989     raeburn  1768:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1769:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1770:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1771:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1772:     } else {
                   1773:         if (defined(&domain($udom,'primary'))) {
                   1774:             my $uhome=&domain($udom,'primary');
                   1775:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1776:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1777:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1778:                 return (\%returnhash,\@order);
                   1779:             }
                   1780:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1781:             my @pairs=split(/\&/,$hashitems);
                   1782:             foreach my $item (@pairs) {
                   1783:                 my ($key,$value)=split(/=/,$item,2);
                   1784:                 $key = &unescape($key);
                   1785:                 next if ($key =~ /^error: 2 /);
                   1786:                 $returnhash{$key}=&thaw_unescape($value);
                   1787:             }
                   1788:             my @esc_order = split(/\&/,$orderitems);
                   1789:             foreach my $item (@esc_order) {
                   1790:                 push(@order,&unescape($item));
                   1791:             }
                   1792:         } else {
1.1256    raeburn  1793:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1794:         }
1.1256    raeburn  1795:         return (\%returnhash,\@order);
1.837     raeburn  1796:     }
                   1797: }
                   1798: 
1.868     raeburn  1799: sub is_domainimage {
                   1800:     my ($url) = @_;
                   1801:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1802:         if (&domain($1) ne '') {
                   1803:             return '1';
                   1804:         }
                   1805:     }
                   1806:     return;
                   1807: }
                   1808: 
1.899     raeburn  1809: sub inst_directory_query {
                   1810:     my ($srch) = @_;
                   1811:     my $udom = $srch->{'srchdomain'};
                   1812:     my %results;
                   1813:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1814:     my $outcome;
1.899     raeburn  1815:     if ($homeserver ne '') {
1.904     albertel 1816: 	my $queryid=&reply("querysend:instdirsearch:".
                   1817: 			   &escape($srch->{'srchby'}).':'.
                   1818: 			   &escape($srch->{'srchterm'}).':'.
                   1819: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1820: 	my $host=&hostname($homeserver);
                   1821: 	if ($queryid !~/^\Q$host\E\_/) {
                   1822: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1823: 	    return;
                   1824: 	}
                   1825: 	my $response = &get_query_reply($queryid);
                   1826: 	my $maxtries = 5;
                   1827: 	my $tries = 1;
                   1828: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1829: 	    $response = &get_query_reply($queryid);
                   1830: 	    $tries ++;
                   1831: 	}
                   1832: 
                   1833:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1834:             if ($response eq 'unavailable') {
                   1835:                 $outcome = $response;
                   1836:             } else {
                   1837:                 $outcome = 'ok';
                   1838:                 my @matches = split(/\n/,$response);
                   1839:                 foreach my $match (@matches) {
                   1840:                     my ($key,$value) = split(/=/,$match);
                   1841:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1842:                 }
1.899     raeburn  1843:             }
                   1844:         }
                   1845:     }
1.909     raeburn  1846:     return ($outcome,%results);
1.899     raeburn  1847: }
                   1848: 
                   1849: sub usersearch {
                   1850:     my ($srch) = @_;
                   1851:     my $dom = $srch->{'srchdomain'};
                   1852:     my %results;
                   1853:     my %libserv = &all_library();
                   1854:     my $query = 'usersearch';
                   1855:     foreach my $tryserver (keys(%libserv)) {
                   1856:         if (&host_domain($tryserver) eq $dom) {
                   1857:             my $host=&hostname($tryserver);
                   1858:             my $queryid=
1.911     raeburn  1859:                 &reply("querysend:".&escape($query).':'.
                   1860:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1861:                        &escape($srch->{'srchtype'}).':'.
                   1862:                        &escape($srch->{'srchterm'}),$tryserver);
                   1863:             if ($queryid !~/^\Q$host\E\_/) {
                   1864:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1865:                 next;
1.899     raeburn  1866:             }
                   1867:             my $reply = &get_query_reply($queryid);
                   1868:             my $maxtries = 1;
                   1869:             my $tries = 1;
                   1870:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1871:                 $reply = &get_query_reply($queryid);
                   1872:                 $tries ++;
                   1873:             }
                   1874:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1875:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1876:             } else {
1.911     raeburn  1877:                 my @matches;
                   1878:                 if ($reply =~ /\n/) {
                   1879:                     @matches = split(/\n/,$reply);
                   1880:                 } else {
                   1881:                     @matches = split(/\&/,$reply);
                   1882:                 }
1.899     raeburn  1883:                 foreach my $match (@matches) {
                   1884:                     my ($uname,$udom,%userhash);
1.911     raeburn  1885:                     foreach my $entry (split(/:/,$match)) {
                   1886:                         my ($key,$value) =
                   1887:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1888:                         $userhash{$key} = $value;
                   1889:                         if ($key eq 'username') {
                   1890:                             $uname = $value;
                   1891:                         } elsif ($key eq 'domain') {
                   1892:                             $udom = $value;
1.911     raeburn  1893:                         }
1.899     raeburn  1894:                     }
                   1895:                     $results{$uname.':'.$udom} = \%userhash;
                   1896:                 }
                   1897:             }
                   1898:         }
                   1899:     }
                   1900:     return %results;
                   1901: }
                   1902: 
1.912     raeburn  1903: sub get_instuser {
                   1904:     my ($udom,$uname,$id) = @_;
                   1905:     my $homeserver = &domain($udom,'primary');
                   1906:     my ($outcome,%results);
                   1907:     if ($homeserver ne '') {
                   1908:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1909:                            &escape($id).':'.&escape($udom),$homeserver);
                   1910:         my $host=&hostname($homeserver);
                   1911:         if ($queryid !~/^\Q$host\E\_/) {
                   1912:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1913:             return;
                   1914:         }
                   1915:         my $response = &get_query_reply($queryid);
                   1916:         my $maxtries = 5;
                   1917:         my $tries = 1;
                   1918:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1919:             $response = &get_query_reply($queryid);
                   1920:             $tries ++;
                   1921:         }
                   1922:         if (!&error($response) && $response ne 'refused') {
                   1923:             if ($response eq 'unavailable') {
                   1924:                 $outcome = $response;
                   1925:             } else {
                   1926:                 $outcome = 'ok';
                   1927:                 my @matches = split(/\n/,$response);
                   1928:                 foreach my $match (@matches) {
                   1929:                     my ($key,$value) = split(/=/,$match);
                   1930:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1931:                 }
                   1932:             }
                   1933:         }
                   1934:     }
                   1935:     my %userinfo;
                   1936:     if (ref($results{$uname}) eq 'HASH') {
                   1937:         %userinfo = %{$results{$uname}};
                   1938:     } 
                   1939:     return ($outcome,%userinfo);
                   1940: }
                   1941: 
                   1942: sub inst_rulecheck {
1.923     raeburn  1943:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1944:     my %returnhash;
                   1945:     if ($udom ne '') {
                   1946:         if (ref($rules) eq 'ARRAY') {
                   1947:             @{$rules} = map {&escape($_);} (@{$rules});
                   1948:             my $rulestr = join(':',@{$rules});
                   1949:             my $homeserver=&domain($udom,'primary');
                   1950:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1951:                 my $response;
                   1952:                 if ($item eq 'username') {                
                   1953:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1954:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1955:                                               $homeserver));
1.923     raeburn  1956:                 } elsif ($item eq 'id') {
                   1957:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1958:                                               ':'.&escape($id).':'.$rulestr,
                   1959:                                               $homeserver));
1.945     raeburn  1960:                 } elsif ($item eq 'selfcreate') {
                   1961:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1962:                                                &escape($udom).':'.&escape($uname).
                   1963:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1964:                 }
1.912     raeburn  1965:                 if ($response ne 'refused') {
                   1966:                     my @pairs=split(/\&/,$response);
                   1967:                     foreach my $item (@pairs) {
                   1968:                         my ($key,$value)=split(/=/,$item,2);
                   1969:                         $key = &unescape($key);
                   1970:                         next if ($key =~ /^error: 2 /);
                   1971:                         $returnhash{$key}=&thaw_unescape($value);
                   1972:                     }
                   1973:                 }
                   1974:             }
                   1975:         }
                   1976:     }
                   1977:     return %returnhash;
                   1978: }
                   1979: 
                   1980: sub inst_userrules {
1.923     raeburn  1981:     my ($udom,$check) = @_;
1.912     raeburn  1982:     my (%ruleshash,@ruleorder);
                   1983:     if ($udom ne '') {
                   1984:         my $homeserver=&domain($udom,'primary');
                   1985:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1986:             my $response;
                   1987:             if ($check eq 'id') {
                   1988:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1989:                                  $homeserver);
1.943     raeburn  1990:             } elsif ($check eq 'email') {
                   1991:                 $response=&reply('instemailrules:'.&escape($udom),
                   1992:                                  $homeserver);
1.923     raeburn  1993:             } else {
                   1994:                 $response=&reply('instuserrules:'.&escape($udom),
                   1995:                                  $homeserver);
                   1996:             }
1.912     raeburn  1997:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1998:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1999:                 ($response ne 'no_such_host')) {
                   2000:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2001:                 my @pairs=split(/\&/,$hashitems);
                   2002:                 foreach my $item (@pairs) {
                   2003:                     my ($key,$value)=split(/=/,$item,2);
                   2004:                     $key = &unescape($key);
                   2005:                     next if ($key =~ /^error: 2 /);
                   2006:                     $ruleshash{$key}=&thaw_unescape($value);
                   2007:                 }
                   2008:                 my @esc_order = split(/\&/,$orderitems);
                   2009:                 foreach my $item (@esc_order) {
                   2010:                     push(@ruleorder,&unescape($item));
                   2011:                 }
                   2012:             }
                   2013:         }
                   2014:     }
                   2015:     return (\%ruleshash,\@ruleorder);
                   2016: }
                   2017: 
1.976     raeburn  2018: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2019: 
                   2020: sub get_domain_defaults {
1.1240    raeburn  2021:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2022:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2023:     my $cachetime = 60*60*24;
1.1240    raeburn  2024:     unless ($ignore_cache) {
                   2025:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2026:         if (defined($cached)) {
                   2027:             if (ref($result) eq 'HASH') {
                   2028:                 return %{$result};
                   2029:             }
1.943     raeburn  2030:         }
                   2031:     }
                   2032:     my %domdefaults;
                   2033:     my %domconfig =
1.989     raeburn  2034:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2035:                                   'requestcourses','inststatus',
1.1183    raeburn  2036:                                   'coursedefaults','usersessions',
1.1258    raeburn  2037:                                   'requestauthor','selfenrollment',
                   2038:                                   'coursecategories'],$domain);
1.1254    raeburn  2039:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2040:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2041:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2042:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2043:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2044:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2045:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2046:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2047:     } else {
                   2048:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2049:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2050:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2051:     }
1.976     raeburn  2052:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2053:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2054:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2055:         } else {
                   2056:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2057:         }
1.1177    raeburn  2058:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2059:         foreach my $item (@usertools) {
                   2060:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2061:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2062:             }
                   2063:         }
1.1229    raeburn  2064:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2065:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2066:         }
1.976     raeburn  2067:     }
1.985     raeburn  2068:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246    raeburn  2069:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2070:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2071:         }
                   2072:     }
1.1183    raeburn  2073:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2074:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2075:     }
1.989     raeburn  2076:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2077:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2078:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2079:         }
                   2080:     }
1.1047    raeburn  2081:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2082:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2083:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2084:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2085:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2086:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2087:         }
1.1254    raeburn  2088:         foreach my $type (@coursetypes) {
                   2089:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2090:                 unless ($type eq 'community') {
                   2091:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2092:                 }
                   2093:             }
                   2094:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2095:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2096:             }
1.1277    raeburn  2097:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2098:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2099:                     $domdefaults{$type.'postsubtimeout'} = 
                   2100:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2101:                 }
                   2102:             }
1.1230    raeburn  2103:         }
1.1047    raeburn  2104:     }
1.1073    raeburn  2105:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2106:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2107:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2108:         }
                   2109:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2110:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2111:         }
1.1279  ! raeburn  2112:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
        !          2113:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
        !          2114:         }
1.1073    raeburn  2115:     }
1.1254    raeburn  2116:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2117:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2118:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2119:                             'approval','limit');
                   2120:             foreach my $type (@coursetypes) {
                   2121:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2122:                     my @mgrdc = ();
                   2123:                     foreach my $item (@settings) {
                   2124:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2125:                             push(@mgrdc,$item);
                   2126:                         }
                   2127:                     }
                   2128:                     if (@mgrdc) {
                   2129:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2130:                     }
                   2131:                 }
                   2132:             }
                   2133:         }
                   2134:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2135:             foreach my $type (@coursetypes) {
                   2136:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2137:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2138:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2139:                     }
                   2140:                 }
                   2141:             }
                   2142:         }
                   2143:     }
1.1258    raeburn  2144:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2145:         $domdefaults{'catauth'} = 'std';
                   2146:         $domdefaults{'catunauth'} = 'std';
                   2147:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2148:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2149:         }
                   2150:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2151:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2152:         }
                   2153:     }
1.1219    raeburn  2154:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2155:     return %domdefaults;
                   2156: }
                   2157: 
1.344     www      2158: # --------------------------------------------------- Assign a key to a student
                   2159: 
                   2160: sub assign_access_key {
1.364     www      2161: #
                   2162: # a valid key looks like uname:udom#comments
                   2163: # comments are being appended
                   2164: #
1.498     www      2165:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2166:     $kdom=
1.620     albertel 2167:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2168:     $knum=
1.620     albertel 2169:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2170:     $cdom=
1.620     albertel 2171:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2172:     $cnum=
1.620     albertel 2173:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2174:     $udom=$env{'user.name'} unless (defined($udom));
                   2175:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2176:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2177:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2178:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2179:                                                   # assigned to this person
                   2180:                                                   # - this should not happen,
1.345     www      2181:                                                   # unless something went wrong
                   2182:                                                   # the first time around
                   2183: # ready to assign
1.364     www      2184:         $logentry=$1.'; '.$logentry;
1.496     www      2185:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2186:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2187: # key now belongs to user
1.346     www      2188: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2189:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2190:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2191:                 return 'ok';
                   2192:             } else {
                   2193:                 return 
                   2194:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2195: 	    }
                   2196:         } else {
                   2197:             return 'error: Could not assign key, try again later.';
                   2198:         }
1.364     www      2199:     } elsif (!$existing{$ckey}) {
1.345     www      2200: # the key does not exist
                   2201: 	return 'error: The key does not exist';
                   2202:     } else {
                   2203: # the key is somebody else's
                   2204: 	return 'error: The key is already in use';
                   2205:     }
1.344     www      2206: }
                   2207: 
1.364     www      2208: # ------------------------------------------ put an additional comment on a key
                   2209: 
                   2210: sub comment_access_key {
                   2211: #
                   2212: # a valid key looks like uname:udom#comments
                   2213: # comments are being appended
                   2214: #
                   2215:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2216:     $cdom=
1.620     albertel 2217:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2218:     $cnum=
1.620     albertel 2219:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2220:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2221:     if ($existing{$ckey}) {
                   2222:         $existing{$ckey}.='; '.$logentry;
                   2223: # ready to assign
1.367     www      2224:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2225:                                                  $cdom,$cnum) eq 'ok') {
                   2226: 	    return 'ok';
                   2227:         } else {
                   2228: 	    return 'error: Count not store comment.';
                   2229:         }
                   2230:     } else {
                   2231: # the key does not exist
                   2232: 	return 'error: The key does not exist';
                   2233:     }
                   2234: }
                   2235: 
1.344     www      2236: # ------------------------------------------------------ Generate a set of keys
                   2237: 
                   2238: sub generate_access_keys {
1.364     www      2239:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2240:     $cdom=
1.620     albertel 2241:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2242:     $cnum=
1.620     albertel 2243:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2244:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2245:     unless (($cdom) && ($cnum)) { return 0; }
                   2246:     if ($number>10000) { return 0; }
                   2247:     sleep(2); # make sure don't get same seed twice
                   2248:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2249:     my $total=0;
                   2250:     for (my $i=1;$i<=$number;$i++) {
                   2251:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2252:                   sprintf("%lx",int(100000*rand)).'-'.
                   2253:                   sprintf("%lx",int(100000*rand));
                   2254:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2255:        $newkey=~s/0/h/g; # and also 0 and O
                   2256:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2257:        if ($existing{$newkey}) {
                   2258:            $i--;
                   2259:        } else {
1.364     www      2260: 	  if (&put('accesskeys',
                   2261:               { $newkey => '# generated '.localtime().
1.620     albertel 2262:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2263:                            '; '.$logentry },
                   2264: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2265:               $total++;
                   2266: 	  }
                   2267:        }
                   2268:     }
1.620     albertel 2269:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2270:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2271:     return $total;
                   2272: }
                   2273: 
                   2274: # ------------------------------------------------------- Validate an accesskey
                   2275: 
                   2276: sub validate_access_key {
                   2277:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2278:     $cdom=
1.620     albertel 2279:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2280:     $cnum=
1.620     albertel 2281:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2282:     $udom=$env{'user.domain'} unless (defined($udom));
                   2283:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2284:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2285:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2286: }
                   2287: 
                   2288: # ------------------------------------- Find the section of student in a course
1.652     albertel 2289: sub devalidate_getsection_cache {
                   2290:     my ($udom,$unam,$courseid)=@_;
                   2291:     my $hashid="$udom:$unam:$courseid";
                   2292:     &devalidate_cache_new('getsection',$hashid);
                   2293: }
1.298     matthew  2294: 
1.815     albertel 2295: sub courseid_to_courseurl {
                   2296:     my ($courseid) = @_;
                   2297:     #already url style courseid
                   2298:     return $courseid if ($courseid =~ m{^/});
                   2299: 
                   2300:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2301: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2302: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2303: 	return "/$cdom/$cnum";
                   2304:     }
                   2305: 
                   2306:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2307:     if (exists($courseinfo{'num'})) {
                   2308: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2309:     }
                   2310: 
                   2311:     return undef;
                   2312: }
                   2313: 
1.298     matthew  2314: sub getsection {
                   2315:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2316:     my $cachetime=1800;
1.551     albertel 2317: 
                   2318:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2319:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2320:     if (defined($cached)) { return $result; }
                   2321: 
1.298     matthew  2322:     my %Pending; 
                   2323:     my %Expired;
                   2324:     #
                   2325:     # Each role can either have not started yet (pending), be active, 
                   2326:     #    or have expired.
                   2327:     #
                   2328:     # If there is an active role, we are done.
                   2329:     #
                   2330:     # If there is more than one role which has not started yet, 
                   2331:     #     choose the one which will start sooner
                   2332:     # If there is one role which has not started yet, return it.
                   2333:     #
                   2334:     # If there is more than one expired role, choose the one which ended last.
                   2335:     # If there is a role which has expired, return it.
                   2336:     #
1.815     albertel 2337:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2338:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2339:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2340:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2341:         my $section=$1;
                   2342:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2343:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2344:         my $now=time;
1.548     albertel 2345:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2346:             $Expired{$end}=$section;
                   2347:             next;
                   2348:         }
1.548     albertel 2349:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2350:             $Pending{$start}=$section;
                   2351:             next;
                   2352:         }
1.599     albertel 2353:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2354:     }
                   2355:     #
                   2356:     # Presumedly there will be few matching roles from the above
                   2357:     # loop and the sorting time will be negligible.
                   2358:     if (scalar(keys(%Pending))) {
                   2359:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2360:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2361:     } 
                   2362:     if (scalar(keys(%Expired))) {
                   2363:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2364:         my $time = pop(@sorted);
1.599     albertel 2365:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2366:     }
1.599     albertel 2367:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2368: }
1.70      www      2369: 
1.599     albertel 2370: sub save_cache {
                   2371:     &purge_remembered();
1.722     albertel 2372:     #&Apache::loncommon::validate_page();
1.620     albertel 2373:     undef(%env);
1.780     albertel 2374:     undef($env_loaded);
1.599     albertel 2375: }
1.452     albertel 2376: 
1.599     albertel 2377: my $to_remember=-1;
                   2378: my %remembered;
                   2379: my %accessed;
                   2380: my $kicks=0;
                   2381: my $hits=0;
1.849     albertel 2382: sub make_key {
                   2383:     my ($name,$id) = @_;
1.872     albertel 2384:     if (length($id) > 65 
                   2385: 	&& length(&escape($id)) > 200) {
                   2386: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2387:     }
1.849     albertel 2388:     return &escape($name.':'.$id);
                   2389: }
                   2390: 
1.599     albertel 2391: sub devalidate_cache_new {
                   2392:     my ($name,$id,$debug) = @_;
                   2393:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2394:     $id=&make_key($name,$id);
1.599     albertel 2395:     $memcache->delete($id);
                   2396:     delete($remembered{$id});
                   2397:     delete($accessed{$id});
                   2398: }
                   2399: 
                   2400: sub is_cached_new {
                   2401:     my ($name,$id,$debug) = @_;
1.849     albertel 2402:     $id=&make_key($name,$id);
1.599     albertel 2403:     if (exists($remembered{$id})) {
1.1133    foxr     2404: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2405: 	$accessed{$id}=[&gettimeofday()];
                   2406: 	$hits++;
                   2407: 	return ($remembered{$id},1);
                   2408:     }
                   2409:     my $value = $memcache->get($id);
                   2410:     if (!(defined($value))) {
                   2411: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2412: 	return (undef,undef);
1.416     albertel 2413:     }
1.599     albertel 2414:     if ($value eq '__undef__') {
                   2415: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2416: 	$value=undef;
                   2417:     }
                   2418:     &make_room($id,$value,$debug);
                   2419:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2420:     return ($value,1);
                   2421: }
                   2422: 
                   2423: sub do_cache_new {
                   2424:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2425:     $id=&make_key($name,$id);
1.599     albertel 2426:     my $setvalue=$value;
                   2427:     if (!defined($setvalue)) {
                   2428: 	$setvalue='__undef__';
                   2429:     }
1.623     albertel 2430:     if (!defined($time) ) {
                   2431: 	$time=600;
                   2432:     }
1.599     albertel 2433:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2434:     my $result = $memcache->set($id,$setvalue,$time);
                   2435:     if (! $result) {
1.872     albertel 2436: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2437: 	$memcache->disconnect_all();
1.872     albertel 2438:     }
1.600     albertel 2439:     # need to make a copy of $value
1.919     albertel 2440:     &make_room($id,$value,$debug);
1.599     albertel 2441:     return $value;
                   2442: }
                   2443: 
                   2444: sub make_room {
                   2445:     my ($id,$value,$debug)=@_;
1.919     albertel 2446: 
                   2447:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2448:                                     : $value;
1.599     albertel 2449:     if ($to_remember<0) { return; }
                   2450:     $accessed{$id}=[&gettimeofday()];
                   2451:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2452:     my $to_kick;
                   2453:     my $max_time=0;
                   2454:     foreach my $other (keys(%accessed)) {
                   2455: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2456: 	    $to_kick=$other;
                   2457: 	    $max_time=&tv_interval($accessed{$other});
                   2458: 	}
                   2459:     }
                   2460:     delete($remembered{$to_kick});
                   2461:     delete($accessed{$to_kick});
                   2462:     $kicks++;
                   2463:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2464:     return;
                   2465: }
                   2466: 
1.599     albertel 2467: sub purge_remembered {
1.604     albertel 2468:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2469:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2470:     undef(%remembered);
                   2471:     undef(%accessed);
1.428     albertel 2472: }
1.70      www      2473: # ------------------------------------- Read an entry from a user's environment
                   2474: 
                   2475: sub userenvironment {
                   2476:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2477:     my $items;
                   2478:     foreach my $item (@what) {
                   2479:         $items.=&escape($item).'&';
                   2480:     }
                   2481:     $items=~s/\&$//;
1.70      www      2482:     my %returnhash=();
1.1009    raeburn  2483:     my $uhome = &homeserver($unam,$udom);
                   2484:     unless ($uhome eq 'no_host') {
                   2485:         my @answer=split(/\&/, 
                   2486:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2487:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2488:             return %returnhash;
                   2489:         }
1.1009    raeburn  2490:         my $i;
                   2491:         for ($i=0;$i<=$#what;$i++) {
                   2492: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2493:         }
1.70      www      2494:     }
                   2495:     return %returnhash;
1.1       albertel 2496: }
                   2497: 
1.617     albertel 2498: # ---------------------------------------------------------- Get a studentphoto
                   2499: sub studentphoto {
                   2500:     my ($udom,$unam,$ext) = @_;
                   2501:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2502:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2503:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2504:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2505:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2506:             } else {
                   2507:                 my ($result,$perm_reqd)=
1.707     albertel 2508: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2509:                 if ($result eq 'ok') {
                   2510:                     if (!($perm_reqd eq 'yes')) {
                   2511:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2512:                     }
                   2513:                 }
                   2514:             }
                   2515:         }
                   2516:     } else {
                   2517:         my ($result,$perm_reqd) = 
1.707     albertel 2518: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2519:         if ($result eq 'ok') {
                   2520:             if (!($perm_reqd eq 'yes')) {
                   2521:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2522:             }
                   2523:         }
                   2524:     }
                   2525:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2526: }
                   2527: 
                   2528: sub retrievestudentphoto {
                   2529:     my ($udom,$unam,$ext,$type) = @_;
                   2530:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2531:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2532:     if ($ret eq 'ok') {
                   2533:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2534:         if ($type eq 'thumbnail') {
                   2535:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2536:         }
                   2537:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2538:         return $tokenurl;
                   2539:     } else {
                   2540:         if ($type eq 'thumbnail') {
                   2541:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2542:         } else { 
                   2543:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2544:         }
1.617     albertel 2545:     }
                   2546: }
                   2547: 
1.263     www      2548: # -------------------------------------------------------------------- New chat
                   2549: 
                   2550: sub chatsend {
1.724     raeburn  2551:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2552:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2553:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2554:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2555:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2556: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2557: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2558: }
                   2559: 
                   2560: # ------------------------------------------ Find current version of a resource
                   2561: 
                   2562: sub getversion {
                   2563:     my $fname=&clutter(shift);
1.1189    raeburn  2564:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2565:     return &currentversion(&filelocation('',$fname));
                   2566: }
                   2567: 
                   2568: sub currentversion {
                   2569:     my $fname=shift;
                   2570:     my $author=$fname;
                   2571:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2572:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2573:     my $home=&homeserver($uname,$udom);
1.292     www      2574:     if ($home eq 'no_host') { 
                   2575:         return -1; 
                   2576:     }
1.1112    www      2577:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2578:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2579: 	return -1;
                   2580:     }
1.1112    www      2581:     return $answer;
1.263     www      2582: }
                   2583: 
1.1111    www      2584: #
                   2585: # Return special version number of resource if set by override, empty otherwise
                   2586: #
                   2587: sub usedversion {
                   2588:     my $fname=shift;
                   2589:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2590:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2591:     if ($urlversion) { return $urlversion; }
                   2592:     return '';
                   2593: }
                   2594: 
1.1       albertel 2595: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2596: 
1.1       albertel 2597: sub subscribe {
                   2598:     my $fname=shift;
1.761     raeburn  2599:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2600:     $fname=~s/[\n\r]//g;
1.1       albertel 2601:     my $author=$fname;
                   2602:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2603:     my ($udom,$uname)=split(/\//,$author);
                   2604:     my $home=homeserver($uname,$udom);
1.335     albertel 2605:     if ($home eq 'no_host') {
                   2606:         return 'not_found';
1.1       albertel 2607:     }
                   2608:     my $answer=reply("sub:$fname",$home);
1.64      www      2609:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2610: 	$answer.=' by '.$home;
                   2611:     }
1.1       albertel 2612:     return $answer;
                   2613: }
                   2614:     
1.8       www      2615: # -------------------------------------------------------------- Replicate file
                   2616: 
                   2617: sub repcopy {
                   2618:     my $filename=shift;
1.23      www      2619:     $filename=~s/\/+/\//g;
1.1142    raeburn  2620:     my $londocroot = $perlvar{'lonDocRoot'};
                   2621:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2622:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2623:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2624: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2625: 	return &repcopy_userfile($filename);
                   2626:     }
1.532     albertel 2627:     $filename=~s/[\n\r]//g;
1.8       www      2628:     my $transname="$filename.in.transfer";
1.828     www      2629: # FIXME: this should flock
1.607     raeburn  2630:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2631:     my $remoteurl=subscribe($filename);
1.64      www      2632:     if ($remoteurl =~ /^con_lost by/) {
                   2633: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2634:            return 'unavailable';
1.8       www      2635:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2636: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2637: 	   return 'not_found';
1.64      www      2638:     } elsif ($remoteurl =~ /^rejected by/) {
                   2639: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2640:            return 'forbidden';
1.20      www      2641:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2642:            return 'ok';
1.8       www      2643:     } else {
1.290     www      2644:         my $author=$filename;
                   2645:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2646:         my ($udom,$uname)=split(/\//,$author);
                   2647:         my $home=homeserver($uname,$udom);
                   2648:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2649:            my @parts=split(/\//,$filename);
                   2650:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2651:            if ($path ne "$londocroot/res") {
1.8       www      2652:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2653: 	       return 'bad_request';
1.8       www      2654:            }
                   2655:            my $count;
                   2656:            for ($count=5;$count<$#parts;$count++) {
                   2657:                $path.="/$parts[$count]";
                   2658:                if ((-e $path)!=1) {
                   2659: 		   mkdir($path,0777);
                   2660:                }
                   2661:            }
                   2662:            my $ua=new LWP::UserAgent;
                   2663:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2664:            my $response=$ua->request($request,$transname);
                   2665:            if ($response->is_error()) {
                   2666: 	       unlink($transname);
                   2667:                my $message=$response->status_line;
1.672     albertel 2668:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2669:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2670:                return 'unavailable';
1.8       www      2671:            } else {
1.16      www      2672: 	       if ($remoteurl!~/\.meta$/) {
                   2673:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2674:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2675:                   if ($mresponse->is_error()) {
                   2676: 		      unlink($filename.'.meta');
                   2677:                       &logthis(
1.672     albertel 2678:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2679:                   }
                   2680: 	       }
1.8       www      2681:                rename($transname,$filename);
1.607     raeburn  2682:                return 'ok';
1.8       www      2683:            }
1.290     www      2684:        }
1.8       www      2685:     }
1.330     www      2686: }
                   2687: 
                   2688: # ------------------------------------------------ Get server side include body
                   2689: sub ssi_body {
1.381     albertel 2690:     my ($filelink,%form)=@_;
1.606     matthew  2691:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2692:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2693:     }
1.953     www      2694:     my $output='';
                   2695:     my $response;
1.980     raeburn  2696:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2697:        ($output,$response)=&externalssi($filelink);
1.953     www      2698:     } else {
1.1004    droeschl 2699:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2700:        $filelink .= 'inhibitmenu=yes';
1.953     www      2701:        ($output,$response)=&ssi($filelink,%form);
                   2702:     }
1.778     albertel 2703:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2704:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2705:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2706:     if (wantarray) {
                   2707:         return ($output, $response);
                   2708:     } else {
                   2709:         return $output;
                   2710:     }
1.8       www      2711: }
                   2712: 
1.15      www      2713: # --------------------------------------------------------- Server Side Include
                   2714: 
1.782     albertel 2715: sub absolute_url {
                   2716:     my ($host_name) = @_;
                   2717:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2718:     if ($host_name eq '') {
                   2719: 	$host_name = $ENV{'SERVER_NAME'};
                   2720:     }
                   2721:     return $protocol.$host_name;
                   2722: }
                   2723: 
1.942     foxr     2724: #
                   2725: #   Server side include.
                   2726: # Parameters:
                   2727: #  fn     Possibly encrypted resource name/id.
                   2728: #  form   Hash that describes how the rendering should be done
                   2729: #         and other things.
1.944     foxr     2730: # Returns:
1.950     raeburn  2731: #   Scalar context: The content of the response.
                   2732: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2733: #     
1.15      www      2734: sub ssi {
                   2735: 
1.944     foxr     2736:     my ($fn,%form)=@_;
1.15      www      2737:     my $ua=new LWP::UserAgent;
1.23      www      2738:     my $request;
1.711     albertel 2739: 
                   2740:     $form{'no_update_last_known'}=1;
1.895     albertel 2741:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2742:     if (%form) {
1.782     albertel 2743:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2744:       $request->content(join('&',map { 
                   2745:             my $name = escape($_);
                   2746:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2747:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2748:             : &escape($form{$_}) );    
                   2749:         } keys(%form)));
1.23      www      2750:     } else {
1.782     albertel 2751:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2752:     }
                   2753: 
1.15      www      2754:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2755:     my $response= $ua->request($request);
1.1182    foxr     2756:     my $content = $response->content;
                   2757: 
                   2758: 
1.944     foxr     2759:     if (wantarray) {
1.1173    foxr     2760: 	return ($content, $response);
1.944     foxr     2761:     } else {
1.1173    foxr     2762: 	return $content;
1.942     foxr     2763:     }
1.324     www      2764: }
                   2765: 
                   2766: sub externalssi {
                   2767:     my ($url)=@_;
                   2768:     my $ua=new LWP::UserAgent;
                   2769:     my $request=new HTTP::Request('GET',$url);
                   2770:     my $response=$ua->request($request);
1.954     raeburn  2771:     if (wantarray) {
                   2772:         return ($response->content, $response);
                   2773:     } else {
                   2774:         return $response->content;
                   2775:     }
1.15      www      2776: }
1.254     www      2777: 
1.492     albertel 2778: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2779: 
                   2780: sub allowuploaded {
                   2781:     my ($srcurl,$url)=@_;
                   2782:     $url=&clutter(&declutter($url));
                   2783:     my $dir=$url;
                   2784:     $dir=~s/\/[^\/]+$//;
                   2785:     my %httpref=();
                   2786:     my $httpurl=&hreflocation('',$url);
                   2787:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2788:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2789: }
1.477     raeburn  2790: 
1.1193    raeburn  2791: #
                   2792: # Determine if the current user should be able to edit a particular resource,
                   2793: # when viewing in course context.
                   2794: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2795: #     Functions.
                   2796: # (b) When displaying folder contents in course editor, used to determine if
                   2797: #     "Edit" link will be displayed alongside resource.
                   2798: #
1.1196    raeburn  2799: #  input: six args -- filename (decluttered), course number, course domain,
                   2800: #                   url, symb (if registered) and group (if this is a group
                   2801: #                   item -- e.g., bulletin board, group page etc.).
                   2802: #  output: array of five scalars -- 
1.1193    raeburn  2803: #          $cfile -- url for file editing if editable on current server
                   2804: #          $home -- homeserver of resource (i.e., for author if published,
                   2805: #                                           or course if uploaded.).
                   2806: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2807: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2808: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2809: #
                   2810: 
                   2811: sub can_edit_resource {
1.1194    raeburn  2812:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2813:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2814: #
                   2815: # For aboutme pages user can only edit his/her own.
                   2816: #
1.1199    raeburn  2817:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2818:         my ($sdom,$sname) = ($1,$2);
                   2819:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2820:             $home = $env{'user.home'};
                   2821:             $cfile = $resurl;
                   2822:             if ($env{'form.forceedit'}) {
                   2823:                 $forceview = 1;
                   2824:             } else {
                   2825:                 $forceedit = 1;
                   2826:             }
                   2827:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2828:         } else {
                   2829:             return;
                   2830:         }
                   2831:     }
                   2832: 
                   2833:     if ($env{'request.course.id'}) {
                   2834:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2835:         if ($group ne '') {
                   2836: # if this is a group homepage or group bulletin board, check group privs
                   2837:             my $allowed = 0;
1.1197    raeburn  2838:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2839:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2840:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2841:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2842:                     $allowed = 1;
                   2843:                 }
1.1197    raeburn  2844:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2845:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2846:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2847:                     $allowed = 1;
                   2848:                 }
                   2849:             }
                   2850:             if ($allowed) {
                   2851:                 $home=&homeserver($cnum,$cdom);
                   2852:                 if ($env{'form.forceedit'}) {
                   2853:                     $forceview = 1;
                   2854:                 } else {
                   2855:                     $forceedit = 1;
                   2856:                 }
                   2857:                 $cfile = $resurl;
                   2858:             } else {
                   2859:                 return;
                   2860:             }
                   2861:         } else {
1.1208    raeburn  2862:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2863:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2864:                     return;
                   2865:                 }
                   2866:             } elsif (!$crsedit) {
1.1194    raeburn  2867: #
                   2868: # No edit allowed where CC has switched to student role.
                   2869: #
                   2870:                 return;
                   2871:             }
                   2872:         }
                   2873:     }
                   2874: 
1.1193    raeburn  2875:     if ($file ne '') {
                   2876:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2877:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2878:                 $uploaded = 1;
                   2879:                 $incourse = 1;
1.1193    raeburn  2880:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2881:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2882:                     if ($env{'form.forceedit'}) {
                   2883:                         $forceview = 1;
                   2884:                     } else {
                   2885:                         $forceedit = 1;
                   2886:                     }
1.1194    raeburn  2887:                 }
                   2888:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2889:                 $incourse = 1;
                   2890:                 if ($env{'form.forceedit'}) {
                   2891:                     $forceview = 1;
                   2892:                 } else {
                   2893:                     $forceedit = 1;
                   2894:                 }
                   2895:                 $cfile = $resurl;
                   2896:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2897:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2898:                     $incourse = 1;
                   2899:                     if ($env{'form.forceedit'}) {
                   2900:                         $forceview = 1;
                   2901:                     } else {
                   2902:                         $forceedit = 1;
                   2903:                     }
                   2904:                     $cfile = $resurl;
1.1199    raeburn  2905:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2906:                     $incourse = 1;
                   2907:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2908:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2909:                     $incourse = 1;
1.1199    raeburn  2910:                     if ($env{'form.forceedit'}) {
                   2911:                         $forceview = 1;
                   2912:                     } else {
                   2913:                         $forceedit = 1;
                   2914:                     }
                   2915:                     $cfile = $resurl;
1.1208    raeburn  2916:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2917:                     $incourse = 1;
                   2918:                     if ($env{'form.forceedit'}) {
                   2919:                         $forceview = 1;
                   2920:                     } else {
                   2921:                         $forceedit = 1;
                   2922:                     }
                   2923:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2924:                 }
                   2925:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2926:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2927:                 if (&is_on_map($template)) { 
                   2928:                     $incourse = 1;
                   2929:                     $forceview = 1;
                   2930:                     $cfile = $template;
1.1193    raeburn  2931:                 }
1.1199    raeburn  2932:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2933:                     $incourse = 1;
                   2934:                     if ($env{'form.forceedit'}) {
                   2935:                         $forceview = 1;
                   2936:                     } else {
                   2937:                         $forceedit = 1;
                   2938:                     }
                   2939:                     $cfile = $resurl;
                   2940:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2941:                 $incourse = 1;
                   2942:                 $forceview = 1;
                   2943:                 if ($symb) {
                   2944:                     my ($map,$id,$res)=&decode_symb($symb);
                   2945:                     $env{'request.symb'} = $symb;
                   2946:                     $cfile = &clutter($res);
                   2947:                 } else {
                   2948:                     $cfile = $env{'form.suppurl'};
                   2949:                     $cfile =~ s{^http://}{};
                   2950:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2951:                 }
1.1234    raeburn  2952:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2953:                 if ($env{'form.forceedit'}) {
                   2954:                     $forceview = 1;
                   2955:                 } else {
                   2956:                     $forceedit = 1;
                   2957:                 }
                   2958:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  2959:             }
                   2960:         }
1.1194    raeburn  2961:         if ($uploaded || $incourse) {
                   2962:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2963:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2964:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2965:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2966:             # Check that the user has permission to edit this resource
                   2967:             my $setpriv = 1;
                   2968:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2969:             if (defined($cfudom)) {
                   2970:                 $home=&homeserver($cfuname,$cfudom);
                   2971:                 $cfile=$file;
                   2972:             }
                   2973:         }
1.1194    raeburn  2974:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2975:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2976:             my @ids=&current_machine_ids();
                   2977:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2978:                 $switchserver=1;
                   2979:             }
                   2980:         }
                   2981:     }
1.1194    raeburn  2982:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2983: }
                   2984: 
                   2985: sub is_course_upload {
                   2986:     my ($file,$cnum,$cdom) = @_;
                   2987:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2988:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2989:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2990:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2991:         return 1;
                   2992:     }
                   2993:     return;
                   2994: }
                   2995: 
1.1194    raeburn  2996: sub in_course {
1.1195    raeburn  2997:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2998:     if ($hideprivileged) {
                   2999:         my $skipuser;
1.1219    raeburn  3000:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3001:         my @possdoms = ($cdom);  
                   3002:         if ($coursehash{'checkforpriv'}) { 
                   3003:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3004:         }
                   3005:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3006:             $skipuser = 1;
                   3007:             if ($coursehash{'nothideprivileged'}) {
                   3008:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3009:                     my $user;
                   3010:                     if ($item =~ /:/) {
                   3011:                         $user = $item;
                   3012:                     } else {
                   3013:                         $user = join(':',split(/[\@]/,$item));
                   3014:                     }
                   3015:                     if ($user eq $uname.':'.$udom) {
                   3016:                         undef($skipuser);
                   3017:                         last;
                   3018:                     }
                   3019:                 }
                   3020:             }
                   3021:             if ($skipuser) {
                   3022:                 return 0;
                   3023:             }
                   3024:         }
                   3025:     }
1.1194    raeburn  3026:     $type ||= 'any';
                   3027:     if (!defined($cdom) || !defined($cnum)) {
                   3028:         my $cid  = $env{'request.course.id'};
                   3029:         $cdom = $env{'course.'.$cid.'.domain'};
                   3030:         $cnum = $env{'course.'.$cid.'.num'};
                   3031:     }
                   3032:     my $typesref;
1.1195    raeburn  3033:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3034:         $typesref = ['active','previous','future'];
                   3035:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3036:         $typesref = [$type];
                   3037:     }
                   3038:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3039:                               $typesref,undef,[$cdom]);
                   3040:     my ($tmp) = keys(%roles);
                   3041:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3042:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3043:     if (@course_roles > 0) {
                   3044:         return 1;
                   3045:     }
                   3046:     return 0;
                   3047: }
                   3048: 
1.478     albertel 3049: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3050: # input: action, courseID, current domain, intended
1.637     raeburn  3051: #        path to file, source of file, instruction to parse file for objects,
                   3052: #        ref to hash for embedded objects,
                   3053: #        ref to hash for codebase of java objects.
1.1095    raeburn  3054: #        reference to scalar to accommodate mime type determined
                   3055: #          from File::MMagic if $parser = parse.
1.637     raeburn  3056: #
1.485     raeburn  3057: # output: url to file (if action was uploaddoc), 
                   3058: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3059: #
1.478     albertel 3060: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3061: # course.
1.477     raeburn  3062: #
1.478     albertel 3063: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3064: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3065: #          course's home server.
1.477     raeburn  3066: #
1.478     albertel 3067: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3068: #          be copied from $source (current location) to 
                   3069: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3070: #         and will then be copied to
                   3071: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3072: #         course's home server.
1.485     raeburn  3073: #
1.481     raeburn  3074: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3075: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3076: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3077: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3078: #         in course's home server.
1.637     raeburn  3079: #
1.477     raeburn  3080: 
                   3081: sub process_coursefile {
1.1095    raeburn  3082:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3083:         $mimetype)=@_;
1.477     raeburn  3084:     my $fetchresult;
1.638     albertel 3085:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3086:     if ($action eq 'propagate') {
1.638     albertel 3087:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3088: 			     $home);
1.481     raeburn  3089:     } else {
1.477     raeburn  3090:         my $fpath = '';
                   3091:         my $fname = $file;
1.478     albertel 3092:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3093:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3094:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3095:         if ($action eq 'copy') {
                   3096:             if ($source eq '') {
                   3097:                 $fetchresult = 'no source file';
                   3098:                 return $fetchresult;
                   3099:             } else {
                   3100:                 my $destination = $filepath.'/'.$fname;
                   3101:                 rename($source,$destination);
                   3102:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3103:                                  $home);
1.481     raeburn  3104:             }
                   3105:         } elsif ($action eq 'uploaddoc') {
                   3106:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3107:             print $fh $env{'form.'.$source};
1.481     raeburn  3108:             close($fh);
1.637     raeburn  3109:             if ($parser eq 'parse') {
1.1024    raeburn  3110:                 my $mm = new File::MMagic;
1.1095    raeburn  3111:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3112:                 if ($type eq 'text/html') {
1.1024    raeburn  3113:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3114:                     unless ($parse_result eq 'ok') {
                   3115:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3116:                     }
1.637     raeburn  3117:                 }
1.1095    raeburn  3118:                 if (ref($mimetype)) {
                   3119:                     $$mimetype = $type;
                   3120:                 } 
1.637     raeburn  3121:             }
1.477     raeburn  3122:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3123:                                  $home);
1.481     raeburn  3124:             if ($fetchresult eq 'ok') {
                   3125:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3126:             } else {
                   3127:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3128:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3129:                 return '/adm/notfound.html';
                   3130:             }
1.477     raeburn  3131:         }
                   3132:     }
1.485     raeburn  3133:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3134:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3135:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3136:     }
                   3137:     return $fetchresult;
                   3138: }
                   3139: 
1.637     raeburn  3140: sub build_filepath {
                   3141:     my ($fpath) = @_;
                   3142:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3143:     unless ($fpath eq '') {
                   3144:         my @parts=split('/',$fpath);
                   3145:         foreach my $part (@parts) {
                   3146:             $filepath.= '/'.$part;
                   3147:             if ((-e $filepath)!=1) {
                   3148:                 mkdir($filepath,0777);
                   3149:             }
                   3150:         }
                   3151:     }
                   3152:     return $filepath;
                   3153: }
                   3154: 
                   3155: sub store_edited_file {
1.638     albertel 3156:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3157:     my $file = $primary_url;
                   3158:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3159:     my $fpath = '';
                   3160:     my $fname = $file;
                   3161:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3162:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3163:     my $filepath = &build_filepath($fpath);
                   3164:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3165:     print $fh $content;
                   3166:     close($fh);
1.638     albertel 3167:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3168:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3169: 			  $home);
1.637     raeburn  3170:     if ($$fetchresult eq 'ok') {
                   3171:         return '/uploaded/'.$fpath.'/'.$fname;
                   3172:     } else {
1.638     albertel 3173:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3174: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3175:         return '/adm/notfound.html';
                   3176:     }
                   3177: }
                   3178: 
1.531     albertel 3179: sub clean_filename {
1.831     albertel 3180:     my ($fname,$args)=@_;
1.315     www      3181: # Replace Windows backslashes by forward slashes
1.257     www      3182:     $fname=~s/\\/\//g;
1.831     albertel 3183:     if (!$args->{'keep_path'}) {
                   3184:         # Get rid of everything but the actual filename
                   3185: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3186:     }
1.315     www      3187: # Replace spaces by underscores
                   3188:     $fname=~s/\s+/\_/g;
                   3189: # Replace all other weird characters by nothing
1.831     albertel 3190:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3191: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3192: # numbers
                   3193:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3194:     return $fname;
                   3195: }
1.1051    raeburn  3196: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3197: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3198: # image with the same aspect ratio as the original, but with dimensions which do 
                   3199: # not exceed $resizewidth and $resizeheight.
                   3200:  
1.984     neumanie 3201: sub resizeImage {
1.1051    raeburn  3202:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3203:     my $ima = Image::Magick->new;
                   3204:     my $resized;
                   3205:     if (-e $img_path) {
                   3206:         $ima->Read($img_path);
                   3207:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3208:             my $width = $ima->Get('width');
                   3209:             my $height = $ima->Get('height');
                   3210:             if ($width > $resizewidth) {
                   3211: 	        my $factor = $width/$resizewidth;
                   3212:                 my $newheight = $height/$factor;
                   3213:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3214:                 $resized = 1;
                   3215:             }
                   3216:         }
                   3217:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3218:             my $width = $ima->Get('width');
                   3219:             my $height = $ima->Get('height');
                   3220:             if ($height > $resizeheight) {
                   3221:                 my $factor = $height/$resizeheight;
                   3222:                 my $newwidth = $width/$factor;
                   3223:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3224:                 $resized = 1;
                   3225:             }
                   3226:         }
                   3227:         if ($resized) {
                   3228:             $ima->Write($img_path);
                   3229:         }
                   3230:     }
                   3231:     return;
1.977     amueller 3232: }
                   3233: 
1.608     albertel 3234: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3235: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3236: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3237: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3238: #                                    canceloverwrite, or ''. 
                   3239: #                   if 'coursedoc': upload to the current course
                   3240: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3241: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3242: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3243: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3244: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3245: #        $allfiles - reference to hash for embedded objects
                   3246: #        $codebase - reference to hash for codebase of java objects
                   3247: #        $desuname - username for permanent storage of uploaded file
                   3248: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3249: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3250: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3251: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3252: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3253: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3254: #                    from File::MMagic.
1.858     raeburn  3255: # 
1.686     albertel 3256: # output: url of file in userspace, or error: <message> 
                   3257: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3258: 
1.531     albertel 3259: sub userfileupload {
1.1090    raeburn  3260:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3261:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3262:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3263:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3264:     $fname=&clean_filename($fname);
1.1090    raeburn  3265:     # See if there is anything left
1.257     www      3266:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3267:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3268:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3269:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3270:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3271:         my $now = time;
1.1090    raeburn  3272:         my $filepath;
1.1095    raeburn  3273:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3274:              $filepath = 'tmp/helprequests/'.$now;
                   3275:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3276:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3277:                          '_'.$env{'user.domain'}.'/pending';
                   3278:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3279:             my ($docuname,$docudom);
                   3280:             if ($destudom) {
                   3281:                 $docudom = $destudom;
                   3282:             } else {
                   3283:                 $docudom = $env{'user.domain'};
                   3284:             }
                   3285:             if ($destuname) {
                   3286:                 $docuname = $destuname;
                   3287:             } else {
                   3288:                 $docuname = $env{'user.name'};
                   3289:             }
                   3290:             if (exists($env{'form.group'})) {
                   3291:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3292:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3293:             }
                   3294:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3295:             if ($context eq 'canceloverwrite') {
                   3296:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3297:                 if (-e  $tempfile) {
                   3298:                     my @info = stat($tempfile);
                   3299:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3300:                         unlink($tempfile);
                   3301:                     }
                   3302:                 }
                   3303:                 return;
1.523     raeburn  3304:             }
                   3305:         }
1.1090    raeburn  3306:         # Create the directory if not present
1.741     raeburn  3307:         my @parts=split(/\//,$filepath);
                   3308:         my $fullpath = $perlvar{'lonDaemons'};
                   3309:         for (my $i=0;$i<@parts;$i++) {
                   3310:             $fullpath .= '/'.$parts[$i];
                   3311:             if ((-e $fullpath)!=1) {
                   3312:                 mkdir($fullpath,0777);
                   3313:             }
                   3314:         }
                   3315:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3316:         print $fh $env{'form.'.$formname};
                   3317:         close($fh);
1.1090    raeburn  3318:         if ($context eq 'existingfile') {
                   3319:             my @info = stat($fullpath.'/'.$fname);
                   3320:             return ($fullpath.'/'.$fname,$info[9]);
                   3321:         } else {
                   3322:             return $fullpath.'/'.$fname;
                   3323:         }
1.523     raeburn  3324:     }
1.995     raeburn  3325:     if ($subdir eq 'scantron') {
                   3326:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3327:     } else {
1.995     raeburn  3328:         $fname="$subdir/$fname";
                   3329:     }
1.1090    raeburn  3330:     if ($context eq 'coursedoc') {
1.638     albertel 3331: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3332: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3333:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3334:             return &finishuserfileupload($docuname,$docudom,
                   3335: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3336: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3337:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3338:         } else {
1.1218    raeburn  3339:             if ($env{'form.folder'}) {
                   3340:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3341:             }
1.638     albertel 3342:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3343: 				       $fname,$formname,$parser,
1.1095    raeburn  3344: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3345:         }
1.719     banghart 3346:     } elsif (defined($destuname)) {
                   3347:         my $docuname=$destuname;
                   3348:         my $docudom=$destudom;
1.860     raeburn  3349: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3350: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3351:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3352:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3353:     } else {
1.638     albertel 3354:         my $docuname=$env{'user.name'};
                   3355:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3356:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3357:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3358:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3359:         }
1.860     raeburn  3360: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3361: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3362:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3363:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3364:     }
1.271     www      3365: }
                   3366: 
                   3367: sub finishuserfileupload {
1.860     raeburn  3368:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3369:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3370:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3371:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3372:   
1.860     raeburn  3373:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3374:     $file=$fname;
                   3375:     if ($fname=~m|/|) {
                   3376:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3377: 	$path.=$fnamepath.'/';
                   3378:     }
1.259     www      3379:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3380:     my $count;
                   3381:     for ($count=4;$count<=$#parts;$count++) {
                   3382:         $filepath.="/$parts[$count]";
                   3383:         if ((-e $filepath)!=1) {
                   3384: 	    mkdir($filepath,0777);
                   3385:         }
                   3386:     }
1.984     neumanie 3387: 
1.258     www      3388: # Save the file
                   3389:     {
1.701     albertel 3390: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3391: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3392: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3393: 	    return '/adm/notfound.html';
                   3394: 	}
1.1090    raeburn  3395:         if ($context eq 'overwrite') {
1.1117    foxr     3396:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3397:             my $target = $filepath.'/'.$file;
                   3398:             if (-e $source) {
                   3399:                 my @info = stat($source);
                   3400:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3401:                     unless (&File::Copy::move($source,$target)) {
                   3402:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3403:                         return "Moving from $source failed";
                   3404:                     }
                   3405:                 } else {
                   3406:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3407:                 }
                   3408:             } else {
                   3409:                 return "Temporary file: $source missing";
                   3410:             }
                   3411:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3412: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3413: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3414: 	    return '/adm/notfound.html';
                   3415: 	}
1.570     albertel 3416: 	close(FH);
1.1051    raeburn  3417:         if ($resizewidth && $resizeheight) {
                   3418:             my $mm = new File::MMagic;
                   3419:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3420:             if ($mime_type =~ m{^image/}) {
                   3421: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3422:             }  
1.977     amueller 3423: 	}
1.258     www      3424:     }
1.1152    raeburn  3425:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3426:         if (ref($mimetype)) {
                   3427:             if ($$mimetype eq '') {
                   3428:                 my $mm = new File::MMagic;
                   3429:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3430:                 $$mimetype = $type;
                   3431:             }
                   3432:         }
                   3433:     }
1.637     raeburn  3434:     if ($parser eq 'parse') {
1.1152    raeburn  3435:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3436:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3437:                                                        $allfiles,$codebase);
                   3438:             unless ($parse_result eq 'ok') {
                   3439:                 &logthis('Failed to parse '.$filepath.$file.
                   3440: 	   	         ' for embedded media: '.$parse_result); 
                   3441:             }
1.637     raeburn  3442:         }
                   3443:     }
1.860     raeburn  3444:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3445:         my $input = $filepath.'/'.$file;
                   3446:         my $output = $filepath.'/'.'tn-'.$file;
                   3447:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3448:         system("convert -sample $thumbsize $input $output");
                   3449:         if (-e $filepath.'/'.'tn-'.$file) {
                   3450:             $fetchthumb  = 1; 
                   3451:         }
                   3452:     }
1.858     raeburn  3453:  
1.259     www      3454: # Notify homeserver to grep it
                   3455: #
1.984     neumanie 3456:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3457:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3458:     if ($fetchresult eq 'ok') {
1.860     raeburn  3459:         if ($fetchthumb) {
                   3460:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3461:             if ($thumbresult ne 'ok') {
                   3462:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3463:                          $docuhome.': '.$thumbresult);
                   3464:             }
                   3465:         }
1.259     www      3466: #
1.258     www      3467: # Return the URL to it
1.494     albertel 3468:         return '/uploaded/'.$path.$file;
1.263     www      3469:     } else {
1.494     albertel 3470:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3471: 		 ': '.$fetchresult);
1.263     www      3472:         return '/adm/notfound.html';
1.858     raeburn  3473:     }
1.493     albertel 3474: }
                   3475: 
1.637     raeburn  3476: sub extract_embedded_items {
1.961     raeburn  3477:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3478:     my @state = ();
1.1164    raeburn  3479:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3480:     my %javafiles = (
                   3481:                       codebase => '',
                   3482:                       code => '',
                   3483:                       archive => ''
                   3484:                     );
                   3485:     my %mediafiles = (
                   3486:                       src => '',
                   3487:                       movie => '',
                   3488:                      );
1.648     raeburn  3489:     my $p;
                   3490:     if ($content) {
                   3491:         $p = HTML::LCParser->new($content);
                   3492:     } else {
1.961     raeburn  3493:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3494:     }
1.641     albertel 3495:     while (my $t=$p->get_token()) {
1.640     albertel 3496: 	if ($t->[0] eq 'S') {
                   3497: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3498: 	    push(@state, $tagname);
1.648     raeburn  3499:             if (lc($tagname) eq 'allow') {
                   3500:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3501:             }
1.640     albertel 3502: 	    if (lc($tagname) eq 'img') {
                   3503: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3504: 	    }
1.886     albertel 3505: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3506:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3507:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3508:                 }
1.886     albertel 3509: 	    }
1.645     raeburn  3510:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3511:                 my $src;
1.645     raeburn  3512:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3513:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3514:                 } else {
1.1164    raeburn  3515:                     if ($attr->{'src'} ne '') {
                   3516:                         $src = $attr->{'src'};
                   3517:                         &add_filetype($allfiles,$src,'src');
                   3518:                     }
                   3519:                 }
                   3520:                 my $text = $p->get_trimmed_text();
                   3521:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3522:                     my @swfargs = split(/,/,$1);
                   3523:                     foreach my $item (@swfargs) {
                   3524:                         $item =~ s/["']//g;
                   3525:                         $item =~ s/^\s+//;
                   3526:                         $item =~ s/\s+$//;
                   3527:                     }
                   3528:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3529:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3530:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3531:                         } else {
                   3532:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3533:                         }
                   3534:                     }
1.645     raeburn  3535:                 }
                   3536:             }
                   3537:             if (lc($tagname) eq 'link') {
                   3538:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3539:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3540:                 }
                   3541:             }
1.640     albertel 3542: 	    if (lc($tagname) eq 'object' ||
                   3543: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3544: 		foreach my $item (keys(%javafiles)) {
                   3545: 		    $javafiles{$item} = '';
                   3546: 		}
1.1164    raeburn  3547:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3548:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3549:                 }
1.640     albertel 3550: 	    }
                   3551: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3552: 		my $name = lc($attr->{'name'});
                   3553: 		foreach my $item (keys(%javafiles)) {
                   3554: 		    if ($name eq $item) {
                   3555: 			$javafiles{$item} = $attr->{'value'};
                   3556: 			last;
                   3557: 		    }
                   3558: 		}
1.1164    raeburn  3559:                 my $pathfrom;
1.640     albertel 3560: 		foreach my $item (keys(%mediafiles)) {
                   3561: 		    if ($name eq $item) {
1.1164    raeburn  3562:                         $pathfrom = $attr->{'value'};
                   3563:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3564: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3565: 			last;
                   3566: 		    }
                   3567: 		}
1.1164    raeburn  3568:                 if ($name eq 'flashvars') {
                   3569:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3570:                 }
                   3571:                 if ($pathfrom ne '') {
                   3572:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3573:                                          $pathfrom);
                   3574:                 }
1.640     albertel 3575: 	    }
                   3576: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3577: 		foreach my $item (keys(%javafiles)) {
                   3578: 		    if ($attr->{$item}) {
                   3579: 			$javafiles{$item} = $attr->{$item};
                   3580: 			last;
                   3581: 		    }
                   3582: 		}
                   3583: 		foreach my $item (keys(%mediafiles)) {
                   3584: 		    if ($attr->{$item}) {
                   3585: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3586: 			last;
                   3587: 		    }
                   3588: 		}
1.1164    raeburn  3589:                 if (lc($tagname) eq 'embed') {
                   3590:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3591:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3592:                                              $attr->{'src'});
                   3593:                     }
                   3594:                 }
1.640     albertel 3595: 	    }
1.1243    raeburn  3596:             if (lc($tagname) eq 'iframe') {
                   3597:                 my $src = $attr->{'src'} ;
                   3598:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3599:                     &add_filetype($allfiles,$src,'src');
                   3600:                 } elsif ($src =~ m{^/}) {
                   3601:                     if ($env{'request.course.id'}) {
                   3602:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3603:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3604:                         my $url = &hreflocation('',$fullpath);
                   3605:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3606:                             my $relpath = $1;
                   3607:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3608:                                 &add_filetype($allfiles,$1,'src');
                   3609:                             }
                   3610:                         }
                   3611:                     }
                   3612:                 }
                   3613:             }
1.1164    raeburn  3614:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3615:                 pop(@state);
1.1164    raeburn  3616:             }
1.640     albertel 3617: 	} elsif ($t->[0] eq 'E') {
                   3618: 	    my ($tagname) = ($t->[1]);
                   3619: 	    if ($javafiles{'codebase'} ne '') {
                   3620: 		$javafiles{'codebase'} .= '/';
                   3621: 	    }  
                   3622: 	    if (lc($tagname) eq 'applet' ||
                   3623: 		lc($tagname) eq 'object' ||
                   3624: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3625: 		) {
                   3626: 		foreach my $item (keys(%javafiles)) {
                   3627: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3628: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3629: 			&add_filetype($allfiles,$file,$item);
                   3630: 		    }
                   3631: 		}
                   3632: 	    } 
                   3633: 	    pop @state;
                   3634: 	}
                   3635:     }
1.1164    raeburn  3636:     foreach my $id (sort(keys(%flashvars))) {
                   3637:         if ($shockwave{$id} ne '') {
                   3638:             my @pairs = split(/\&/,$flashvars{$id});
                   3639:             foreach my $pair (@pairs) {
                   3640:                 my ($key,$value) = split(/\=/,$pair);
                   3641:                 if ($key eq 'thumb') {
                   3642:                     &add_filetype($allfiles,$value,$key);
                   3643:                 } elsif ($key eq 'content') {
                   3644:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3645:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3646:                     if ($ext ne '') {
                   3647:                         &add_filetype($allfiles,$path.$value,$ext);
                   3648:                     }
                   3649:                 }
                   3650:             }
                   3651:         }
                   3652:     }
1.637     raeburn  3653:     return 'ok';
                   3654: }
                   3655: 
1.639     albertel 3656: sub add_filetype {
                   3657:     my ($allfiles,$file,$type)=@_;
                   3658:     if (exists($allfiles->{$file})) {
                   3659: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3660: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3661: 	}
                   3662:     } else {
                   3663: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3664:     }
                   3665: }
                   3666: 
1.1164    raeburn  3667: sub embedded_dependency {
                   3668:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3669:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3670:         if (($identifier ne '') &&
                   3671:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3672:             ($pathfrom ne '')) {
                   3673:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3674:             foreach my $dep (@{$related->{$identifier}}) {
                   3675:                 &add_filetype($allfiles,$path.$dep,'object');
                   3676:             }
                   3677:         }
                   3678:     }
                   3679:     return;
                   3680: }
                   3681: 
1.493     albertel 3682: sub removeuploadedurl {
1.984     neumanie 3683:     my ($url)=@_;	
                   3684:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3685:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3686: }
                   3687: 
                   3688: sub removeuserfile {
                   3689:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3690:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3691:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3692:     if ($result eq 'ok') {	
1.798     raeburn  3693:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3694:             my $metafile = $fname.'.meta';
                   3695:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3696: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3697:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3698:             my $sqlresult = 
1.823     albertel 3699:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3700:                                         'portfolio_metadata',$group,
                   3701:                                         'delete');
1.798     raeburn  3702:         }
                   3703:     }
                   3704:     return $result;
1.257     www      3705: }
1.15      www      3706: 
1.530     albertel 3707: sub mkdiruserfile {
                   3708:     my ($docuname,$docudom,$dir)=@_;
                   3709:     my $home=&homeserver($docuname,$docudom);
                   3710:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3711: }
                   3712: 
1.531     albertel 3713: sub renameuserfile {
                   3714:     my ($docuname,$docudom,$old,$new)=@_;
                   3715:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3716:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3717:                         &escape("$old").':'.&escape("$new"),$home);
                   3718:     if ($result eq 'ok') {
                   3719:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3720:             my $oldmeta = $old.'.meta';
                   3721:             my $newmeta = $new.'.meta';
                   3722:             my $metaresult = 
                   3723:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3724: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3725:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3726:             my $sqlresult = 
1.823     albertel 3727:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3728:                                         'portfolio_metadata',$group,
                   3729:                                         'delete');
1.798     raeburn  3730:         }
                   3731:     }
                   3732:     return $result;
1.531     albertel 3733: }
                   3734: 
1.14      www      3735: # ------------------------------------------------------------------------- Log
                   3736: 
                   3737: sub log {
                   3738:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3739:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3740: }
                   3741: 
                   3742: # ------------------------------------------------------------------ Course Log
1.352     www      3743: #
                   3744: # This routine flushes several buffers of non-mission-critical nature
                   3745: #
1.157     www      3746: 
                   3747: sub flushcourselogs {
1.352     www      3748:     &logthis('Flushing log buffers');
                   3749: #
                   3750: # course logs
                   3751: # This is a log of all transactions in a course, which can be used
                   3752: # for data mining purposes
                   3753: #
                   3754: # It also collects the courseid database, which lists last transaction
                   3755: # times and course titles for all courseids
                   3756: #
                   3757:     my %courseidbuffer=();
1.921     raeburn  3758:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3759:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3760: 		          &escape($courselogs{$crsid}),
                   3761: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3762: 	    delete $courselogs{$crsid};
                   3763:         } else {
                   3764:             &logthis('Failed to flush log buffer for '.$crsid);
                   3765:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3766:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3767:                         " exceeded maximum size, deleting.</font>");
                   3768:                delete $courselogs{$crsid};
                   3769:             }
1.352     www      3770:         }
1.920     raeburn  3771:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3772:             'description' => $coursedescrbuf{$crsid},
                   3773:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3774:             'type'        => $coursetypebuf{$crsid},
                   3775:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3776:         };
1.191     harris41 3777:     }
1.352     www      3778: #
                   3779: # Write course id database (reverse lookup) to homeserver of courses 
                   3780: # Is used in pickcourse
                   3781: #
1.840     albertel 3782:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3783:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3784:                                     $courseidbuffer{$crs_home},
                   3785:                                     $crs_home,'timeonly');
1.352     www      3786:     }
                   3787: #
                   3788: # File accesses
                   3789: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3790: #
1.449     matthew  3791:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3792:         if ($entry =~ /___count$/) {
                   3793:             my ($dom,$name);
1.807     albertel 3794:             ($dom,$name,undef)=
1.811     albertel 3795: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3796:             if (! defined($dom) || $dom eq '' || 
                   3797:                 ! defined($name) || $name eq '') {
1.620     albertel 3798:                 my $cid = $env{'request.course.id'};
                   3799:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3800:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3801:             }
1.450     matthew  3802:             my $value = $accesshash{$entry};
                   3803:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3804:             my %temphash=($url => $value);
1.449     matthew  3805:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3806:             if ($result eq 'ok') {
                   3807:                 delete $accesshash{$entry};
                   3808:             }
                   3809:         } else {
1.811     albertel 3810:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3811:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3812:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3813:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3814:                 delete $accesshash{$entry};
                   3815:             }
1.185     www      3816:         }
1.191     harris41 3817:     }
1.352     www      3818: #
                   3819: # Roles
                   3820: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3821: #
1.800     albertel 3822:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3823:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3824: 	    split(/\:/,$entry);
                   3825:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3826:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3827:                 $rudom,$runame) eq 'ok') {
                   3828: 	    delete $userrolehash{$entry};
                   3829:         }
                   3830:     }
1.662     raeburn  3831: #
                   3832: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3833: #
                   3834:     my %domrolebuffer = ();
1.1000    raeburn  3835:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3836:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3837:         if ($domrolebuffer{$rudom}) {
                   3838:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3839:                       '='.&escape($domainrolehash{$entry});
                   3840:         } else {
                   3841:             $domrolebuffer{$rudom}.=&escape($entry).
                   3842:                       '='.&escape($domainrolehash{$entry});
                   3843:         }
                   3844:         delete $domainrolehash{$entry};
                   3845:     }
                   3846:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3847: 	my %servers = &get_servers($dom,'library');
                   3848: 	foreach my $tryserver (keys(%servers)) {
                   3849: 	    unless (&reply('domroleput:'.$dom.':'.
                   3850: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3851: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3852: 	    }
1.662     raeburn  3853:         }
                   3854:     }
1.186     www      3855:     $dumpcount++;
1.157     www      3856: }
                   3857: 
                   3858: sub courselog {
                   3859:     my $what=shift;
1.158     www      3860:     $what=time.':'.$what;
1.620     albertel 3861:     unless ($env{'request.course.id'}) { return ''; }
                   3862:     $coursedombuf{$env{'request.course.id'}}=
                   3863:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3864:     $coursenumbuf{$env{'request.course.id'}}=
                   3865:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3866:     $coursehombuf{$env{'request.course.id'}}=
                   3867:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3868:     $coursedescrbuf{$env{'request.course.id'}}=
                   3869:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3870:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3871:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3872:     $courseownerbuf{$env{'request.course.id'}}=
                   3873:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3874:     $coursetypebuf{$env{'request.course.id'}}=
                   3875:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3876:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3877: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3878:     } else {
1.620     albertel 3879: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3880:     }
1.620     albertel 3881:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3882: 	&flushcourselogs();
                   3883:     }
1.158     www      3884: }
                   3885: 
                   3886: sub courseacclog {
                   3887:     my $fnsymb=shift;
1.620     albertel 3888:     unless ($env{'request.course.id'}) { return ''; }
                   3889:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3890:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3891:         $what.=':POST';
1.583     matthew  3892:         # FIXME: Probably ought to escape things....
1.800     albertel 3893: 	foreach my $key (keys(%env)) {
                   3894:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3895:                 my $formitem = $1;
                   3896:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3897:                     $what.=':'.$formitem.'='.$env{$key};
                   3898:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3899:                     $what.=':'.$formitem.'='.$env{$key};
                   3900:                 }
1.158     www      3901:             }
1.191     harris41 3902:         }
1.583     matthew  3903:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3904:         # FIXME: We should not be depending on a form parameter that someone
                   3905:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3906:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3907:             $what.= ':POST';
                   3908:             # FIXME: Probably ought to escape things....
                   3909:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3910:                                  'crsdiscuss') {
1.620     albertel 3911:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3912:             }
                   3913:         }
1.158     www      3914:     }
                   3915:     &courselog($what);
1.149     www      3916: }
                   3917: 
1.185     www      3918: sub countacc {
                   3919:     my $url=&declutter(shift);
1.458     matthew  3920:     return if (! defined($url) || $url eq '');
1.620     albertel 3921:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3922: #
                   3923: # Mark that this url was used in this course
                   3924: #
1.620     albertel 3925:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3926: #
                   3927: # Increase the access count for this resource in this child process
                   3928: #
1.281     www      3929:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3930:     $accesshash{$key}++;
1.185     www      3931: }
1.349     www      3932: 
1.361     www      3933: sub linklog {
                   3934:     my ($from,$to)=@_;
                   3935:     $from=&declutter($from);
                   3936:     $to=&declutter($to);
                   3937:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3938:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3939: }
1.1160    www      3940: 
                   3941: sub statslog {
                   3942:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3943:     if ($users<2) { return; }
                   3944:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3945:             'course'       => $env{'request.course.id'},
                   3946:             'sections'     => '"all"',
                   3947:             'num_students' => $users,
                   3948:             'part'         => $part,
                   3949:             'symb'         => $symb,
                   3950:             'mean_tries'   => $av_attempts,
                   3951:             'deg_of_diff'  => $degdiff});
                   3952:     foreach my $key (keys(%dynstore)) {
                   3953:         $accesshash{$key}=$dynstore{$key};
                   3954:     }
                   3955: }
1.361     www      3956:   
1.349     www      3957: sub userrolelog {
                   3958:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3959:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3960:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3961:        $userrolehash
                   3962:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3963:                     =$tend.':'.$tstart;
1.662     raeburn  3964:     }
1.1169    droeschl 3965:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3966:        $userrolehash
                   3967:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3968:                     =$tend.':'.$tstart;
                   3969:     }
1.1169    droeschl 3970:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3971:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3972:        $domainrolehash
                   3973:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3974:                     = $tend.':'.$tstart;
                   3975:     }
1.351     www      3976: }
                   3977: 
1.957     raeburn  3978: sub courserolelog {
                   3979:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3980:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3981:         my $cdom = $1;
                   3982:         my $cnum = $2;
                   3983:         my $sec = $3;
                   3984:         my $namespace = 'rolelog';
                   3985:         my %storehash = (
                   3986:                            role    => $trole,
                   3987:                            start   => $tstart,
                   3988:                            end     => $tend,
                   3989:                            selfenroll => $selfenroll,
                   3990:                            context    => $context,
                   3991:                         );
                   3992:         if ($trole eq 'gr') {
                   3993:             $namespace = 'groupslog';
                   3994:             $storehash{'group'} = $sec;
                   3995:         } else {
                   3996:             $storehash{'section'} = $sec;
                   3997:         }
1.1188    raeburn  3998:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3999:                    $domain,$cnum,$cdom);
1.1184    raeburn  4000:         if (($trole ne 'st') || ($sec ne '')) {
                   4001:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4002:         }
                   4003:     }
                   4004:     return;
                   4005: }
                   4006: 
1.1184    raeburn  4007: sub domainrolelog {
                   4008:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4009:     if ($area =~ m{^/($match_domain)/$}) {
                   4010:         my $cdom = $1;
                   4011:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4012:         my $namespace = 'rolelog';
                   4013:         my %storehash = (
                   4014:                            role    => $trole,
                   4015:                            start   => $tstart,
                   4016:                            end     => $tend,
                   4017:                            context => $context,
                   4018:                         );
1.1188    raeburn  4019:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4020:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4021:     }
                   4022:     return;
                   4023: 
                   4024: }
                   4025: 
                   4026: sub coauthorrolelog {
                   4027:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4028:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4029:         my $audom = $1;
                   4030:         my $auname = $2;
                   4031:         my $namespace = 'rolelog';
                   4032:         my %storehash = (
                   4033:                            role    => $trole,
                   4034:                            start   => $tstart,
                   4035:                            end     => $tend,
                   4036:                            context => $context,
                   4037:                         );
1.1188    raeburn  4038:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4039:                    $domain,$auname,$audom);
1.1184    raeburn  4040:     }
                   4041:     return;
                   4042: }
                   4043: 
1.351     www      4044: sub get_course_adv_roles {
1.948     raeburn  4045:     my ($cid,$codes) = @_;
1.620     albertel 4046:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4047:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4048:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4049:     my %nothide=();
1.800     albertel 4050:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4051:         if ($user !~ /:/) {
                   4052: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4053:         } else {
                   4054:             $nothide{$user}=1;
                   4055:         }
1.470     www      4056:     }
1.1219    raeburn  4057:     my @possdoms = ($coursehash{'domain'});
                   4058:     if ($coursehash{'checkforpriv'}) {
                   4059:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4060:     }
1.351     www      4061:     my %returnhash=();
                   4062:     my %dumphash=
                   4063:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4064:     my $now=time;
1.997     raeburn  4065:     my %privileged;
1.1000    raeburn  4066:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4067: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4068:         if (($tstart) && ($tstart<0)) { next; }
                   4069:         if (($tend) && ($tend<$now)) { next; }
                   4070:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4071:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4072: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4073:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4074:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4075: 	if ($role eq 'cr') { next; }
1.948     raeburn  4076:         if ($codes) {
                   4077:             if ($section) { $role .= ':'.$section; }
                   4078:             if ($returnhash{$role}) {
                   4079:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4080:             } else {
                   4081:                 $returnhash{$role}=$username.':'.$domain;
                   4082:             }
1.351     www      4083:         } else {
1.988     raeburn  4084:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4085:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4086:             if ($returnhash{$key}) {
                   4087: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4088:             } else {
                   4089:                 $returnhash{$key}=$username.':'.$domain;
                   4090:             }
1.351     www      4091:         }
1.948     raeburn  4092:     }
1.400     www      4093:     return %returnhash;
                   4094: }
                   4095: 
                   4096: sub get_my_roles {
1.937     raeburn  4097:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4098:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4099:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4100:     my (%dumphash,%nothide);
1.1086    raeburn  4101:     if ($context eq 'userroles') {
1.1166    raeburn  4102:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4103:     } else {
1.1219    raeburn  4104:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4105:         if ($hidepriv) {
                   4106:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4107:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4108:                 if ($user !~ /:/) {
                   4109:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4110:                 } else {
                   4111:                     $nothide{$user} = 1;
                   4112:                 }
                   4113:             }
                   4114:         }
1.858     raeburn  4115:     }
1.400     www      4116:     my %returnhash=();
                   4117:     my $now=time;
1.999     raeburn  4118:     my %privileged;
1.800     albertel 4119:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4120:         my ($role,$tend,$tstart);
                   4121:         if ($context eq 'userroles') {
1.1149    raeburn  4122:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4123: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4124:         } else {
                   4125:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4126:         }
1.400     www      4127:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4128:         my $status = 'active';
1.939     raeburn  4129:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4130:             $status = 'previous';
                   4131:         } 
                   4132:         if (($tstart) && ($now<$tstart)) {
                   4133:             $status = 'future';
                   4134:         }
                   4135:         if (ref($types) eq 'ARRAY') {
                   4136:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4137:                 next;
                   4138:             } 
                   4139:         } else {
                   4140:             if ($status ne 'active') {
                   4141:                 next;
                   4142:             }
                   4143:         }
1.867     raeburn  4144:         my ($rolecode,$username,$domain,$section,$area);
                   4145:         if ($context eq 'userroles') {
1.1186    raeburn  4146:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4147:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4148:         } else {
                   4149:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4150:         }
1.832     raeburn  4151:         if (ref($roledoms) eq 'ARRAY') {
                   4152:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4153:                 next;
                   4154:             }
                   4155:         }
                   4156:         if (ref($roles) eq 'ARRAY') {
                   4157:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4158:                 if ($role =~ /^cr\//) {
                   4159:                     if (!grep(/^cr$/,@{$roles})) {
                   4160:                         next;
                   4161:                     }
1.1104    raeburn  4162:                 } elsif ($role =~ /^gr\//) {
                   4163:                     if (!grep(/^gr$/,@{$roles})) {
                   4164:                         next;
                   4165:                     }
1.922     raeburn  4166:                 } else {
                   4167:                     next;
                   4168:                 }
1.832     raeburn  4169:             }
1.867     raeburn  4170:         }
1.937     raeburn  4171:         if ($hidepriv) {
1.1219    raeburn  4172:             my @privroles = ('dc','su');
1.999     raeburn  4173:             if ($context eq 'userroles') {
1.1219    raeburn  4174:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4175:             } else {
1.1219    raeburn  4176:                 my $possdoms = [$domain];
                   4177:                 if (ref($roledoms) eq 'ARRAY') {
                   4178:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4179:                 }
1.1219    raeburn  4180:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4181:                     if (!$nothide{$username.':'.$domain}) {
                   4182:                         next;
                   4183:                     }
                   4184:                 }
1.937     raeburn  4185:             }
                   4186:         }
1.933     raeburn  4187:         if ($withsec) {
                   4188:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4189:                 $tstart.':'.$tend;
                   4190:         } else {
                   4191:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4192:         }
1.832     raeburn  4193:     }
1.373     www      4194:     return %returnhash;
1.399     www      4195: }
                   4196: 
                   4197: # ----------------------------------------------------- Frontpage Announcements
                   4198: #
                   4199: #
                   4200: 
                   4201: sub postannounce {
                   4202:     my ($server,$text)=@_;
1.844     albertel 4203:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4204:     unless ($text=~/\w/) { $text=''; }
                   4205:     return &reply('setannounce:'.&escape($text),$server);
                   4206: }
                   4207: 
                   4208: sub getannounce {
1.448     albertel 4209: 
                   4210:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4211: 	my $announcement='';
1.800     albertel 4212: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4213: 	close($fh);
1.399     www      4214: 	if ($announcement=~/\w/) { 
                   4215: 	    return 
                   4216:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4217:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4218: 	} else {
                   4219: 	    return '';
                   4220: 	}
                   4221:     } else {
                   4222: 	return '';
                   4223:     }
1.351     www      4224: }
1.353     www      4225: 
                   4226: # ---------------------------------------------------------- Course ID routines
                   4227: # Deal with domain's nohist_courseid.db files
                   4228: #
                   4229: 
                   4230: sub courseidput {
1.921     raeburn  4231:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4232:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4233:     my $outcome;
                   4234:     if ($caller eq 'timeonly') {
                   4235:         my $cids = '';
                   4236:         foreach my $item (keys(%$storehash)) {
                   4237:             $cids.=&escape($item).'&';
                   4238:         }
                   4239:         $cids=~s/\&$//;
                   4240:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4241:                           $coursehome);       
                   4242:     } else {
                   4243:         my $items = '';
                   4244:         foreach my $item (keys(%$storehash)) {
                   4245:             $items.= &escape($item).'='.
                   4246:                      &freeze_escape($$storehash{$item}).'&';
                   4247:         }
                   4248:         $items=~s/\&$//;
                   4249:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4250:                           $coursehome);
1.918     raeburn  4251:     }
                   4252:     if ($outcome eq 'unknown_cmd') {
                   4253:         my $what;
                   4254:         foreach my $cid (keys(%$storehash)) {
                   4255:             $what .= &escape($cid).'=';
1.921     raeburn  4256:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4257:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4258:             }
                   4259:             $what =~ s/\:$/&/;
                   4260:         }
                   4261:         $what =~ s/\&$//;  
                   4262:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4263:     } else {
                   4264:         return $outcome;
                   4265:     }
1.353     www      4266: }
                   4267: 
                   4268: sub courseiddump {
1.921     raeburn  4269:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4270:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4271:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4272:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4273:         $hasuniquecode)=@_;
1.918     raeburn  4274:     my $as_hash = 1;
                   4275:     my %returnhash;
                   4276:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4277:     my %libserv = &all_library();
                   4278:     foreach my $tryserver (keys(%libserv)) {
                   4279:         if ( (  $hostidflag == 1 
                   4280: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4281: 	     || (!defined($hostidflag)) ) {
                   4282: 
1.918     raeburn  4283: 	    if (($domfilter eq '') ||
                   4284: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4285:                 my $rep;
                   4286:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4287:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4288:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4289:                                 &escape($descfilter), &escape($instcodefilter), 
                   4290:                                 &escape($ownerfilter), &escape($coursefilter),
                   4291:                                 &escape($typefilter), &escape($regexp_ok), 
                   4292:                                 $as_hash, &escape($selfenrollonly), 
                   4293:                                 &escape($catfilter), $showhidden, $caller, 
                   4294:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4295:                                 &escape($createdbefore), &escape($createdafter), 
1.1247    raeburn  4296:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180    droeschl 4297:                 } else {
                   4298:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4299:                              $sincefilter.':'.&escape($descfilter).':'.
                   4300:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4301:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4302:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4303:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4304:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4305:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4306:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247    raeburn  4307:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180    droeschl 4308:                              $tryserver);
                   4309:                 }
                   4310:                      
1.918     raeburn  4311:                 my @pairs=split(/\&/,$rep);
                   4312:                 foreach my $item (@pairs) {
                   4313:                     my ($key,$value)=split(/\=/,$item,2);
                   4314:                     $key = &unescape($key);
                   4315:                     next if ($key =~ /^error: 2 /);
                   4316:                     my $result = &thaw_unescape($value);
                   4317:                     if (ref($result) eq 'HASH') {
                   4318:                         $returnhash{$key}=$result;
                   4319:                     } else {
1.921     raeburn  4320:                         my @responses = split(/:/,$value);
                   4321:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4322:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4323:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4324:                         }
1.1008    raeburn  4325:                     }
1.353     www      4326:                 }
                   4327:             }
                   4328:         }
                   4329:     }
                   4330:     return %returnhash;
                   4331: }
                   4332: 
1.1055    raeburn  4333: sub courselastaccess {
                   4334:     my ($cdom,$cnum,$hostidref) = @_;
                   4335:     my %returnhash;
                   4336:     if ($cdom && $cnum) {
                   4337:         my $chome = &homeserver($cnum,$cdom);
                   4338:         if ($chome ne 'no_host') {
                   4339:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4340:             &extract_lastaccess(\%returnhash,$rep);
                   4341:         }
                   4342:     } else {
                   4343:         if (!$cdom) { $cdom=''; }
                   4344:         my %libserv = &all_library();
                   4345:         foreach my $tryserver (keys(%libserv)) {
                   4346:             if (ref($hostidref) eq 'ARRAY') {
                   4347:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4348:             } 
                   4349:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4350:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4351:                 &extract_lastaccess(\%returnhash,$rep);
                   4352:             }
                   4353:         }
                   4354:     }
                   4355:     return %returnhash;
                   4356: }
                   4357: 
                   4358: sub extract_lastaccess {
                   4359:     my ($returnhash,$rep) = @_;
                   4360:     if (ref($returnhash) eq 'HASH') {
                   4361:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4362:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4363:                  $rep eq '') {
                   4364:             my @pairs=split(/\&/,$rep);
                   4365:             foreach my $item (@pairs) {
                   4366:                 my ($key,$value)=split(/\=/,$item,2);
                   4367:                 $key = &unescape($key);
                   4368:                 next if ($key =~ /^error: 2 /);
                   4369:                 $returnhash->{$key} = &thaw_unescape($value);
                   4370:             }
                   4371:         }
                   4372:     }
                   4373:     return;
                   4374: }
                   4375: 
1.658     raeburn  4376: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4377: 
                   4378: sub dcmailput {
1.685     raeburn  4379:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4380:     my $status = &Apache::lonnet::critical(
1.740     www      4381:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4382:        &escape($message),$server);
1.662     raeburn  4383:     return $status;
                   4384: }
                   4385: 
1.658     raeburn  4386: sub dcmaildump {
                   4387:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4388:     my %returnhash=();
1.846     albertel 4389: 
                   4390:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4391:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4392:                                                          &escape($enddate).':';
                   4393: 	my @esc_senders=map { &escape($_)} @$senders;
                   4394: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4395: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4396:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4397:             if (($key) && ($value)) {
                   4398:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4399:             }
                   4400:         }
                   4401:     }
                   4402:     return %returnhash;
                   4403: }
1.662     raeburn  4404: # ---------------------------------------------------------- Domain roles
                   4405: 
                   4406: sub get_domain_roles {
                   4407:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4408:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4409:         $startdate = '.';
                   4410:     }
1.1018    raeburn  4411:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4412:         $enddate = '.';
                   4413:     }
1.922     raeburn  4414:     my $rolelist;
                   4415:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4416:         $rolelist = join('&',@{$roles});
1.922     raeburn  4417:     }
1.662     raeburn  4418:     my %personnel = ();
1.841     albertel 4419: 
                   4420:     my %servers = &get_servers($dom,'library');
                   4421:     foreach my $tryserver (keys(%servers)) {
                   4422: 	%{$personnel{$tryserver}}=();
                   4423: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4424: 					    &escape($startdate).':'.
                   4425: 					    &escape($enddate).':'.
                   4426: 					    &escape($rolelist), $tryserver))) {
                   4427: 	    my ($key,$value) = split(/\=/,$line,2);
                   4428: 	    if (($key) && ($value)) {
                   4429: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4430: 	    }
                   4431: 	}
1.662     raeburn  4432:     }
                   4433:     return %personnel;
                   4434: }
1.658     raeburn  4435: 
1.1057    www      4436: # ----------------------------------------------------------- Interval timing 
1.149     www      4437: 
1.1153    www      4438: {
                   4439: # Caches needed for speedup of navmaps
                   4440: # We don't want to cache this for very long at all (5 seconds at most)
                   4441: # 
                   4442: # The user for whom we cache
                   4443: my $cachedkey='';
                   4444: # The cached times for this user
                   4445: my %cachedtimes=();
                   4446: # When this was last done
                   4447: my $cachedtime=();
                   4448: 
                   4449: sub load_all_first_access {
1.1154    raeburn  4450:     my ($uname,$udom)=@_;
1.1156    www      4451:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4452:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4453:         return;
                   4454:     }
                   4455:     $cachedtime=time;
                   4456:     $cachedkey=$uname.':'.$udom;
                   4457:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4458: }
                   4459: 
1.504     albertel 4460: sub get_first_access {
1.1162    raeburn  4461:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4462:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4463:     if ($argsymb) { $symb=$argsymb; }
                   4464:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4465:     if ($argmap) { $map = $argmap; }
1.926     albertel 4466:     if ($type eq 'course') {
                   4467: 	$res='course';
                   4468:     } elsif ($type eq 'map') {
1.588     albertel 4469: 	$res=&symbread($map);
                   4470:     } else {
                   4471: 	$res=$symb;
                   4472:     }
1.1153    www      4473:     &load_all_first_access($uname,$udom);
                   4474:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4475: }
                   4476: 
                   4477: sub set_first_access {
1.1162    raeburn  4478:     my ($type,$interval)=@_;
1.790     albertel 4479:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4480:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4481:     if ($type eq 'course') {
                   4482: 	$res='course';
                   4483:     } elsif ($type eq 'map') {
1.588     albertel 4484: 	$res=&symbread($map);
                   4485:     } else {
                   4486: 	$res=$symb;
                   4487:     }
1.1153    www      4488:     $cachedkey='';
1.1162    raeburn  4489:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4490:     if (!$firstaccess) {
1.1162    raeburn  4491:         my $start = time;
                   4492: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4493:                           $udom,$uname);
                   4494:         if ($putres eq 'ok') {
                   4495:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4496:                  $udom,$uname); 
                   4497:             &appenv(
                   4498:                      {
                   4499:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4500:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4501:                      }
                   4502:                   );
                   4503:         }
                   4504:         return $putres;
1.505     albertel 4505:     }
                   4506:     return 'already_set';
1.504     albertel 4507: }
1.1153    www      4508: }
1.110     www      4509: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4510: 
                   4511: sub expirespread {
                   4512:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4513:     my $cid=$env{'request.course.id'}; 
1.110     www      4514:     if ($cid) {
                   4515:        my $now=time;
                   4516:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4517:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4518:                             $env{'course.'.$cid.'.num'}.
1.110     www      4519: 	        	    ':nohist_expirationdates:'.
                   4520:                             &escape($key).'='.$now,
1.620     albertel 4521:                             $env{'course.'.$cid.'.home'})
1.110     www      4522:     }
                   4523:     return 'ok';
1.14      www      4524: }
                   4525: 
1.109     www      4526: # ----------------------------------------------------- Devalidate Spreadsheets
                   4527: 
                   4528: sub devalidate {
1.325     www      4529:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4530:     my $cid=$env{'request.course.id'}; 
1.109     www      4531:     if ($cid) {
1.391     matthew  4532:         # delete the stored spreadsheets for
                   4533:         # - the student level sheet of this user in course's homespace
                   4534:         # - the assessment level sheet for this resource 
                   4535:         #   for this user in user's homespace
1.553     albertel 4536: 	# - current conditional state info
1.325     www      4537: 	my $key=$uname.':'.$udom.':';
1.109     www      4538:         my $status=
1.299     matthew  4539: 	    &del('nohist_calculatedsheets',
1.391     matthew  4540: 		 [$key.'studentcalc:'],
1.620     albertel 4541: 		 $env{'course.'.$cid.'.domain'},
                   4542: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4543: 		.' '.
                   4544: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4545: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4546:         unless ($status eq 'ok ok') {
                   4547:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4548:                     $uname.' at '.$udom.' for '.
1.109     www      4549: 		    $symb.': '.$status);
1.133     albertel 4550:         }
1.553     albertel 4551: 	&delenv('user.state.'.$cid);
1.109     www      4552:     }
                   4553: }
                   4554: 
1.265     albertel 4555: sub get_scalar {
                   4556:     my ($string,$end) = @_;
                   4557:     my $value;
                   4558:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4559: 	$value = $1;
                   4560:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4561: 	$value = $1;
                   4562:     }
                   4563:     return &unescape($value);
                   4564: }
                   4565: 
                   4566: sub array2str {
                   4567:   my (@array) = @_;
                   4568:   my $result=&arrayref2str(\@array);
                   4569:   $result=~s/^__ARRAY_REF__//;
                   4570:   $result=~s/__END_ARRAY_REF__$//;
                   4571:   return $result;
                   4572: }
                   4573: 
1.204     albertel 4574: sub arrayref2str {
                   4575:   my ($arrayref) = @_;
1.265     albertel 4576:   my $result='__ARRAY_REF__';
1.204     albertel 4577:   foreach my $elem (@$arrayref) {
1.265     albertel 4578:     if(ref($elem) eq 'ARRAY') {
                   4579:       $result.=&arrayref2str($elem).'&';
                   4580:     } elsif(ref($elem) eq 'HASH') {
                   4581:       $result.=&hashref2str($elem).'&';
                   4582:     } elsif(ref($elem)) {
                   4583:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4584:     } else {
                   4585:       $result.=&escape($elem).'&';
                   4586:     }
                   4587:   }
                   4588:   $result=~s/\&$//;
1.265     albertel 4589:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4590:   return $result;
                   4591: }
                   4592: 
1.168     albertel 4593: sub hash2str {
1.204     albertel 4594:   my (%hash) = @_;
                   4595:   my $result=&hashref2str(\%hash);
1.265     albertel 4596:   $result=~s/^__HASH_REF__//;
                   4597:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4598:   return $result;
                   4599: }
                   4600: 
                   4601: sub hashref2str {
                   4602:   my ($hashref)=@_;
1.265     albertel 4603:   my $result='__HASH_REF__';
1.800     albertel 4604:   foreach my $key (sort(keys(%$hashref))) {
                   4605:     if (ref($key) eq 'ARRAY') {
                   4606:       $result.=&arrayref2str($key).'=';
                   4607:     } elsif (ref($key) eq 'HASH') {
                   4608:       $result.=&hashref2str($key).'=';
                   4609:     } elsif (ref($key)) {
1.265     albertel 4610:       $result.='=';
1.800     albertel 4611:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4612:     } else {
1.1132    raeburn  4613: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4614:     }
                   4615: 
1.800     albertel 4616:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4617:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4618:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4619:       $result.=&hashref2str($hashref->{$key}).'&';
                   4620:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4621:        $result.='&';
1.800     albertel 4622:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4623:     } else {
1.800     albertel 4624:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4625:     }
                   4626:   }
1.168     albertel 4627:   $result=~s/\&$//;
1.265     albertel 4628:   $result .= '__END_HASH_REF__';
1.168     albertel 4629:   return $result;
                   4630: }
                   4631: 
                   4632: sub str2hash {
1.265     albertel 4633:     my ($string)=@_;
                   4634:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4635:     return %$hash;
                   4636: }
                   4637: 
                   4638: sub str2hashref {
1.168     albertel 4639:   my ($string) = @_;
1.265     albertel 4640: 
                   4641:   my %hash;
                   4642: 
                   4643:   if($string !~ /^__HASH_REF__/) {
                   4644:       if (! ($string eq '' || !defined($string))) {
                   4645: 	  $hash{'error'}='Not hash reference';
                   4646:       }
                   4647:       return (\%hash, $string);
                   4648:   }
                   4649: 
                   4650:   $string =~ s/^__HASH_REF__//;
                   4651: 
                   4652:   while($string !~ /^__END_HASH_REF__/) {
                   4653:       #key
                   4654:       my $key='';
                   4655:       if($string =~ /^__HASH_REF__/) {
                   4656:           ($key, $string)=&str2hashref($string);
                   4657:           if(defined($key->{'error'})) {
                   4658:               $hash{'error'}='Bad data';
                   4659:               return (\%hash, $string);
                   4660:           }
                   4661:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4662:           ($key, $string)=&str2arrayref($string);
                   4663:           if($key->[0] eq 'Array reference error') {
                   4664:               $hash{'error'}='Bad data';
                   4665:               return (\%hash, $string);
                   4666:           }
                   4667:       } else {
                   4668:           $string =~ s/^(.*?)=//;
1.267     albertel 4669: 	  $key=&unescape($1);
1.265     albertel 4670:       }
                   4671:       $string =~ s/^=//;
                   4672: 
                   4673:       #value
                   4674:       my $value='';
                   4675:       if($string =~ /^__HASH_REF__/) {
                   4676:           ($value, $string)=&str2hashref($string);
                   4677:           if(defined($value->{'error'})) {
                   4678:               $hash{'error'}='Bad data';
                   4679:               return (\%hash, $string);
                   4680:           }
                   4681:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4682:           ($value, $string)=&str2arrayref($string);
                   4683:           if($value->[0] eq 'Array reference error') {
                   4684:               $hash{'error'}='Bad data';
                   4685:               return (\%hash, $string);
                   4686:           }
                   4687:       } else {
                   4688: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4689:       }
                   4690:       $string =~ s/^&//;
                   4691: 
                   4692:       $hash{$key}=$value;
1.204     albertel 4693:   }
1.265     albertel 4694: 
                   4695:   $string =~ s/^__END_HASH_REF__//;
                   4696: 
                   4697:   return (\%hash, $string);
1.204     albertel 4698: }
                   4699: 
                   4700: sub str2array {
1.265     albertel 4701:     my ($string)=@_;
                   4702:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4703:     return @$array;
                   4704: }
                   4705: 
                   4706: sub str2arrayref {
1.204     albertel 4707:   my ($string) = @_;
1.265     albertel 4708:   my @array;
                   4709: 
                   4710:   if($string !~ /^__ARRAY_REF__/) {
                   4711:       if (! ($string eq '' || !defined($string))) {
                   4712: 	  $array[0]='Array reference error';
                   4713:       }
                   4714:       return (\@array, $string);
                   4715:   }
                   4716: 
                   4717:   $string =~ s/^__ARRAY_REF__//;
                   4718: 
                   4719:   while($string !~ /^__END_ARRAY_REF__/) {
                   4720:       my $value='';
                   4721:       if($string =~ /^__HASH_REF__/) {
                   4722:           ($value, $string)=&str2hashref($string);
                   4723:           if(defined($value->{'error'})) {
                   4724:               $array[0] ='Array reference error';
                   4725:               return (\@array, $string);
                   4726:           }
                   4727:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4728:           ($value, $string)=&str2arrayref($string);
                   4729:           if($value->[0] eq 'Array reference error') {
                   4730:               $array[0] ='Array reference error';
                   4731:               return (\@array, $string);
                   4732:           }
                   4733:       } else {
                   4734: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4735:       }
                   4736:       $string =~ s/^&//;
                   4737: 
                   4738:       push(@array, $value);
1.191     harris41 4739:   }
1.265     albertel 4740: 
                   4741:   $string =~ s/^__END_ARRAY_REF__//;
                   4742: 
                   4743:   return (\@array, $string);
1.168     albertel 4744: }
                   4745: 
1.167     albertel 4746: # -------------------------------------------------------------------Temp Store
                   4747: 
1.168     albertel 4748: sub tmpreset {
                   4749:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4750:   if (!$symb) {
                   4751:     $symb=&symbread();
1.620     albertel 4752:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4753:   }
                   4754:   $symb=escape($symb);
                   4755: 
1.620     albertel 4756:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4757:   $namespace=~s/\//\_/g;
                   4758:   $namespace=~s/\W//g;
                   4759: 
1.620     albertel 4760:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4761:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4762:   if ($domain eq 'public' && $stuname eq 'public') {
                   4763:       $stuname=$ENV{'REMOTE_ADDR'};
                   4764:   }
1.1117    foxr     4765:   my $path=LONCAPA::tempdir();
1.168     albertel 4766:   my %hash;
                   4767:   if (tie(%hash,'GDBM_File',
                   4768: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4769: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4770:     foreach my $key (keys(%hash)) {
1.180     albertel 4771:       if ($key=~ /:$symb/) {
1.168     albertel 4772: 	delete($hash{$key});
                   4773:       }
                   4774:     }
                   4775:   }
                   4776: }
                   4777: 
1.167     albertel 4778: sub tmpstore {
1.168     albertel 4779:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4780: 
                   4781:   if (!$symb) {
                   4782:     $symb=&symbread();
1.620     albertel 4783:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4784:   }
                   4785:   $symb=escape($symb);
                   4786: 
                   4787:   if (!$namespace) {
                   4788:     # I don't think we would ever want to store this for a course.
                   4789:     # it seems this will only be used if we don't have a course.
1.620     albertel 4790:     #$namespace=$env{'request.course.id'};
1.168     albertel 4791:     #if (!$namespace) {
1.620     albertel 4792:       $namespace=$env{'request.state'};
1.168     albertel 4793:     #}
                   4794:   }
                   4795:   $namespace=~s/\//\_/g;
                   4796:   $namespace=~s/\W//g;
1.620     albertel 4797:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4798:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4799:   if ($domain eq 'public' && $stuname eq 'public') {
                   4800:       $stuname=$ENV{'REMOTE_ADDR'};
                   4801:   }
1.168     albertel 4802:   my $now=time;
                   4803:   my %hash;
1.1117    foxr     4804:   my $path=LONCAPA::tempdir();
1.168     albertel 4805:   if (tie(%hash,'GDBM_File',
                   4806: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4807: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4808:     $hash{"version:$symb"}++;
                   4809:     my $version=$hash{"version:$symb"};
                   4810:     my $allkeys=''; 
                   4811:     foreach my $key (keys(%$storehash)) {
                   4812:       $allkeys.=$key.':';
1.591     albertel 4813:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4814:     }
                   4815:     $hash{"$version:$symb:timestamp"}=$now;
                   4816:     $allkeys.='timestamp';
                   4817:     $hash{"$version:keys:$symb"}=$allkeys;
                   4818:     if (untie(%hash)) {
                   4819:       return 'ok';
                   4820:     } else {
                   4821:       return "error:$!";
                   4822:     }
                   4823:   } else {
                   4824:     return "error:$!";
                   4825:   }
                   4826: }
1.167     albertel 4827: 
1.168     albertel 4828: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4829: 
1.168     albertel 4830: sub tmprestore {
                   4831:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4832: 
1.168     albertel 4833:   if (!$symb) {
                   4834:     $symb=&symbread();
1.620     albertel 4835:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4836:   }
                   4837:   $symb=escape($symb);
                   4838: 
1.620     albertel 4839:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4840: 
1.620     albertel 4841:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4842:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4843:   if ($domain eq 'public' && $stuname eq 'public') {
                   4844:       $stuname=$ENV{'REMOTE_ADDR'};
                   4845:   }
1.168     albertel 4846:   my %returnhash;
                   4847:   $namespace=~s/\//\_/g;
                   4848:   $namespace=~s/\W//g;
                   4849:   my %hash;
1.1117    foxr     4850:   my $path=LONCAPA::tempdir();
1.168     albertel 4851:   if (tie(%hash,'GDBM_File',
                   4852: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4853: 	  &GDBM_READER(),0640)) {
1.168     albertel 4854:     my $version=$hash{"version:$symb"};
                   4855:     $returnhash{'version'}=$version;
                   4856:     my $scope;
                   4857:     for ($scope=1;$scope<=$version;$scope++) {
                   4858:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4859:       my @keys=split(/:/,$vkeys);
                   4860:       my $key;
                   4861:       $returnhash{"$scope:keys"}=$vkeys;
                   4862:       foreach $key (@keys) {
1.591     albertel 4863: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4864: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4865:       }
                   4866:     }
1.168     albertel 4867:     if (!(untie(%hash))) {
                   4868:       return "error:$!";
                   4869:     }
                   4870:   } else {
                   4871:     return "error:$!";
                   4872:   }
                   4873:   return %returnhash;
1.167     albertel 4874: }
                   4875: 
1.9       www      4876: # ----------------------------------------------------------------------- Store
                   4877: 
                   4878: sub store {
1.1269    raeburn  4879:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4880:     my $home='';
                   4881: 
1.168     albertel 4882:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4883: 
1.213     www      4884:     $symb=&symbclean($symb);
1.122     albertel 4885:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4886: 
1.620     albertel 4887:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4888:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4889: 
                   4890:     &devalidate($symb,$stuname,$domain);
1.109     www      4891: 
                   4892:     $symb=escape($symb);
1.187     www      4893:     if (!$namespace) { 
1.620     albertel 4894:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4895:           return ''; 
                   4896:        } 
                   4897:     }
1.620     albertel 4898:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4899: 
                   4900:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4901:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4902: 
1.12      www      4903:     my $namevalue='';
1.800     albertel 4904:     foreach my $key (keys(%$storehash)) {
                   4905:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4906:     }
1.12      www      4907:     $namevalue=~s/\&$//;
1.187     www      4908:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  4909:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      4910: }
                   4911: 
1.47      www      4912: # -------------------------------------------------------------- Critical Store
                   4913: 
                   4914: sub cstore {
1.1269    raeburn  4915:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4916:     my $home='';
                   4917: 
1.168     albertel 4918:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4919: 
1.213     www      4920:     $symb=&symbclean($symb);
1.122     albertel 4921:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4922: 
1.620     albertel 4923:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4924:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4925: 
                   4926:     &devalidate($symb,$stuname,$domain);
1.109     www      4927: 
                   4928:     $symb=escape($symb);
1.187     www      4929:     if (!$namespace) { 
1.620     albertel 4930:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4931:           return ''; 
                   4932:        } 
                   4933:     }
1.620     albertel 4934:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4935: 
                   4936:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4937:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4938: 
1.47      www      4939:     my $namevalue='';
1.800     albertel 4940:     foreach my $key (keys(%$storehash)) {
                   4941:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4942:     }
1.47      www      4943:     $namevalue=~s/\&$//;
1.187     www      4944:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4945:     return critical
1.1269    raeburn  4946:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      4947: }
                   4948: 
1.9       www      4949: # --------------------------------------------------------------------- Restore
                   4950: 
                   4951: sub restore {
1.124     www      4952:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4953:     my $home='';
                   4954: 
1.168     albertel 4955:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4956: 
1.122     albertel 4957:     if (!$symb) {
1.1224    raeburn  4958:         return if ($namespace eq 'courserequests');
                   4959:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4960:     } else {
1.1224    raeburn  4961:         unless ($namespace eq 'courserequests') {
                   4962:             $symb=&escape(&symbclean($symb));
                   4963:         }
1.122     albertel 4964:     }
1.188     www      4965:     if (!$namespace) { 
1.620     albertel 4966:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4967:           return ''; 
                   4968:        } 
                   4969:     }
1.620     albertel 4970:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4971:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4972:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4973:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4974: 
1.12      www      4975:     my %returnhash=();
1.800     albertel 4976:     foreach my $line (split(/\&/,$answer)) {
                   4977: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4978:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4979:     }
1.75      www      4980:     my $version;
                   4981:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4982:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4983:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4984:        }
1.75      www      4985:     }
1.13      www      4986:     return %returnhash;
1.34      www      4987: }
                   4988: 
                   4989: # ---------------------------------------------------------- Course Description
1.1118    foxr     4990: #
                   4991: #  
1.34      www      4992: 
                   4993: sub coursedescription {
1.731     albertel 4994:     my ($courseid,$args)=@_;
1.34      www      4995:     $courseid=~s/^\///;
1.49      www      4996:     $courseid=~s/\_/\//g;
1.34      www      4997:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4998:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4999:     my $normalid=$cdomain.'_'.$cnum;
                   5000:     # need to always cache even if we get errors otherwise we keep 
                   5001:     # trying and trying and trying to get the course description.
                   5002:     my %envhash=();
                   5003:     my %returnhash=();
1.731     albertel 5004:     
                   5005:     my $expiretime=600;
                   5006:     if ($env{'request.course.id'} eq $normalid) {
                   5007: 	$expiretime=120;
                   5008:     }
                   5009: 
                   5010:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5011:     if (!$args->{'freshen_cache'}
                   5012: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5013: 	foreach my $key (keys(%env)) {
                   5014: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5015: 	    my ($setting) = $1;
                   5016: 	    $returnhash{$setting} = $env{$key};
                   5017: 	}
                   5018: 	return %returnhash;
                   5019:     }
                   5020: 
1.1118    foxr     5021:     # get the data again
                   5022: 
1.731     albertel 5023:     if (!$args->{'one_time'}) {
                   5024: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5025:     }
1.811     albertel 5026: 
1.34      www      5027:     if ($chome ne 'no_host') {
1.302     albertel 5028:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5029:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5030: 	   my $username = $env{'user.name'}; # Defult username
                   5031: 	   if(defined $args->{'user'}) {
                   5032: 	       $username = $args->{'user'};
                   5033: 	   }
1.129     albertel 5034:            $returnhash{'home'}= $chome;
                   5035: 	   $returnhash{'domain'} = $cdomain;
                   5036: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5037:            if (!defined($returnhash{'type'})) {
                   5038:                $returnhash{'type'} = 'Course';
                   5039:            }
1.130     albertel 5040:            while (my ($name,$value) = each %returnhash) {
1.53      www      5041:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5042:            }
1.270     www      5043:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5044:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5045: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5046:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5047:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5048:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5049:        }
                   5050:     }
1.731     albertel 5051:     if (!$args->{'one_time'}) {
1.949     raeburn  5052: 	&appenv(\%envhash);
1.731     albertel 5053:     }
1.302     albertel 5054:     return %returnhash;
1.461     www      5055: }
                   5056: 
1.1080    raeburn  5057: sub update_released_required {
                   5058:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5059:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5060:         $cid = $env{'request.course.id'};
                   5061:         $cdom = $env{'course.'.$cid.'.domain'};
                   5062:         $cnum = $env{'course.'.$cid.'.num'};
                   5063:         $chome = $env{'course.'.$cid.'.home'};
                   5064:     }
                   5065:     if ($needsrelease) {
                   5066:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5067:         my $needsupdate;
                   5068:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5069:             $needsupdate = 1;
                   5070:         } else {
                   5071:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5072:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5073:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5074:                 $needsupdate = 1;
                   5075:             }
                   5076:         }
                   5077:         if ($needsupdate) {
                   5078:             my %needshash = (
                   5079:                              'internal.releaserequired' => $needsrelease,
                   5080:                             );
                   5081:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5082:             if ($putresult eq 'ok') {
                   5083:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5084:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5085:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5086:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5087:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5088:                 }
                   5089:             }
                   5090:         }
                   5091:     }
                   5092:     return;
                   5093: }
                   5094: 
1.461     www      5095: # -------------------------------------------------See if a user is privileged
                   5096: 
                   5097: sub privileged {
1.1219    raeburn  5098:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5099:     my $now = time;
1.1219    raeburn  5100:     my $roles;
                   5101:     if (ref($possroles) eq 'ARRAY') {
                   5102:         $roles = $possroles; 
                   5103:     } else {
                   5104:         $roles = ['dc','su'];
                   5105:     }
                   5106:     if (ref($possdomains) eq 'ARRAY') {
                   5107:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5108:         foreach my $dom (@{$possdomains}) {
                   5109:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5110:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5111:                 foreach my $role (@{$roles}) {
                   5112:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5113:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5114:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5115:                             return 1 unless (($end && $end < $now) ||
                   5116:                                              ($start && $start > $now));
                   5117:                         }
                   5118:                     }
                   5119:                 }
                   5120:             }
                   5121:         }
                   5122:     } else {
                   5123:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5124:         my $now = time;
1.1170    droeschl 5125: 
1.1275    musolffc 5126:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5127:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5128:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5129:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5130:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5131:             }
1.1219    raeburn  5132:         }
                   5133:     }
                   5134:     return 0;
                   5135: }
1.1170    droeschl 5136: 
1.1219    raeburn  5137: sub privileged_by_domain {
                   5138:     my ($domains,$roles) = @_;
                   5139:     my %privileged = ();
                   5140:     my $cachetime = 60*60*24;
                   5141:     my $now = time;
                   5142:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5143:         return %privileged;
                   5144:     }
                   5145:     foreach my $dom (@{$domains}) {
                   5146:         next if (ref($privileged{$dom}) eq 'HASH');
                   5147:         my $needroles;
                   5148:         foreach my $role (@{$roles}) {
                   5149:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5150:             if (defined($cached)) {
                   5151:                 if (ref($result) eq 'HASH') {
                   5152:                     $privileged{$dom}{$role} = $result;
                   5153:                 }
                   5154:             } else {
                   5155:                 $needroles = 1;
                   5156:             }
                   5157:         }
                   5158:         if ($needroles) {
                   5159:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5160:             $privileged{$dom} = {};
                   5161:             foreach my $server (keys(%dompersonnel)) {
                   5162:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5163:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5164:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5165:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5166:                         next if ($end && $end < $now);
                   5167:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5168:                             $dompersonnel{$server}{$item};
                   5169:                     }
                   5170:                 }
                   5171:             }
                   5172:             if (ref($privileged{$dom}) eq 'HASH') {
                   5173:                 foreach my $role (@{$roles}) {
                   5174:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5175:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5176:                     } else {
                   5177:                         my %hash = ();
                   5178:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5179:                     }
                   5180:                 }
                   5181:             }
                   5182:         }
                   5183:     }
                   5184:     return %privileged;
1.9       www      5185: }
1.1       albertel 5186: 
1.103     harris41 5187: # -------------------------------------------------------- Get user privileges
1.11      www      5188: 
                   5189: sub rolesinit {
1.1169    droeschl 5190:     my ($domain, $username) = @_;
                   5191:     my %userroles = ('user.login.time' => time);
                   5192:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5193: 
                   5194:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5195:     # also, blocking can be triggered by an activating timer
                   5196:     # it's saved in the user's %env.
                   5197:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5198:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5199:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5200:         %timerintchk, %timerintenv);
                   5201: 
1.1162    raeburn  5202:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5203:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5204:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5205:     }
1.1169    droeschl 5206: 
1.1162    raeburn  5207:     foreach my $key (keys(%timerinterval)) {
                   5208:         my ($cid,$rest) = split(/\0/,$key);
                   5209:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5210:     }
1.1169    droeschl 5211: 
1.11      www      5212:     my %allroles=();
1.1162    raeburn  5213:     my %allgroups=();
1.11      www      5214: 
1.1274    raeburn  5215:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5216:         my $role = $rolesdump{$area};
                   5217:         $area =~ s/\_\w\w$//;
                   5218: 
                   5219:         my ($trole, $tend, $tstart, $group_privs);
                   5220: 
                   5221:         if ($role =~ /^cr/) {
                   5222:         # Custom role, defined by a user 
                   5223:         # e.g., user.role.cr/msu/smith/mynewrole
                   5224:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5225:                 $trole = $1;
                   5226:                 ($tend, $tstart) = split('_', $2);
                   5227:             } else {
                   5228:                 $trole = $role;
                   5229:             }
                   5230:         } elsif ($role =~ m|^gr/|) {
                   5231:         # Role of member in a group, defined within a course/community
                   5232:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5233:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5234:             next if $tstart eq '-1';
                   5235:             ($trole, $group_privs) = split(/\//, $trole);
                   5236:             $group_privs = &unescape($group_privs);
                   5237:         } else {
                   5238:         # Just a normal role, defined in roles.tab
                   5239:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5240:         }
                   5241: 
                   5242:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5243:                  $username);
                   5244:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5245: 
                   5246:         # role expired or not available yet?
                   5247:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5248:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5249: 
                   5250:         next if $area eq '' or $trole eq '';
                   5251: 
                   5252:         my $spec = "$trole.$area";
                   5253:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5254: 
                   5255:         if ($trole =~ /^cr\//) {
                   5256:         # Custom role, defined by a user
                   5257:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5258:         } elsif ($trole eq 'gr') {
                   5259:         # Role of a member in a group, defined within a course/community
                   5260:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5261:             next;
                   5262:         } else {
                   5263:         # Normal role, defined in roles.tab
                   5264:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5265:         }
                   5266: 
                   5267:         my $cid = $tdomain.'_'.$trest;
                   5268:         unless ($firstaccchk{$cid}) {
                   5269:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5270:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5271:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5272:                         $coursetimerstarts{$cid}{$item}; 
                   5273:                 }
                   5274:             }
                   5275:             $firstaccchk{$cid} = 1;
                   5276:         }
                   5277:         unless ($timerintchk{$cid}) {
                   5278:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5279:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5280:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5281:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5282:                 }
1.12      www      5283:             }
1.1169    droeschl 5284:             $timerintchk{$cid} = 1;
1.191     harris41 5285:         }
1.11      www      5286:     }
1.1169    droeschl 5287: 
                   5288:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5289:         \%allroles, \%allgroups);
                   5290:     $env{'user.adv'} = $userroles{'user.adv'};
                   5291: 
1.1162    raeburn  5292:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5293: }
                   5294: 
1.567     raeburn  5295: sub set_arearole {
1.1215    raeburn  5296:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5297:     unless ($nolog) {
1.567     raeburn  5298: # log the associated role with the area
1.1215    raeburn  5299:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5300:     }
1.743     albertel 5301:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5302: }
                   5303: 
                   5304: sub custom_roleprivs {
                   5305:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5306:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5307:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5308:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5309:         my ($rdummy,$roledef)=
                   5310:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5311:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5312:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5313:             if (defined($syspriv)) {
1.1043    raeburn  5314:                 if ($trest =~ /^$match_community$/) {
                   5315:                     $syspriv =~ s/bre\&S//; 
                   5316:                 }
1.567     raeburn  5317:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5318:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5319:             }
                   5320:             if ($tdomain ne '') {
                   5321:                 if (defined($dompriv)) {
                   5322:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5323:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5324:                 }
                   5325:                 if (($trest ne '') && (defined($coursepriv))) {
                   5326:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5327:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5328:                 }
                   5329:             }
                   5330:         }
                   5331:     }
                   5332: }
                   5333: 
1.678     raeburn  5334: sub group_roleprivs {
                   5335:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5336:     my $access = 1;
                   5337:     my $now = time;
                   5338:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5339:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5340:     if ($access) {
1.811     albertel 5341:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5342:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5343:     }
                   5344: }
1.567     raeburn  5345: 
                   5346: sub standard_roleprivs {
                   5347:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5348:     if (defined($pr{$trole.':s'})) {
                   5349:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5350:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5351:     }
                   5352:     if ($tdomain ne '') {
                   5353:         if (defined($pr{$trole.':d'})) {
                   5354:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5355:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5356:         }
                   5357:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5358:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5359:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5360:         }
                   5361:     }
                   5362: }
                   5363: 
                   5364: sub set_userprivs {
1.1064    raeburn  5365:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5366:     my $author=0;
                   5367:     my $adv=0;
1.678     raeburn  5368:     my %grouproles = ();
                   5369:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5370:         my @groupkeys; 
1.1000    raeburn  5371:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5372:             push(@groupkeys,$role);
                   5373:         }
                   5374:         if (ref($groups_roles) eq 'HASH') {
                   5375:             foreach my $key (keys(%{$groups_roles})) {
                   5376:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5377:                     push(@groupkeys,$key);
                   5378:                 }
                   5379:             }
                   5380:         }
                   5381:         if (@groupkeys > 0) {
                   5382:             foreach my $role (@groupkeys) {
                   5383:                 my ($trole,$area,$sec,$extendedarea);
                   5384:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5385:                     $trole = $1;
                   5386:                     $area = $2;
                   5387:                     $sec = $3;
                   5388:                     $extendedarea = $area.$sec;
                   5389:                     if (exists($$allgroups{$area})) {
                   5390:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5391:                             my $spec = $trole.'.'.$extendedarea;
                   5392:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5393:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5394:                         }
1.678     raeburn  5395:                     }
                   5396:                 }
                   5397:             }
                   5398:         }
                   5399:     }
1.800     albertel 5400:     foreach my $group (keys(%grouproles)) {
                   5401:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5402:     }
1.800     albertel 5403:     foreach my $role (keys(%{$allroles})) {
                   5404:         my %thesepriv;
1.941     raeburn  5405:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5406:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5407:             if ($item ne '') {
                   5408:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5409:                 if ($restrictions eq '') {
                   5410:                     $thesepriv{$privilege}='F';
                   5411:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5412:                     $thesepriv{$privilege}.=$restrictions;
                   5413:                 }
                   5414:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5415:             }
                   5416:         }
                   5417:         my $thesestr='';
1.1104    raeburn  5418:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5419: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5420: 	}
                   5421:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5422:     }
                   5423:     return ($author,$adv);
                   5424: }
                   5425: 
1.994     raeburn  5426: sub role_status {
1.1104    raeburn  5427:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5428:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5429:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5430:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5431:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5432:             $$where = '/'.$two;
1.994     raeburn  5433:             $$trolecode=$$role.'.'.$$where;
                   5434:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5435:             $$tstatus='is';
1.1104    raeburn  5436:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5437:                 $$tstatus='future';
1.1034    raeburn  5438:                 if ($$tstart<$now) {
                   5439:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5440:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5441:                             my (%allroles,%allgroups,$group_privs,
                   5442:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5443:                             my %userroles = (
                   5444:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5445:                             );
1.1064    raeburn  5446:                             @rolecodes = ('cm'); 
1.1002    raeburn  5447:                             my $spec=$$role.'.'.$$where;
                   5448:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5449:                             if ($$role =~ /^cr\//) {
                   5450:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5451:                                 push(@rolecodes,'cr');
1.1002    raeburn  5452:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5453:                                 push(@rolecodes,$$role);
1.1002    raeburn  5454:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5455:                                                     $env{'user.name'});
1.1064    raeburn  5456:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5457:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5458:                                 $group_privs = &unescape($group_privs);
                   5459:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5460:                                 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  5461:                                 &get_groups_roles($tdomain,$trest,
                   5462:                                                   \%course_roles,\@rolecodes,
                   5463:                                                   \%groups_roles);
1.1002    raeburn  5464:                             } else {
1.1064    raeburn  5465:                                 push(@rolecodes,$$role);
1.1002    raeburn  5466:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5467:                             }
1.1064    raeburn  5468:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5469:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5470:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5471:                         }
                   5472:                     }
1.1034    raeburn  5473:                     $$tstatus = 'is';
1.1002    raeburn  5474:                 }
1.994     raeburn  5475:             }
                   5476:             if ($$tend) {
1.1104    raeburn  5477:                 if ($$tend<$update) {
1.994     raeburn  5478:                     $$tstatus='expired';
                   5479:                 } elsif ($$tend<$now) {
                   5480:                     $$tstatus='will_not';
                   5481:                 }
                   5482:             }
                   5483:         }
                   5484:     }
                   5485: }
                   5486: 
1.1104    raeburn  5487: sub get_groups_roles {
                   5488:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5489:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5490:                   (ref($rolecodes) eq 'ARRAY') && 
                   5491:                   (ref($groups_roles) eq 'HASH')); 
                   5492:     if (keys(%{$cdom_courseroles}) > 0) {
                   5493:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5494:         if ($cdom ne '' && $cnum ne '') {
                   5495:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5496:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5497:                     my $crsrole = $1;
                   5498:                     my $crssec = $2;
                   5499:                     if ($crsrole =~ /^cr/) {
                   5500:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5501:                             push(@{$rolecodes},'cr');
                   5502:                         }
                   5503:                     } else {
                   5504:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5505:                             push(@{$rolecodes},$crsrole);
                   5506:                         }
                   5507:                     }
                   5508:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5509:                     if ($crssec ne '') {
                   5510:                         $rolekey .= "/$crssec";
                   5511:                     }
                   5512:                     $rolekey .= './';
                   5513:                     $groups_roles->{$rolekey} = $rolecodes;
                   5514:                 }
                   5515:             }
                   5516:         }
                   5517:     }
                   5518:     return;
                   5519: }
                   5520: 
                   5521: sub delete_env_groupprivs {
                   5522:     my ($where,$courseroles,$possroles) = @_;
                   5523:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5524:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5525:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5526:         %{$courseroles->{$udom}} =
                   5527:             &get_my_roles('','','userroles',['active'],
                   5528:                           $possroles,[$udom],1);
                   5529:     }
                   5530:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5531:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5532:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5533:             my $area = '/'.$cdom.'/'.$cnum;
                   5534:             my $privkey = "user.priv.$crsrole.$area";
                   5535:             if ($crssec ne '') {
                   5536:                 $privkey .= '/'.$crssec;
                   5537:             }
                   5538:             $privkey .= ".$area/$group";
                   5539:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5540:         }
                   5541:     }
                   5542:     return;
                   5543: }
                   5544: 
1.994     raeburn  5545: sub check_adhoc_privs {
1.1104    raeburn  5546:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5547:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5548:     my $setprivs;
1.994     raeburn  5549:     if ($env{$cckey}) {
                   5550:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5551:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5552:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5553:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5554:             $setprivs = 1;
1.994     raeburn  5555:         }
                   5556:     } else {
1.1088    raeburn  5557:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5558:         $setprivs = 1;
1.994     raeburn  5559:     }
1.1185    raeburn  5560:     return $setprivs;
1.994     raeburn  5561: }
                   5562: 
                   5563: sub set_adhoc_privileges {
                   5564: # role can be cc or ca
1.1088    raeburn  5565:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5566:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5567:     my $spec = $role.'.'.$area;
                   5568:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5569:                                   $env{'user.name'},1);
1.994     raeburn  5570:     my %ccrole = ();
                   5571:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5572:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5573:     &appenv(\%userroles,[$role,'cm']);
                   5574:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5575:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5576:         &appenv( {'request.role'        => $spec,
                   5577:                   'request.role.domain' => $dcdom,
                   5578:                   'request.course.sec'  => ''
                   5579:                  }
                   5580:                );
                   5581:         my $tadv=0;
                   5582:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5583:         &appenv({'request.role.adv'    => $tadv});
                   5584:     }
1.994     raeburn  5585: }
                   5586: 
1.12      www      5587: # --------------------------------------------------------------- get interface
                   5588: 
                   5589: sub get {
1.131     albertel 5590:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5591:    my $items='';
1.800     albertel 5592:    foreach my $item (@$storearr) {
                   5593:        $items.=&escape($item).'&';
1.191     harris41 5594:    }
1.12      www      5595:    $items=~s/\&$//;
1.620     albertel 5596:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5597:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5598:    my $uhome=&homeserver($uname,$udomain);
                   5599: 
1.133     albertel 5600:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5601:    my @pairs=split(/\&/,$rep);
1.273     albertel 5602:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5603:      return @pairs;
                   5604:    }
1.15      www      5605:    my %returnhash=();
1.42      www      5606:    my $i=0;
1.800     albertel 5607:    foreach my $item (@$storearr) {
                   5608:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5609:       $i++;
1.191     harris41 5610:    }
1.15      www      5611:    return %returnhash;
1.27      www      5612: }
                   5613: 
                   5614: # --------------------------------------------------------------- del interface
                   5615: 
                   5616: sub del {
1.133     albertel 5617:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5618:    my $items='';
1.800     albertel 5619:    foreach my $item (@$storearr) {
                   5620:        $items.=&escape($item).'&';
1.191     harris41 5621:    }
1.984     neumanie 5622: 
1.27      www      5623:    $items=~s/\&$//;
1.620     albertel 5624:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5625:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5626:    my $uhome=&homeserver($uname,$udomain);
                   5627:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5628: }
                   5629: 
                   5630: # -------------------------------------------------------------- dump interface
                   5631: 
1.1180    droeschl 5632: sub unserialize {
                   5633:     my ($rep, $escapedkeys) = @_;
                   5634: 
                   5635:     return {} if $rep =~ /^error/;
                   5636: 
                   5637:     my %returnhash=();
1.1252    raeburn  5638: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5639: 	    my ($key, $value) = split(/=/, $item, 2);
                   5640: 	    $key = unescape($key) unless $escapedkeys;
                   5641: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5642: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5643: 	}
                   5644:     #return %returnhash;
                   5645:     return \%returnhash;
                   5646: }        
                   5647: 
                   5648: # see Lond::dump_with_regexp
                   5649: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5650: sub dump {
1.1180    droeschl 5651:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5652:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5653:     if (!$uname) { $uname=$env{'user.name'}; }
                   5654:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5655: 
1.1266    raeburn  5656:     if ($regexp) {
                   5657:         $regexp=&escape($regexp);
                   5658:     } else {
                   5659:         $regexp='.';
                   5660:     }
1.1180    droeschl 5661:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5662:         # user is hosted on this machine
1.1266    raeburn  5663:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5664:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5665:         return %{unserialize($reply, $escapedkeys)};
                   5666:     }
1.1166    raeburn  5667:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5668:     my @pairs=split(/\&/,$rep);
                   5669:     my %returnhash=();
1.1098    foxr     5670:     if (!($rep =~ /^error/ )) {
                   5671: 	foreach my $item (@pairs) {
                   5672: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5673:         $key = unescape($key) unless $escapedkeys;
                   5674:         #$key = &unescape($key);
1.1098    foxr     5675: 	    next if ($key =~ /^error: 2 /);
                   5676: 	    $returnhash{$key}=&thaw_unescape($value);
                   5677: 	}
1.755     albertel 5678:     }
                   5679:     return %returnhash;
1.407     www      5680: }
                   5681: 
1.1098    foxr     5682: 
1.717     albertel 5683: # --------------------------------------------------------- dumpstore interface
                   5684: 
                   5685: sub dumpstore {
                   5686:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5687:    # same as dump but keys must be escaped. They may contain colon separated
                   5688:    # lists of values that may themself contain colons (e.g. symbs).
                   5689:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5690: }
                   5691: 
1.407     www      5692: # -------------------------------------------------------------- keys interface
                   5693: 
                   5694: sub getkeys {
                   5695:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5696:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5697:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5698:    my $uhome=&homeserver($uname,$udomain);
                   5699:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5700:    my @keyarray=();
1.800     albertel 5701:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5702:       next if ($key =~ /^error: 2 /);
1.800     albertel 5703:       push(@keyarray,&unescape($key));
1.407     www      5704:    }
                   5705:    return @keyarray;
1.318     matthew  5706: }
                   5707: 
1.319     matthew  5708: # --------------------------------------------------------------- currentdump
                   5709: sub currentdump {
1.328     matthew  5710:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5711:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5712:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5713:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5714:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5715:    my $rep;
                   5716: 
                   5717:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5718:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5719:                    $courseid)));
                   5720:    } else {
                   5721:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5722:    }
                   5723: 
1.318     matthew  5724:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5725:    #
1.318     matthew  5726:    my %returnhash=();
1.319     matthew  5727:    #
                   5728:    if ($rep eq "unknown_cmd") { 
                   5729:        # an old lond will not know currentdump
                   5730:        # Do a dump and make it look like a currentdump
1.822     albertel 5731:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5732:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5733:        my %hash = @tmp;
                   5734:        @tmp=();
1.424     matthew  5735:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5736:    } else {
                   5737:        my @pairs=split(/\&/,$rep);
1.800     albertel 5738:        foreach my $pair (@pairs) {
                   5739:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5740:            my ($symb,$param) = split(/:/,$key);
                   5741:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5742:                                                         &thaw_unescape($value);
1.319     matthew  5743:        }
1.191     harris41 5744:    }
1.12      www      5745:    return %returnhash;
1.424     matthew  5746: }
                   5747: 
                   5748: sub convert_dump_to_currentdump{
                   5749:     my %hash = %{shift()};
                   5750:     my %returnhash;
                   5751:     # Code ripped from lond, essentially.  The only difference
                   5752:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5753:     # we might run in to problems with parameter names =~ /^v\./
                   5754:     while (my ($key,$value) = each(%hash)) {
                   5755:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5756: 	$symb  = &unescape($symb);
                   5757: 	$param = &unescape($param);
1.424     matthew  5758:         next if ($v eq 'version' || $symb eq 'keys');
                   5759:         next if (exists($returnhash{$symb}) &&
                   5760:                  exists($returnhash{$symb}->{$param}) &&
                   5761:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5762:         $returnhash{$symb}->{$param}=$value;
                   5763:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5764:     }
                   5765:     #
                   5766:     # Remove all of the keys in the hashes which keep track of
                   5767:     # the version of the parameter.
                   5768:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5769:         # use a foreach because we are going to delete from the hash.
                   5770:         foreach my $key (keys(%$param_hash)) {
                   5771:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5772:         }
                   5773:     }
                   5774:     return \%returnhash;
1.12      www      5775: }
                   5776: 
1.627     albertel 5777: # ------------------------------------------------------ critical inc interface
                   5778: 
                   5779: sub cinc {
                   5780:     return &inc(@_,'critical');
                   5781: }
                   5782: 
1.449     matthew  5783: # --------------------------------------------------------------- inc interface
                   5784: 
                   5785: sub inc {
1.627     albertel 5786:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5787:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5788:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5789:     my $uhome=&homeserver($uname,$udomain);
                   5790:     my $items='';
                   5791:     if (! ref($store)) {
                   5792:         # got a single value, so use that instead
                   5793:         $items = &escape($store).'=&';
                   5794:     } elsif (ref($store) eq 'SCALAR') {
                   5795:         $items = &escape($$store).'=&';        
                   5796:     } elsif (ref($store) eq 'ARRAY') {
                   5797:         $items = join('=&',map {&escape($_);} @{$store});
                   5798:     } elsif (ref($store) eq 'HASH') {
                   5799:         while (my($key,$value) = each(%{$store})) {
                   5800:             $items.= &escape($key).'='.&escape($value).'&';
                   5801:         }
                   5802:     }
                   5803:     $items=~s/\&$//;
1.627     albertel 5804:     if ($critical) {
                   5805: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5806:     } else {
                   5807: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5808:     }
1.449     matthew  5809: }
                   5810: 
1.12      www      5811: # --------------------------------------------------------------- put interface
                   5812: 
                   5813: sub put {
1.134     albertel 5814:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5815:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5816:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5817:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5818:    my $items='';
1.800     albertel 5819:    foreach my $item (keys(%$storehash)) {
                   5820:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5821:    }
1.12      www      5822:    $items=~s/\&$//;
1.134     albertel 5823:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5824: }
                   5825: 
1.631     albertel 5826: # ------------------------------------------------------------ newput interface
                   5827: 
                   5828: sub newput {
                   5829:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5830:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5831:    if (!$uname) { $uname=$env{'user.name'}; }
                   5832:    my $uhome=&homeserver($uname,$udomain);
                   5833:    my $items='';
                   5834:    foreach my $key (keys(%$storehash)) {
                   5835:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5836:    }
                   5837:    $items=~s/\&$//;
                   5838:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5839: }
                   5840: 
                   5841: # ---------------------------------------------------------  putstore interface
                   5842: 
1.524     raeburn  5843: sub putstore {
1.1269    raeburn  5844:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 5845:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5846:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5847:    my $uhome=&homeserver($uname,$udomain);
                   5848:    my $items='';
1.715     albertel 5849:    foreach my $key (keys(%$storehash)) {
                   5850:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5851:    }
1.715     albertel 5852:    $items=~s/\&$//;
1.716     albertel 5853:    my $esc_symb=&escape($symb);
                   5854:    my $esc_v=&escape($version);
1.715     albertel 5855:    my $reply =
1.716     albertel 5856:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5857: 	      $uhome);
1.1269    raeburn  5858:    if (($tolog) && ($reply eq 'ok')) {
                   5859:        my $namevalue='';
                   5860:        foreach my $key (keys(%{$storehash})) {
                   5861:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   5862:        }
                   5863:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   5864:                      '&host='.&escape($perlvar{'lonHostID'}).
                   5865:                      '&version='.$esc_v.
                   5866:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   5867:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   5868:    }
1.715     albertel 5869:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5870:        # gfall back to way things use to be done
1.715     albertel 5871:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5872: 			    $uname);
1.524     raeburn  5873:    }
1.715     albertel 5874:    return $reply;
                   5875: }
                   5876: 
                   5877: sub old_putstore {
1.716     albertel 5878:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5879:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5880:     if (!$uname) { $uname=$env{'user.name'}; }
                   5881:     my $uhome=&homeserver($uname,$udomain);
                   5882:     my %newstorehash;
1.800     albertel 5883:     foreach my $item (keys(%$storehash)) {
                   5884: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5885: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5886:     }
                   5887:     my $items='';
                   5888:     my %allitems = ();
1.800     albertel 5889:     foreach my $item (keys(%newstorehash)) {
                   5890: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5891: 	    my $key = $1.':keys:'.$2;
                   5892: 	    $allitems{$key} .= $3.':';
                   5893: 	}
1.800     albertel 5894: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5895:     }
1.800     albertel 5896:     foreach my $item (keys(%allitems)) {
                   5897: 	$allitems{$item} =~ s/\:$//;
                   5898: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5899:     }
                   5900:     $items=~s/\&$//;
                   5901:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5902: }
                   5903: 
1.47      www      5904: # ------------------------------------------------------ critical put interface
                   5905: 
                   5906: sub cput {
1.134     albertel 5907:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5908:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5909:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5910:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5911:    my $items='';
1.800     albertel 5912:    foreach my $item (keys(%$storehash)) {
                   5913:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5914:    }
1.47      www      5915:    $items=~s/\&$//;
1.134     albertel 5916:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5917: }
                   5918: 
                   5919: # -------------------------------------------------------------- eget interface
                   5920: 
                   5921: sub eget {
1.133     albertel 5922:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5923:    my $items='';
1.800     albertel 5924:    foreach my $item (@$storearr) {
                   5925:        $items.=&escape($item).'&';
1.191     harris41 5926:    }
1.12      www      5927:    $items=~s/\&$//;
1.620     albertel 5928:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5929:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5930:    my $uhome=&homeserver($uname,$udomain);
                   5931:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5932:    my @pairs=split(/\&/,$rep);
                   5933:    my %returnhash=();
1.42      www      5934:    my $i=0;
1.800     albertel 5935:    foreach my $item (@$storearr) {
                   5936:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5937:       $i++;
1.191     harris41 5938:    }
1.12      www      5939:    return %returnhash;
                   5940: }
                   5941: 
1.667     albertel 5942: # ------------------------------------------------------------ tmpput interface
                   5943: sub tmpput {
1.802     raeburn  5944:     my ($storehash,$server,$context)=@_;
1.667     albertel 5945:     my $items='';
1.800     albertel 5946:     foreach my $item (keys(%$storehash)) {
                   5947: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5948:     }
                   5949:     $items=~s/\&$//;
1.802     raeburn  5950:     if (defined($context)) {
                   5951:         $items .= ':'.&escape($context);
                   5952:     }
1.667     albertel 5953:     return &reply("tmpput:$items",$server);
                   5954: }
                   5955: 
                   5956: # ------------------------------------------------------------ tmpget interface
                   5957: sub tmpget {
1.688     albertel 5958:     my ($token,$server)=@_;
                   5959:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5960:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5961:     my %returnhash;
                   5962:     foreach my $item (split(/\&/,$rep)) {
                   5963: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5964:         next if ($key =~ /^error: 2 /);
1.667     albertel 5965: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5966:     }
                   5967:     return %returnhash;
                   5968: }
                   5969: 
1.1113    raeburn  5970: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5971: sub tmpdel {
                   5972:     my ($token,$server)=@_;
                   5973:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5974:     return &reply("tmpdel:$token",$server);
                   5975: }
                   5976: 
1.1198    raeburn  5977: # ------------------------------------------------------------ get_timebased_id 
                   5978: 
                   5979: sub get_timebased_id {
                   5980:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5981:         $maxtries) = @_;
                   5982:     my ($newid,$error,$dellock);
                   5983:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5984:         return ('','ok','invalid call to get suffix');
                   5985:     }
                   5986: 
                   5987: # set defaults for any optional args for which values were not supplied
                   5988:     if ($who eq '') {
                   5989:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5990:     }
                   5991:     if (!$locktries) {
                   5992:         $locktries = 3;
                   5993:     }
                   5994:     if (!$maxtries) {
                   5995:         $maxtries = 10;
                   5996:     }
                   5997:     
                   5998:     if (($cdom eq '') || ($cnum eq '')) {
                   5999:         if ($env{'request.course.id'}) {
                   6000:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6001:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6002:         }
                   6003:         if (($cdom eq '') || ($cnum eq '')) {
                   6004:             return ('','ok','call to get suffix not in course context');
                   6005:         }
                   6006:     }
                   6007: 
                   6008: # construct locking item
                   6009:     my $lockhash = {
                   6010:                       $prefix."\0".'locked_'.$keyid => $who,
                   6011:                    };
                   6012:     my $tries = 0;
                   6013: 
                   6014: # attempt to get lock on nohist_$namespace file
                   6015:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6016:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6017:         $tries ++;
                   6018:         sleep 1;
                   6019:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6020:     }
                   6021: 
                   6022: # attempt to get unique identifier, based on current timestamp
                   6023:     if ($gotlock eq 'ok') {
                   6024:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6025:         my $id = time;
                   6026:         $newid = $id;
1.1268    raeburn  6027:         if ($idtype eq 'addcode') {
                   6028:             $newid .= &sixnum_code();
                   6029:         }
1.1198    raeburn  6030:         my $idtries = 0;
                   6031:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6032:             if ($idtype eq 'concat') {
                   6033:                 $newid = $id.$idtries;
1.1268    raeburn  6034:             } elsif ($idtype eq 'addcode') {
                   6035:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6036:             } else {
                   6037:                 $newid ++;
                   6038:             }
                   6039:             $idtries ++;
                   6040:         }
                   6041:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6042:             my %new_item =  (
                   6043:                               $prefix."\0".$newid => $who,
                   6044:                             );
                   6045:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6046:                                                  $cdom,$cnum);
                   6047:             if ($putresult ne 'ok') {
                   6048:                 undef($newid);
                   6049:                 $error = 'error saving new item: '.$putresult;
                   6050:             }
                   6051:         } else {
1.1268    raeburn  6052:              undef($newid);
1.1198    raeburn  6053:              $error = ('error: no unique suffix available for the new item ');
                   6054:         }
                   6055: #  remove lock
                   6056:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6057:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6058:     } else {
                   6059:         $error = "error: could not obtain lockfile\n";
                   6060:         $dellock = 'ok';
1.1276    raeburn  6061:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6062:             $dellock = 'nolock';
                   6063:         }
1.1198    raeburn  6064:     }
                   6065:     return ($newid,$dellock,$error);
                   6066: }
                   6067: 
1.1268    raeburn  6068: sub sixnum_code {
                   6069:     my $code;
                   6070:     for (0..6) {
                   6071:         $code .= int( rand(9) );
                   6072:     }
                   6073:     return $code;
                   6074: }
                   6075: 
1.765     albertel 6076: # -------------------------------------------------- portfolio access checking
                   6077: 
                   6078: sub portfolio_access {
1.1270    raeburn  6079:     my ($requrl,$clientip) = @_;
1.765     albertel 6080:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6081:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6082:     if ($result) {
                   6083:         my %setters;
                   6084:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6085:             my ($startblock,$endblock) =
                   6086:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6087:             if ($startblock && $endblock) {
                   6088:                 return 'B';
                   6089:             }
                   6090:         } else {
                   6091:             my ($startblock,$endblock) =
                   6092:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6093:             if ($startblock && $endblock) {
                   6094:                 return 'B';
                   6095:             }
                   6096:         }
                   6097:     }
1.765     albertel 6098:     if ($result eq 'ok') {
1.766     albertel 6099:        return 'F';
1.765     albertel 6100:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6101:        return 'A';
1.765     albertel 6102:     }
1.766     albertel 6103:     return '';
1.765     albertel 6104: }
                   6105: 
                   6106: sub get_portfolio_access {
1.1270    raeburn  6107:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6108: 
                   6109:     if (!ref($access_hash)) {
                   6110: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6111: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6112: 						   $file_name);
                   6113: 	$access_hash = $access_controls{$file_name};
                   6114:     }
                   6115: 
1.1270    raeburn  6116:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6117:     my $now = time;
                   6118:     if (ref($access_hash) eq 'HASH') {
                   6119:         foreach my $key (keys(%{$access_hash})) {
                   6120:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6121:             if ($start > $now) {
                   6122:                 next;
                   6123:             }
                   6124:             if ($end && $end<$now) {
                   6125:                 next;
                   6126:             }
                   6127:             if ($scope eq 'public') {
                   6128:                 $public = $key;
                   6129:                 last;
                   6130:             } elsif ($scope eq 'guest') {
                   6131:                 $guest = $key;
                   6132:             } elsif ($scope eq 'domains') {
                   6133:                 push(@domains,$key);
                   6134:             } elsif ($scope eq 'users') {
                   6135:                 push(@users,$key);
                   6136:             } elsif ($scope eq 'course') {
                   6137:                 push(@courses,$key);
                   6138:             } elsif ($scope eq 'group') {
                   6139:                 push(@groups,$key);
1.1270    raeburn  6140:             } elsif ($scope eq 'ip') {
                   6141:                 push(@ips,$key);
1.765     albertel 6142:             }
                   6143:         }
                   6144:         if ($public) {
                   6145:             return 'ok';
1.1270    raeburn  6146:         } elsif (@ips > 0) {
                   6147:             my $allowed;
                   6148:             foreach my $ipkey (@ips) {
                   6149:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6150:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6151:                         $allowed = 1;
                   6152:                         last; 
                   6153:                     }
                   6154:                 }
                   6155:             }
                   6156:             if ($allowed) {
                   6157:                 return 'ok';
                   6158:             }
1.765     albertel 6159:         }
                   6160:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6161:             if ($guest) {
                   6162:                 return $guest;
                   6163:             }
                   6164:         } else {
                   6165:             if (@domains > 0) {
                   6166:                 foreach my $domkey (@domains) {
                   6167:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6168:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6169:                             return 'ok';
                   6170:                         }
                   6171:                     }
                   6172:                 }
                   6173:             }
                   6174:             if (@users > 0) {
                   6175:                 foreach my $userkey (@users) {
1.865     raeburn  6176:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6177:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6178:                             if (ref($item) eq 'HASH') {
                   6179:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6180:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6181:                                     return 'ok';
                   6182:                                 }
                   6183:                             }
                   6184:                         }
                   6185:                     } 
1.765     albertel 6186:                 }
                   6187:             }
                   6188:             my %roleshash;
                   6189:             my @courses_and_groups = @courses;
                   6190:             push(@courses_and_groups,@groups); 
                   6191:             if (@courses_and_groups > 0) {
                   6192:                 my (%allgroups,%allroles); 
                   6193:                 my ($start,$end,$role,$sec,$group);
                   6194:                 foreach my $envkey (%env) {
1.1060    raeburn  6195:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6196:                         my $cid = $2.'_'.$3; 
                   6197:                         if ($1 eq 'gr') {
                   6198:                             $group = $4;
                   6199:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6200:                         } else {
                   6201:                             if ($4 eq '') {
                   6202:                                 $sec = 'none';
                   6203:                             } else {
                   6204:                                 $sec = $4;
                   6205:                             }
                   6206:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6207:                         }
1.811     albertel 6208:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6209:                         my $cid = $2.'_'.$3;
                   6210:                         if ($4 eq '') {
                   6211:                             $sec = 'none';
                   6212:                         } else {
                   6213:                             $sec = $4;
                   6214:                         }
                   6215:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6216:                     }
                   6217:                 }
                   6218:                 if (keys(%allroles) == 0) {
                   6219:                     return;
                   6220:                 }
                   6221:                 foreach my $key (@courses_and_groups) {
                   6222:                     my %content = %{$$access_hash{$key}};
                   6223:                     my $cnum = $content{'number'};
                   6224:                     my $cdom = $content{'domain'};
                   6225:                     my $cid = $cdom.'_'.$cnum;
                   6226:                     if (!exists($allroles{$cid})) {
                   6227:                         next;
                   6228:                     }    
                   6229:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6230:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6231:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6232:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6233:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6234:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6235:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6236:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6237:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6238:                                         if (grep/^all$/,@sections) {
                   6239:                                             return 'ok';
                   6240:                                         } else {
                   6241:                                             if (grep/^$sec$/,@sections) {
                   6242:                                                 return 'ok';
                   6243:                                             }
                   6244:                                         }
                   6245:                                     }
                   6246:                                 }
                   6247:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6248:                                     if (grep/^none$/,@groups) {
                   6249:                                         return 'ok';
                   6250:                                     }
                   6251:                                 } else {
                   6252:                                     if (grep/^all$/,@groups) {
                   6253:                                         return 'ok';
                   6254:                                     } 
                   6255:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6256:                                         if (grep/^$group$/,@groups) {
                   6257:                                             return 'ok';
                   6258:                                         }
                   6259:                                     }
                   6260:                                 } 
                   6261:                             }
                   6262:                         }
                   6263:                     }
                   6264:                 }
                   6265:             }
                   6266:             if ($guest) {
                   6267:                 return $guest;
                   6268:             }
                   6269:         }
                   6270:     }
                   6271:     return;
                   6272: }
                   6273: 
                   6274: sub course_group_datechecker {
                   6275:     my ($dates,$now,$status) = @_;
                   6276:     my ($start,$end) = split(/\./,$dates);
                   6277:     if (!$start && !$end) {
                   6278:         return 'ok';
                   6279:     }
                   6280:     if (grep/^active$/,@{$status}) {
                   6281:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6282:             return 'ok';
                   6283:         }
                   6284:     }
                   6285:     if (grep/^previous$/,@{$status}) {
                   6286:         if ($end > $now ) {
                   6287:             return 'ok';
                   6288:         }
                   6289:     }
                   6290:     if (grep/^future$/,@{$status}) {
                   6291:         if ($start > $now) {
                   6292:             return 'ok';
                   6293:         }
                   6294:     }
                   6295:     return; 
                   6296: }
                   6297: 
                   6298: sub parse_portfolio_url {
                   6299:     my ($url) = @_;
                   6300: 
                   6301:     my ($type,$udom,$unum,$group,$file_name);
                   6302:     
1.823     albertel 6303:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6304: 	$type = 1;
                   6305:         $udom = $1;
                   6306:         $unum = $2;
                   6307:         $file_name = $3;
1.823     albertel 6308:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6309: 	$type = 2;
                   6310:         $udom = $1;
                   6311:         $unum = $2;
                   6312:         $group = $3;
                   6313:         $file_name = $3.'/'.$4;
                   6314:     }
                   6315:     if (wantarray) {
                   6316: 	return ($type,$udom,$unum,$file_name,$group);
                   6317:     }
                   6318:     return $type;
                   6319: }
                   6320: 
                   6321: sub is_portfolio_url {
                   6322:     my ($url) = @_;
                   6323:     return scalar(&parse_portfolio_url($url));
                   6324: }
                   6325: 
1.798     raeburn  6326: sub is_portfolio_file {
                   6327:     my ($file) = @_;
1.820     raeburn  6328:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6329:         return 1;
                   6330:     }
                   6331:     return;
                   6332: }
                   6333: 
1.976     raeburn  6334: sub usertools_access {
1.1084    raeburn  6335:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6336:     my ($access,%tools);
                   6337:     if ($context eq '') {
                   6338:         $context = 'tools';
                   6339:     }
                   6340:     if ($context eq 'requestcourses') {
                   6341:         %tools = (
                   6342:                       official   => 1,
                   6343:                       unofficial => 1,
1.1006    raeburn  6344:                       community  => 1,
1.1246    raeburn  6345:                       textbook   => 1,
1.985     raeburn  6346:                  );
1.1183    raeburn  6347:     } elsif ($context eq 'requestauthor') {
                   6348:         %tools = (
                   6349:                       requestauthor => 1,
                   6350:                  );
1.985     raeburn  6351:     } else {
                   6352:         %tools = (
                   6353:                       aboutme   => 1,
                   6354:                       blog      => 1,
1.1177    raeburn  6355:                       webdav    => 1,
1.985     raeburn  6356:                       portfolio => 1,
                   6357:                  );
                   6358:     }
1.976     raeburn  6359:     return if (!defined($tools{$tool}));
                   6360: 
1.1242    raeburn  6361:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6362:         $udom = $env{'user.domain'};
                   6363:         $uname = $env{'user.name'};
                   6364:     }
                   6365: 
1.978     raeburn  6366:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6367:         if ($action ne 'reload') {
1.985     raeburn  6368:             if ($context eq 'requestcourses') {
                   6369:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6370:             } elsif ($context eq 'requestauthor') {
                   6371:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6372:             } else {
                   6373:                 return $env{'environment.availabletools.'.$tool};
                   6374:             }
                   6375:         }
1.976     raeburn  6376:     }
                   6377: 
1.1183    raeburn  6378:     my ($toolstatus,$inststatus,$envkey);
                   6379:     if ($context eq 'requestauthor') {
                   6380:         $envkey = $context; 
                   6381:     } else {
                   6382:         $envkey = $context.'.'.$tool;
                   6383:     }
1.976     raeburn  6384: 
1.985     raeburn  6385:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6386:          ($action ne 'reload')) {
1.1183    raeburn  6387:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6388:         $inststatus = $env{'environment.inststatus'};
                   6389:     } else {
1.1084    raeburn  6390:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6391:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6392:             $inststatus = $userenvref->{'inststatus'};
                   6393:         } else {
1.1183    raeburn  6394:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6395:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6396:             $inststatus = $userenv{'inststatus'};
                   6397:         }
1.976     raeburn  6398:     }
                   6399: 
                   6400:     if ($toolstatus ne '') {
                   6401:         if ($toolstatus) {
                   6402:             $access = 1;
                   6403:         } else {
                   6404:             $access = 0;
                   6405:         }
                   6406:         return $access;
                   6407:     }
                   6408: 
1.1084    raeburn  6409:     my ($is_adv,%domdef);
                   6410:     if (ref($is_advref) eq 'HASH') {
                   6411:         $is_adv = $is_advref->{'is_adv'};
                   6412:     } else {
                   6413:         $is_adv = &is_advanced_user($udom,$uname);
                   6414:     }
                   6415:     if (ref($domdefref) eq 'HASH') {
                   6416:         %domdef = %{$domdefref};
                   6417:     } else {
                   6418:         %domdef = &get_domain_defaults($udom);
                   6419:     }
1.976     raeburn  6420:     if (ref($domdef{$tool}) eq 'HASH') {
                   6421:         if ($is_adv) {
                   6422:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6423:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6424:                     $access = 1;
                   6425:                 } else {
                   6426:                     $access = 0;
                   6427:                 }
                   6428:                 return $access;
                   6429:             }
                   6430:         }
                   6431:         if ($inststatus ne '') {
                   6432:             my ($hasaccess,$hasnoaccess);
                   6433:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6434:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6435:                     if ($domdef{$tool}{$affiliation}) {
                   6436:                         $hasaccess = 1;
                   6437:                     } else {
                   6438:                         $hasnoaccess = 1;
                   6439:                     }
                   6440:                 }
                   6441:             }
                   6442:             if ($hasaccess || $hasnoaccess) {
                   6443:                 if ($hasaccess) {
                   6444:                     $access = 1;
                   6445:                 } elsif ($hasnoaccess) {
                   6446:                     $access = 0; 
                   6447:                 }
                   6448:                 return $access;
                   6449:             }
                   6450:         } else {
                   6451:             if ($domdef{$tool}{'default'} ne '') {
                   6452:                 if ($domdef{$tool}{'default'}) {
                   6453:                     $access = 1;
                   6454:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6455:                     $access = 0;
                   6456:                 }
                   6457:                 return $access;
                   6458:             }
                   6459:         }
                   6460:     } else {
1.1177    raeburn  6461:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6462:             $access = 1;
                   6463:         } else {
                   6464:             $access = 0;
                   6465:         }
1.976     raeburn  6466:         return $access;
                   6467:     }
                   6468: }
                   6469: 
1.1050    raeburn  6470: sub is_course_owner {
                   6471:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6472:     if (($udom eq '') || ($uname eq '')) {
                   6473:         $udom = $env{'user.domain'};
                   6474:         $uname = $env{'user.name'};
                   6475:     }
                   6476:     unless (($udom eq '') || ($uname eq '')) {
                   6477:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6478:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6479:                 return 1;
                   6480:             } else {
                   6481:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6482:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6483:                     return 1;
                   6484:                 }
                   6485:             }
                   6486:         }
                   6487:     }
                   6488:     return;
                   6489: }
                   6490: 
1.976     raeburn  6491: sub is_advanced_user {
                   6492:     my ($udom,$uname) = @_;
1.1085    raeburn  6493:     if ($udom ne '' && $uname ne '') {
                   6494:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6495:             if (wantarray) {
                   6496:                 return ($env{'user.adv'},$env{'user.author'});
                   6497:             } else {
                   6498:                 return $env{'user.adv'};
                   6499:             }
1.1085    raeburn  6500:         }
                   6501:     }
1.976     raeburn  6502:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6503:     my %allroles;
1.1128    raeburn  6504:     my ($is_adv,$is_author);
1.976     raeburn  6505:     foreach my $role (keys(%roleshash)) {
                   6506:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6507:         my $area = '/'.$tdomain.'/'.$trest;
                   6508:         if ($sec ne '') {
                   6509:             $area .= '/'.$sec;
                   6510:         }
                   6511:         if (($area ne '') && ($trole ne '')) {
                   6512:             my $spec=$trole.'.'.$area;
                   6513:             if ($trole =~ /^cr\//) {
                   6514:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6515:             } elsif ($trole ne 'gr') {
                   6516:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6517:             }
1.1128    raeburn  6518:             if ($trole eq 'au') {
                   6519:                 $is_author = 1;
                   6520:             }
1.976     raeburn  6521:         }
                   6522:     }
                   6523:     foreach my $role (keys(%allroles)) {
                   6524:         last if ($is_adv);
                   6525:         foreach my $item (split(/:/,$allroles{$role})) {
                   6526:             if ($item ne '') {
                   6527:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6528:                 if ($privilege eq 'adv') {
                   6529:                     $is_adv = 1;
                   6530:                     last;
                   6531:                 }
                   6532:             }
                   6533:         }
                   6534:     }
1.1128    raeburn  6535:     if (wantarray) {
                   6536:         return ($is_adv,$is_author);
                   6537:     }
1.976     raeburn  6538:     return $is_adv;
                   6539: }
1.798     raeburn  6540: 
1.1035    raeburn  6541: sub check_can_request {
1.1036    raeburn  6542:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6543:     my $canreq = 0;
                   6544:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6545:     my @options = ('approval','validate','autolimit');
                   6546:     my $optregex = join('|',@options);
                   6547:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6548:         foreach my $type (@{$types}) {
                   6549:             if (&usertools_access($env{'user.name'},
                   6550:                                   $env{'user.domain'},
                   6551:                                   $type,undef,'requestcourses')) {
                   6552:                 $canreq ++;
1.1036    raeburn  6553:                 if (ref($request_domains) eq 'HASH') {
                   6554:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6555:                 }
1.1035    raeburn  6556:                 if ($dom eq $env{'user.domain'}) {
                   6557:                     $can_request->{$type} = 1;
                   6558:                 }
                   6559:             }
                   6560:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6561:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6562:                 if (@curr > 0) {
1.1036    raeburn  6563:                     foreach my $item (@curr) {
                   6564:                         if (ref($request_domains) eq 'HASH') {
                   6565:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6566:                             if ($otherdom ne '') {
                   6567:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6568:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6569:                                         push(@{$request_domains->{$type}},$otherdom);
                   6570:                                     }
                   6571:                                 } else {
                   6572:                                     push(@{$request_domains->{$type}},$otherdom);
                   6573:                                 }
                   6574:                             }
                   6575:                         }
                   6576:                     }
                   6577:                     unless($dom eq $env{'user.domain'}) {
                   6578:                         $canreq ++;
1.1035    raeburn  6579:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6580:                             $can_request->{$type} = 1;
                   6581:                         }
                   6582:                     }
                   6583:                 }
                   6584:             }
                   6585:         }
                   6586:     }
                   6587:     return $canreq;
                   6588: }
                   6589: 
1.341     www      6590: # ---------------------------------------------- Custom access rule evaluation
                   6591: 
                   6592: sub customaccess {
                   6593:     my ($priv,$uri)=@_;
1.807     albertel 6594:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6595:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6596:     $udom = &LONCAPA::clean_domain($udom);
                   6597:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6598:     my $access=0;
1.800     albertel 6599:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6600: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6601: 	if ($type eq 'user') {
                   6602: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6603: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6604: 		if ($tdom) {
                   6605: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6606: 		}
1.896     albertel 6607: 		if ($tuname) {
                   6608: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6609: 		}
                   6610: 		$access=($effect eq 'allow');
                   6611: 		last;
                   6612: 	    }
                   6613: 	} else {
                   6614: 	    if ($role) {
                   6615: 		if ($role ne $urole) { next; }
                   6616: 	    }
                   6617: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6618: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6619: 		if ($tdom) {
                   6620: 		    if ($tdom ne $udom) { next; }
                   6621: 		}
                   6622: 		if ($tcrs) {
                   6623: 		    if ($tcrs ne $ucrs) { next; }
                   6624: 		}
                   6625: 		if ($tsec) {
                   6626: 		    if ($tsec ne $usec) { next; }
                   6627: 		}
                   6628: 		$access=($effect eq 'allow');
                   6629: 		last;
                   6630: 	    }
                   6631: 	    if ($realm eq '' && $role eq '') {
                   6632: 		$access=($effect eq 'allow');
                   6633: 	    }
1.402     bowersj2 6634: 	}
1.341     www      6635:     }
                   6636:     return $access;
                   6637: }
                   6638: 
1.103     harris41 6639: # ------------------------------------------------- Check for a user privilege
1.12      www      6640: 
                   6641: sub allowed {
1.1270    raeburn  6642:     my ($priv,$uri,$symb,$role,$clientip)=@_;
1.705     albertel 6643:     my $ver_orguri=$uri;
1.439     www      6644:     $uri=&deversion($uri);
1.152     www      6645:     my $orguri=$uri;
1.52      www      6646:     $uri=&declutter($uri);
1.809     raeburn  6647: 
1.810     raeburn  6648:     if ($priv eq 'evb') {
                   6649: # Evade communication block restrictions for specified role in a course
                   6650:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6651:             return $1;
                   6652:         } else {
                   6653:             return;
                   6654:         }
                   6655:     }
                   6656: 
1.620     albertel 6657:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6658: # Free bre access to adm and meta resources
1.775     albertel 6659:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6660: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6661: 	&& ($priv eq 'bre')) {
1.14      www      6662: 	return 'F';
1.159     www      6663:     }
                   6664: 
1.545     banghart 6665: # Free bre access to user's own portfolio contents
1.714     raeburn  6666:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6667:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6668: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6669:         my %setters;
                   6670:         my ($startblock,$endblock) = 
                   6671:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6672:         if ($startblock && $endblock) {
                   6673:             return 'B';
                   6674:         } else {
                   6675:             return 'F';
                   6676:         }
1.545     banghart 6677:     }
                   6678: 
1.762     raeburn  6679: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6680:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6681:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6682:         if (exists($env{'request.course.id'})) {
                   6683:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6684:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6685:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6686:                 my $courseprivid=$env{'request.course.id'};
                   6687:                 $courseprivid=~s/\_/\//;
                   6688:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6689:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6690:                     return $1; 
1.762     raeburn  6691:                 } else {
                   6692:                     if ($env{'request.course.sec'}) {
                   6693:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6694:                     }
                   6695:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6696:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6697:                         return $2;
                   6698:                     }
1.714     raeburn  6699:                 }
                   6700:             }
                   6701:         }
                   6702:     }
                   6703: 
1.159     www      6704: # Free bre to public access
                   6705: 
                   6706:     if ($priv eq 'bre') {
1.238     www      6707:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6708: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6709:            return 'F'; 
                   6710:         }
1.238     www      6711:         if ($copyright eq 'priv') {
                   6712:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6713: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6714: 		return '';
                   6715:             }
                   6716:         }
                   6717:         if ($copyright eq 'domain') {
                   6718:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6719: 	    unless (($env{'user.domain'} eq $1) ||
                   6720:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6721: 		return '';
                   6722:             }
1.262     matthew  6723:         }
1.620     albertel 6724:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6725:             # Library role, so allow browsing of resources in this domain.
                   6726:             return 'F';
1.238     www      6727:         }
1.341     www      6728:         if ($copyright eq 'custom') {
                   6729: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6730:         }
1.14      www      6731:     }
1.264     matthew  6732:     # Domain coordinator is trying to create a course
1.620     albertel 6733:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6734:         # uri is the requested domain in this case.
                   6735:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6736:         # a role of dc for the domain in question.
1.620     albertel 6737:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6738:     }
1.29      www      6739: 
1.52      www      6740:     my $thisallowed='';
                   6741:     my $statecond=0;
                   6742:     my $courseprivid='';
                   6743: 
1.1039    raeburn  6744:     my $ownaccess;
1.1043    raeburn  6745:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6746:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6747:         if ($uri eq '') {
                   6748:             $ownaccess = 1;
                   6749:         } else {
                   6750:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6751:                 my $udom = $env{'user.domain'};
                   6752:                 my $uname = $env{'user.name'};
                   6753:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6754:                     $ownaccess = 1;
1.1040    raeburn  6755:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6756:                     unless ($uri =~ m{\.\./}) {
                   6757:                         $ownaccess = 1;
                   6758:                     }
                   6759:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6760:                     my $now = time;
                   6761:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6762:                         my $adom = $1;
                   6763:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6764:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6765:                                 my ($start,$end) = split('.',$env{$key});
                   6766:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6767:                                     $ownaccess = 1;
                   6768:                                     last;
                   6769:                                 }
                   6770:                             }
                   6771:                         }
                   6772:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6773:                         my $adom = $1;
                   6774:                         my $aname = $2;
1.1042    raeburn  6775:                         foreach my $role ('ca','aa') { 
                   6776:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6777:                                 my ($start,$end) =
                   6778:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6779:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6780:                                     $ownaccess = 1;
                   6781:                                     last;
                   6782:                                 }
1.1039    raeburn  6783:                             }
                   6784:                         }
                   6785:                     }
                   6786:                 }
                   6787:             }
                   6788:         }
                   6789:     }
                   6790: 
1.52      www      6791: # Course
                   6792: 
1.620     albertel 6793:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6794:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6795:             $thisallowed.=$1;
                   6796:         }
1.52      www      6797:     }
1.29      www      6798: 
1.52      www      6799: # Domain
                   6800: 
1.620     albertel 6801:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6802:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6803:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6804:             $thisallowed.=$1;
                   6805:         }
1.12      www      6806:     }
1.52      www      6807: 
1.1141    raeburn  6808: # User who is not author or co-author might still be able to edit
                   6809: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6810:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6811:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6812:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6813:             $thisallowed.=$1;
                   6814:         }
                   6815:     }
                   6816: 
1.52      www      6817: # Course: uri itself is a course
1.66      www      6818:     my $courseuri=$uri;
                   6819:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6820:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6821: 
1.620     albertel 6822:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6823:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6824:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6825:             $thisallowed.=$1;
                   6826:         }
1.12      www      6827:     }
1.29      www      6828: 
1.665     albertel 6829: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6830: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6831:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6832: 	$thisallowed='';
1.671     raeburn  6833:         my ($match)=&is_on_map($uri);
                   6834:         if ($match) {
                   6835:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6836:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6837:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6838:                 if (@blockers > 0) {
                   6839:                     $thisallowed = 'B';
                   6840:                 } else {
                   6841:                     $thisallowed.=$1;
                   6842:                 }
1.671     raeburn  6843:             }
                   6844:         } else {
1.705     albertel 6845:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6846:             if ($refuri) {
                   6847:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6848:                     $thisallowed='F';
1.671     raeburn  6849:                 } else {
                   6850:                     $refuri=&declutter($refuri);
                   6851:                     my ($match) = &is_on_map($refuri);
                   6852:                     if ($match) {
1.1162    raeburn  6853:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6854:                         if (@blockers > 0) {
                   6855:                             $thisallowed = 'B';
                   6856:                         } else {
                   6857:                             $thisallowed='F';
                   6858:                         }
1.671     raeburn  6859:                     }
1.669     raeburn  6860:                 }
1.671     raeburn  6861:             }
                   6862:         }
1.314     www      6863:     }
1.492     albertel 6864: 
1.766     albertel 6865:     if ($priv eq 'bre'
                   6866: 	&& $thisallowed ne 'F' 
                   6867: 	&& $thisallowed ne '2'
                   6868: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  6869: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 6870:     }
1.1250    raeburn  6871: 
1.52      www      6872: # Full access at system, domain or course-wide level? Exit.
1.29      www      6873:     if ($thisallowed=~/F/) {
                   6874: 	return 'F';
                   6875:     }
                   6876: 
1.52      www      6877: # If this is generating or modifying users, exit with special codes
1.29      www      6878: 
1.643     www      6879:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6880: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6881: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6882: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6883: 	    unless ($auname) { return $thisallowed; }
                   6884: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6885: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6886: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6887: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6888: 	}
1.52      www      6889: 	return $thisallowed;
                   6890:     }
                   6891: #
1.103     harris41 6892: # Gathered so far: system, domain and course wide privileges
1.52      www      6893: #
                   6894: # Course: See if uri or referer is an individual resource that is part of 
                   6895: # the course
                   6896: 
1.620     albertel 6897:     if ($env{'request.course.id'}) {
1.232     www      6898: 
1.620     albertel 6899:        $courseprivid=$env{'request.course.id'};
                   6900:        if ($env{'request.course.sec'}) {
                   6901:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6902:        }
                   6903:        $courseprivid=~s/\_/\//;
                   6904:        my $checkreferer=1;
1.232     www      6905:        my ($match,$cond)=&is_on_map($uri);
                   6906:        if ($match) {
                   6907:            $statecond=$cond;
1.620     albertel 6908:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6909:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6910:                my $value = $1;
                   6911:                if ($priv eq 'bre') {
                   6912:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6913:                    if (@blockers > 0) {
                   6914:                        $thisallowed = 'B';
                   6915:                    } else {
                   6916:                        $thisallowed.=$value;
                   6917:                    }
                   6918:                } else {
                   6919:                    $thisallowed.=$value;
                   6920:                }
1.52      www      6921:                $checkreferer=0;
                   6922:            }
1.29      www      6923:        }
1.83      www      6924:        
1.148     www      6925:        if ($checkreferer) {
1.620     albertel 6926: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6927:             unless ($refuri) {
1.800     albertel 6928:                 foreach my $key (keys(%env)) {
                   6929: 		    if ($key=~/^httpref\..*\*/) {
                   6930: 			my $pattern=$key;
1.156     www      6931:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6932:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6933:                         $pattern=~s/\//\\\//g;
1.152     www      6934:                         if ($orguri=~/$pattern/) {
1.800     albertel 6935: 			    $refuri=$env{$key};
1.148     www      6936:                         }
                   6937:                     }
1.191     harris41 6938:                 }
1.148     www      6939:             }
1.232     www      6940: 
1.148     www      6941:          if ($refuri) { 
1.152     www      6942: 	  $refuri=&declutter($refuri);
1.232     www      6943:           my ($match,$cond)=&is_on_map($refuri);
                   6944:             if ($match) {
                   6945:               my $refstatecond=$cond;
1.620     albertel 6946:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6947:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6948:                   my $value = $1;
                   6949:                   if ($priv eq 'bre') {
                   6950:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6951:                       if (@blockers > 0) {
                   6952:                           $thisallowed = 'B';
                   6953:                       } else {
                   6954:                           $thisallowed.=$value;
                   6955:                       }
                   6956:                   } else {
                   6957:                       $thisallowed.=$value;
                   6958:                   }
1.53      www      6959:                   $uri=$refuri;
                   6960:                   $statecond=$refstatecond;
1.52      www      6961:               }
                   6962:           }
1.148     www      6963:         }
1.29      www      6964:        }
1.52      www      6965:    }
1.29      www      6966: 
1.52      www      6967: #
1.103     harris41 6968: # Gathered now: all privileges that could apply, and condition number
1.52      www      6969: # 
                   6970: #
                   6971: # Full or no access?
                   6972: #
1.29      www      6973: 
1.52      www      6974:     if ($thisallowed=~/F/) {
                   6975: 	return 'F';
                   6976:     }
1.29      www      6977: 
1.52      www      6978:     unless ($thisallowed) {
                   6979:         return '';
                   6980:     }
1.29      www      6981: 
1.52      www      6982: # Restrictions exist, deal with them
                   6983: #
                   6984: #   C:according to course preferences
                   6985: #   R:according to resource settings
                   6986: #   L:unless locked
                   6987: #   X:according to user session state
                   6988: #
                   6989: 
                   6990: # Possibly locked functionality, check all courses
1.54      www      6991: # Locks might take effect only after 10 minutes cache expiration for other
                   6992: # courses, and 2 minutes for current course
1.52      www      6993: 
                   6994:     my $envkey;
                   6995:     if ($thisallowed=~/L/) {
1.1000    raeburn  6996:         foreach $envkey (keys(%env)) {
1.54      www      6997:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6998:                my $courseid=$2;
                   6999:                my $roleid=$1.'.'.$2;
1.92      www      7000:                $courseid=~s/^\///;
1.54      www      7001:                my $expiretime=600;
1.620     albertel 7002:                if ($env{'request.role'} eq $roleid) {
1.54      www      7003: 		  $expiretime=120;
                   7004:                }
                   7005: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7006:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7007:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7008: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7009:                }
1.620     albertel 7010:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7011:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7012: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7013:                        &log($env{'user.domain'},$env{'user.name'},
                   7014:                             $env{'user.home'},
1.57      www      7015:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7016:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7017:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7018: 		       return '';
                   7019:                    }
                   7020:                }
1.620     albertel 7021:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7022:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7023: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7024:                        &log($env{'user.domain'},$env{'user.name'},
                   7025:                             $env{'user.home'},
1.57      www      7026:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7027:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7028:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7029: 		       return '';
                   7030:                    }
                   7031:                }
                   7032: 	   }
1.29      www      7033:        }
1.52      www      7034:     }
                   7035:    
                   7036: #
                   7037: # Rest of the restrictions depend on selected course
                   7038: #
                   7039: 
1.620     albertel 7040:     unless ($env{'request.course.id'}) {
1.766     albertel 7041: 	if ($thisallowed eq 'A') {
                   7042: 	    return 'A';
1.814     raeburn  7043:         } elsif ($thisallowed eq 'B') {
                   7044:             return 'B';
1.766     albertel 7045: 	} else {
                   7046: 	    return '1';
                   7047: 	}
1.52      www      7048:     }
1.29      www      7049: 
1.52      www      7050: #
                   7051: # Now user is definitely in a course
                   7052: #
1.53      www      7053: 
                   7054: 
                   7055: # Course preferences
                   7056: 
                   7057:    if ($thisallowed=~/C/) {
1.620     albertel 7058:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7059:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7060:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7061: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7062: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7063: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7064: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7065: 			$env{'request.course.id'});
                   7066: 	   }
1.237     www      7067:            return '';
                   7068:        }
                   7069: 
1.620     albertel 7070:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7071: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7072: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7073: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7074: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7075: 			$env{'request.course.id'});
                   7076: 	   }
1.54      www      7077:            return '';
                   7078:        }
1.53      www      7079:    }
                   7080: 
                   7081: # Resource preferences
                   7082: 
                   7083:    if ($thisallowed=~/R/) {
1.620     albertel 7084:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7085:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7086: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7087: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7088: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7089: 	   }
                   7090: 	   return '';
1.54      www      7091:        }
1.53      www      7092:    }
1.30      www      7093: 
1.246     www      7094: # Restricted by state or randomout?
1.30      www      7095: 
1.52      www      7096:    if ($thisallowed=~/X/) {
1.620     albertel 7097:       if ($env{'acc.randomout'}) {
1.579     albertel 7098: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7099:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7100:             return ''; 
                   7101:          }
1.247     www      7102:       }
                   7103:       if (&condval($statecond)) {
1.52      www      7104: 	 return '2';
                   7105:       } else {
                   7106:          return '';
                   7107:       }
                   7108:    }
1.30      www      7109: 
1.766     albertel 7110:     if ($thisallowed eq 'A') {
                   7111: 	return 'A';
1.814     raeburn  7112:     } elsif ($thisallowed eq 'B') {
                   7113:         return 'B';
1.766     albertel 7114:     }
1.52      www      7115:    return 'F';
1.232     www      7116: }
1.1162    raeburn  7117: 
1.1192    raeburn  7118: # ------------------------------------------- Check construction space access
                   7119: 
                   7120: sub constructaccess {
                   7121:     my ($url,$setpriv)=@_;
                   7122: 
                   7123: # We do not allow editing of previous versions of files
                   7124:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7125: 
                   7126: # Get username and domain from URL
                   7127:     my ($ownername,$ownerdomain,$ownerhome);
                   7128: 
                   7129:     ($ownerdomain,$ownername) =
                   7130:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7131: 
                   7132: # The URL does not really point to any authorspace, forget it
                   7133:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7134: 
                   7135: # Now we need to see if the user has access to the authorspace of
                   7136: # $ownername at $ownerdomain
                   7137: 
                   7138:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7139: # Real author for this?
                   7140:        $ownerhome = $env{'user.home'};
                   7141:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7142:           return ($ownername,$ownerdomain,$ownerhome);
                   7143:        }
                   7144:     } else {
                   7145: # Co-author for this?
                   7146:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7147:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7148:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7149:             return ($ownername,$ownerdomain,$ownerhome);
                   7150:         }
                   7151:     }
                   7152: 
                   7153: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7154: # we might as well leave
                   7155:    unless ($setpriv) { return ''; }
                   7156: 
                   7157: # Backdoor access?
                   7158:     my $allowed=&allowed('eco',$ownerdomain);
                   7159: # Nope
                   7160:     unless ($allowed) { return ''; }
                   7161: # Looks like we may have access, but could be locked by the owner of the construction space
                   7162:     if ($allowed eq 'U') {
                   7163:         my %blocked=&get('environment',['domcoord.author'],
                   7164:                          $ownerdomain,$ownername);
                   7165: # Is blocked by owner
                   7166:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7167:     }
                   7168:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7169: # Grant temporary access
                   7170:         my $then=$env{'user.login.time'};
1.1209    raeburn  7171:         my $update=$env{'user.update.time'};
1.1192    raeburn  7172:         if (!$update) { $update = $then; }
                   7173:         my $refresh=$env{'user.refresh.time'};
                   7174:         if (!$refresh) { $refresh = $update; }
                   7175:         my $now = time;
                   7176:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7177:                            $now,'ca','constructaccess');
                   7178:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7179:         return($ownername,$ownerdomain,$ownerhome);
                   7180:     }
                   7181: # No business here
                   7182:     return '';
                   7183: }
                   7184: 
1.1162    raeburn  7185: sub get_comm_blocks {
                   7186:     my ($cdom,$cnum) = @_;
                   7187:     if ($cdom eq '' || $cnum eq '') {
                   7188:         return unless ($env{'request.course.id'});
                   7189:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7190:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7191:     }
                   7192:     my %commblocks;
                   7193:     my $hashid=$cdom.'_'.$cnum;
                   7194:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7195:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7196:         %commblocks = %{$blocksref};
                   7197:     } else {
                   7198:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7199:         my $cachetime = 600;
                   7200:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7201:     }
                   7202:     return %commblocks;
                   7203: }
                   7204: 
                   7205: sub has_comm_blocking {
                   7206:     my ($priv,$symb,$uri,$blocks) = @_;
                   7207:     return unless ($env{'request.course.id'});
                   7208:     return unless ($priv eq 'bre');
                   7209:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7210:     my %commblocks;
                   7211:     if (ref($blocks) eq 'HASH') {
                   7212:         %commblocks = %{$blocks};
                   7213:     } else {
                   7214:         %commblocks = &get_comm_blocks();
                   7215:     }
                   7216:     return unless (keys(%commblocks) > 0);
                   7217:     if (!$symb) { $symb=&symbread($uri,1); }
                   7218:     my ($map,$resid,undef)=&decode_symb($symb);
                   7219:     my %tocheck = (
                   7220:                     maps      => $map,
                   7221:                     resources => $symb,
                   7222:                   );
                   7223:     my @blockers;
                   7224:     my $now = time;
1.1163    raeburn  7225:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7226:     foreach my $block (keys(%commblocks)) {
                   7227:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7228:             my ($start,$end) = ($1,$2);
                   7229:             if ($start <= $now && $end >= $now) {
                   7230:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7231:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7232:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7233:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7234:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7235:                                     push(@blockers,$block);
                   7236:                                 }
                   7237:                             }
                   7238:                         }
                   7239:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7240:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7241:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7242:                                     push(@blockers,$block);
                   7243:                                 }
                   7244:                             }
                   7245:                         }
                   7246:                     }
                   7247:                 }
                   7248:             }
                   7249:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7250:             my $item = $1;
1.1163    raeburn  7251:             my @to_test;
1.1162    raeburn  7252:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7253:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7254:                     my $check_interval;
                   7255:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7256:                         my @interval;
                   7257:                         my $type = 'map';
                   7258:                         if ($item eq 'course') {
                   7259:                             $type = 'course';
                   7260:                             @interval=&EXT("resource.0.interval");
                   7261:                         } else {
                   7262:                             if ($item =~ /___\d+___/) {
                   7263:                                 $type = 'resource';
                   7264:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7265:                                 if (ref($navmap)) {                        
                   7266:                                     my $res = $navmap->getBySymb($item); 
                   7267:                                     push(@to_test,$res);
                   7268:                                 }
1.1162    raeburn  7269:                             } else {
                   7270:                                 my $mapsymb = &symbread($item,1);
                   7271:                                 if ($mapsymb) {
                   7272:                                     if (ref($navmap)) {
                   7273:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7274:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7275:                                         foreach my $res (@to_test) {
1.1162    raeburn  7276:                                             my $symb = $res->symb();
                   7277:                                             next if ($symb eq $mapsymb);
                   7278:                                             if ($symb ne '') {
                   7279:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7280:                                                 last;
                   7281:                                             }
                   7282:                                         }
                   7283:                                     }
                   7284:                                 }
                   7285:                             }
                   7286:                         }
                   7287:                         if ($interval[0] =~ /\d+/) {
                   7288:                             my $first_access;
                   7289:                             if ($type eq 'resource') {
                   7290:                                 $first_access=&get_first_access($interval[1],$item);
                   7291:                             } elsif ($type eq 'map') {
                   7292:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7293:                             } else {
                   7294:                                 $first_access=&get_first_access($interval[1]);
                   7295:                             }
                   7296:                             if ($first_access) {
                   7297:                                 my $timesup = $first_access+$interval[0];
                   7298:                                 if ($timesup > $now) {
1.1163    raeburn  7299:                                     foreach my $res (@to_test) {
                   7300:                                         if ($res->is_problem()) {
                   7301:                                             if ($res->completable()) {
                   7302:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7303:                                                     push(@blockers,$block);
                   7304:                                                 }
                   7305:                                                 last;
                   7306:                                             }
                   7307:                                         }
1.1162    raeburn  7308:                                     }
                   7309:                                 }
                   7310:                             }
                   7311:                         }
                   7312:                     }
                   7313:                 }
                   7314:             }
                   7315:         }
                   7316:     }
                   7317:     return @blockers;
                   7318: }
                   7319: 
                   7320: sub check_docs_block {
                   7321:     my ($docsblock,$tocheck) =@_;
                   7322:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7323:         return;
                   7324:     }
                   7325:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7326:         if ($tocheck->{'maps'}) {
                   7327:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7328:                 return 1;
                   7329:             }
                   7330:         }
                   7331:     }
                   7332:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7333:         if ($tocheck->{'resources'}) {
                   7334:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7335:                 return 1;
                   7336:             }
                   7337:         }
                   7338:     }
                   7339:     return;
                   7340: }
                   7341: 
1.1133    foxr     7342: #
                   7343: #   Removes the versino from a URI and
                   7344: #   splits it in to its filename and path to the filename.
                   7345: #   Seems like File::Basename could have done this more clearly.
                   7346: #   Parameters:
                   7347: #      $uri   - input URI
                   7348: #   Returns:
                   7349: #     Two element list consisting of 
                   7350: #     $pathname  - the URI up to and excluding the trailing /
                   7351: #     $filename  - The part of the URI following the last /
                   7352: #  NOTE:
                   7353: #    Another realization of this is simply:
                   7354: #    use File::Basename;
                   7355: #    ...
                   7356: #    $uri = shift;
                   7357: #    $filename = basename($uri);
                   7358: #    $path     = dirname($uri);
                   7359: #    return ($filename, $path);
                   7360: #
                   7361: #     The implementation below is probably faster however.
                   7362: #
1.710     albertel 7363: sub split_uri_for_cond {
                   7364:     my $uri=&deversion(&declutter(shift));
                   7365:     my @uriparts=split(/\//,$uri);
                   7366:     my $filename=pop(@uriparts);
                   7367:     my $pathname=join('/',@uriparts);
                   7368:     return ($pathname,$filename);
                   7369: }
1.232     www      7370: # --------------------------------------------------- Is a resource on the map?
                   7371: 
                   7372: sub is_on_map {
1.710     albertel 7373:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7374:     #Trying to find the conditional for the file
1.620     albertel 7375:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7376: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7377:     if ($match) {
1.289     bowersj2 7378: 	return (1,$1);
                   7379:     } else {
1.434     www      7380: 	return (0,0);
1.289     bowersj2 7381:     }
1.12      www      7382: }
                   7383: 
1.427     www      7384: # --------------------------------------------------------- Get symb from alias
                   7385: 
                   7386: sub get_symb_from_alias {
                   7387:     my $symb=shift;
                   7388:     my ($map,$resid,$url)=&decode_symb($symb);
                   7389: # Already is a symb
                   7390:     if ($url) { return $symb; }
                   7391: # Must be an alias
                   7392:     my $aliassymb='';
                   7393:     my %bighash;
1.620     albertel 7394:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7395:                             &GDBM_READER(),0640)) {
                   7396:         my $rid=$bighash{'mapalias_'.$symb};
                   7397: 	if ($rid) {
                   7398: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7399: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7400: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7401: 	}
                   7402:         untie %bighash;
                   7403:     }
                   7404:     return $aliassymb;
                   7405: }
                   7406: 
1.12      www      7407: # ----------------------------------------------------------------- Define Role
                   7408: 
                   7409: sub definerole {
                   7410:   if (allowed('mcr','/')) {
                   7411:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7412:     foreach my $role (split(':',$sysrole)) {
                   7413: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7414:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7415:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7416: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7417:                return "refused:s:$crole&$cqual"; 
                   7418:             }
                   7419:         }
1.191     harris41 7420:     }
1.800     albertel 7421:     foreach my $role (split(':',$domrole)) {
                   7422: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7423:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7424:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7425: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7426:                return "refused:d:$crole&$cqual"; 
                   7427:             }
                   7428:         }
1.191     harris41 7429:     }
1.800     albertel 7430:     foreach my $role (split(':',$courole)) {
                   7431: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7432:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7433:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7434: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7435:                return "refused:c:$crole&$cqual"; 
                   7436:             }
                   7437:         }
1.191     harris41 7438:     }
1.620     albertel 7439:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7440:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7441: 	        "rolesdef_$rolename=".
                   7442:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7443:     return reply($command,$env{'user.home'});
1.12      www      7444:   } else {
                   7445:     return 'refused';
                   7446:   }
1.105     harris41 7447: }
                   7448: 
                   7449: # ---------------- Make a metadata query against the network of library servers
                   7450: 
                   7451: sub metadata_query {
1.1237    raeburn  7452:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7453:     my %rhash;
1.845     albertel 7454:     my %libserv = &all_library();
1.244     matthew  7455:     my @server_list = (defined($server_array) ? @$server_array
                   7456:                                               : keys(%libserv) );
                   7457:     for my $server (@server_list) {
1.1237    raeburn  7458:         my $domains = ''; 
                   7459:         if (ref($domains_hash) eq 'HASH') {
                   7460:             $domains = $domains_hash->{$server}; 
                   7461:         }
1.118     harris41 7462: 	unless ($custom or $customshow) {
1.1237    raeburn  7463: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7464: 	    $rhash{$server}=$reply;
                   7465: 	}
                   7466: 	else {
                   7467: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7468: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7469: 			     $server);
                   7470: 	    $rhash{$server}=$reply;
                   7471: 	}
1.112     harris41 7472:     }
1.118     harris41 7473:     return \%rhash;
1.240     www      7474: }
                   7475: 
                   7476: # ----------------------------------------- Send log queries and wait for reply
                   7477: 
                   7478: sub log_query {
                   7479:     my ($uname,$udom,$query,%filters)=@_;
                   7480:     my $uhome=&homeserver($uname,$udom);
                   7481:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7482:     my $uhost=&hostname($uhome);
1.800     albertel 7483:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7484:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7485:                        $uhome);
1.479     albertel 7486:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7487:     return get_query_reply($queryid);
                   7488: }
                   7489: 
1.818     raeburn  7490: # -------------------------- Update MySQL table for portfolio file
                   7491: 
                   7492: sub update_portfolio_table {
1.821     raeburn  7493:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7494:     if ($group ne '') {
                   7495:         $file_name =~s /^\Q$group\E//;
                   7496:     }
1.818     raeburn  7497:     my $homeserver = &homeserver($uname,$udom);
                   7498:     my $queryid=
1.821     raeburn  7499:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7500:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7501:     my $reply = &get_query_reply($queryid);
                   7502:     return $reply;
                   7503: }
                   7504: 
1.899     raeburn  7505: # -------------------------- Update MySQL allusers table
                   7506: 
                   7507: sub update_allusers_table {
                   7508:     my ($uname,$udom,$names) = @_;
                   7509:     my $homeserver = &homeserver($uname,$udom);
                   7510:     my $queryid=
                   7511:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7512:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7513:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7514:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7515:                'generation='.&escape($names->{'generation'}).'%%'.
                   7516:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7517:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7518:     return;
1.899     raeburn  7519: }
                   7520: 
1.508     raeburn  7521: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7522: 
                   7523: sub fetch_enrollment_query {
1.511     raeburn  7524:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7525:     my $homeserver;
1.547     raeburn  7526:     my $maxtries = 1;
1.508     raeburn  7527:     if ($context eq 'automated') {
                   7528:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7529:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7530:     } else {
                   7531:         $homeserver = &homeserver($cnum,$dom);
                   7532:     }
1.838     albertel 7533:     my $host=&hostname($homeserver);
1.506     raeburn  7534:     my $cmd = '';
1.1000    raeburn  7535:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7536:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7537:     }
                   7538:     $cmd =~ s/%%$//;
                   7539:     $cmd = &escape($cmd);
                   7540:     my $query = 'fetchenrollment';
1.620     albertel 7541:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7542:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7543:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7544:         return 'error: '.$queryid;
                   7545:     }
1.506     raeburn  7546:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7547:     my $tries = 1;
                   7548:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7549:         $reply = &get_query_reply($queryid);
                   7550:         $tries ++;
                   7551:     }
1.526     raeburn  7552:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7553:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7554:     } else {
1.901     albertel 7555:         my @responses = split(/:/,$reply);
1.515     raeburn  7556:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7557:             foreach my $line (@responses) {
                   7558:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7559:                 $$replyref{$key} = $value;
                   7560:             }
                   7561:         } else {
1.1117    foxr     7562:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7563:             foreach my $line (@responses) {
                   7564:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7565:                 $$replyref{$key} = $value;
                   7566:                 if ($value > 0) {
1.800     albertel 7567:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7568:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7569:                         my $destname = $pathname.'/'.$filename;
                   7570:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7571:                         if ($xml_classlist =~ /^error/) {
                   7572:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7573:                         } else {
1.506     raeburn  7574:                             if ( open(FILE,">$destname") ) {
                   7575:                                 print FILE &unescape($xml_classlist);
                   7576:                                 close(FILE);
1.526     raeburn  7577:                             } else {
                   7578:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7579:                             }
                   7580:                         }
                   7581:                     }
                   7582:                 }
                   7583:             }
                   7584:         }
                   7585:         return 'ok';
                   7586:     }
                   7587:     return 'error';
                   7588: }
                   7589: 
1.242     www      7590: sub get_query_reply {
                   7591:     my $queryid=shift;
1.1117    foxr     7592:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7593:     my $reply='';
                   7594:     for (1..100) {
                   7595: 	sleep 2;
                   7596:         if (-e $replyfile.'.end') {
1.448     albertel 7597: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7598: 		$reply = join('',<$fh>);
                   7599: 		close($fh);
1.240     www      7600: 	   } else { return 'error: reply_file_error'; }
1.242     www      7601:            return &unescape($reply);
                   7602: 	}
1.240     www      7603:     }
1.242     www      7604:     return 'timeout:'.$queryid;
1.240     www      7605: }
                   7606: 
                   7607: sub courselog_query {
1.241     www      7608: #
                   7609: # possible filters:
                   7610: # url: url or symb
                   7611: # username
                   7612: # domain
                   7613: # action: view, submit, grade
                   7614: # start: timestamp
                   7615: # end: timestamp
                   7616: #
1.240     www      7617:     my (%filters)=@_;
1.620     albertel 7618:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7619:     if ($filters{'url'}) {
                   7620: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7621:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7622:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7623:     }
1.620     albertel 7624:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7625:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7626:     return &log_query($cname,$cdom,'courselog',%filters);
                   7627: }
                   7628: 
                   7629: sub userlog_query {
1.858     raeburn  7630: #
                   7631: # possible filters:
                   7632: # action: log check role
                   7633: # start: timestamp
                   7634: # end: timestamp
                   7635: #
1.240     www      7636:     my ($uname,$udom,%filters)=@_;
                   7637:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7638: }
                   7639: 
1.506     raeburn  7640: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7641: 
                   7642: sub auto_run {
1.508     raeburn  7643:     my ($cnum,$cdom) = @_;
1.876     raeburn  7644:     my $response = 0;
                   7645:     my $settings;
                   7646:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7647:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7648:         $settings = $domconfig{'autoenroll'};
                   7649:         if ($settings->{'run'} eq '1') {
                   7650:             $response = 1;
                   7651:         }
                   7652:     } else {
1.934     raeburn  7653:         my $homeserver;
                   7654:         if (&is_course($cdom,$cnum)) {
                   7655:             $homeserver = &homeserver($cnum,$cdom);
                   7656:         } else {
                   7657:             $homeserver = &domain($cdom,'primary');
                   7658:         }
                   7659:         if ($homeserver ne 'no_host') {
                   7660:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7661:         }
1.876     raeburn  7662:     }
1.506     raeburn  7663:     return $response;
                   7664: }
1.776     albertel 7665: 
1.506     raeburn  7666: sub auto_get_sections {
1.508     raeburn  7667:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7668:     my $homeserver;
                   7669:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7670:         $homeserver = &homeserver($cnum,$cdom);
                   7671:     }
                   7672:     if (!defined($homeserver)) { 
                   7673:         if ($cdom =~ /^$match_domain$/) {
                   7674:             $homeserver = &domain($cdom,'primary');
                   7675:         }
                   7676:     }
                   7677:     my @secs;
                   7678:     if (defined($homeserver)) {
                   7679:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7680:         unless ($response eq 'refused') {
                   7681:             @secs = split(/:/,$response);
                   7682:         }
1.506     raeburn  7683:     }
                   7684:     return @secs;
                   7685: }
1.776     albertel 7686: 
1.506     raeburn  7687: sub auto_new_course {
1.1099    raeburn  7688:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7689:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7690:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7691:     return $response;
                   7692: }
1.776     albertel 7693: 
1.506     raeburn  7694: sub auto_validate_courseID {
1.508     raeburn  7695:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7696:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7697:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7698:     return $response;
                   7699: }
1.776     albertel 7700: 
1.1007    raeburn  7701: sub auto_validate_instcode {
1.1020    raeburn  7702:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7703:     my ($homeserver,$response);
                   7704:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7705:         $homeserver = &homeserver($cnum,$cdom);
                   7706:     }
                   7707:     if (!defined($homeserver)) {
                   7708:         if ($cdom =~ /^$match_domain$/) {
                   7709:             $homeserver = &domain($cdom,'primary');
                   7710:         }
                   7711:     }
1.1065    raeburn  7712:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7713:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7714:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7715:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7716: }
                   7717: 
1.506     raeburn  7718: sub auto_create_password {
1.873     raeburn  7719:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7720:     my ($homeserver,$response);
1.506     raeburn  7721:     my $create_passwd = 0;
                   7722:     my $authchk = '';
1.873     raeburn  7723:     if ($udom =~ /^$match_domain$/) {
                   7724:         $homeserver = &domain($udom,'primary');
                   7725:     }
                   7726:     if ($homeserver eq '') {
                   7727:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7728:             $homeserver = &homeserver($cnum,$cdom);
                   7729:         }
                   7730:     }
                   7731:     if ($homeserver eq '') {
                   7732:         $authchk = 'nodomain';
1.506     raeburn  7733:     } else {
1.873     raeburn  7734:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7735:         if ($response eq 'refused') {
                   7736:             $authchk = 'refused';
                   7737:         } else {
1.901     albertel 7738:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7739:         }
1.506     raeburn  7740:     }
                   7741:     return ($authparam,$create_passwd,$authchk);
                   7742: }
                   7743: 
1.706     raeburn  7744: sub auto_photo_permission {
                   7745:     my ($cnum,$cdom,$students) = @_;
                   7746:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7747:     my ($outcome,$perm_reqd,$conditions) = 
                   7748: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7749:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7750: 	return (undef,undef);
                   7751:     }
1.706     raeburn  7752:     return ($outcome,$perm_reqd,$conditions);
                   7753: }
                   7754: 
                   7755: sub auto_checkphotos {
                   7756:     my ($uname,$udom,$pid) = @_;
                   7757:     my $homeserver = &homeserver($uname,$udom);
                   7758:     my ($result,$resulttype);
                   7759:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7760: 				   &escape($uname).':'.&escape($pid),
                   7761: 				   $homeserver));
1.709     albertel 7762:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7763: 	return (undef,undef);
                   7764:     }
1.706     raeburn  7765:     if ($outcome) {
                   7766:         ($result,$resulttype) = split(/:/,$outcome);
                   7767:     } 
                   7768:     return ($result,$resulttype);
                   7769: }
                   7770: 
                   7771: sub auto_photochoice {
                   7772:     my ($cnum,$cdom) = @_;
                   7773:     my $homeserver = &homeserver($cnum,$cdom);
                   7774:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7775: 						       &escape($cdom),
                   7776: 						       $homeserver)));
1.709     albertel 7777:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7778: 	return (undef,undef);
                   7779:     }
1.706     raeburn  7780:     return ($update,$comment);
                   7781: }
                   7782: 
                   7783: sub auto_photoupdate {
                   7784:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7785:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7786:     my $host=&hostname($homeserver);
1.706     raeburn  7787:     my $cmd = '';
                   7788:     my $maxtries = 1;
1.800     albertel 7789:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7790:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7791:     }
                   7792:     $cmd =~ s/%%$//;
                   7793:     $cmd = &escape($cmd);
                   7794:     my $query = 'institutionalphotos';
                   7795:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7796:     unless ($queryid=~/^\Q$host\E\_/) {
                   7797:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7798:         return 'error: '.$queryid;
                   7799:     }
                   7800:     my $reply = &get_query_reply($queryid);
                   7801:     my $tries = 1;
                   7802:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7803:         $reply = &get_query_reply($queryid);
                   7804:         $tries ++;
                   7805:     }
                   7806:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7807:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7808:     } else {
                   7809:         my @responses = split(/:/,$reply);
                   7810:         my $outcome = shift(@responses); 
                   7811:         foreach my $item (@responses) {
                   7812:             my ($key,$value) = split(/=/,$item);
                   7813:             $$photo{$key} = $value;
                   7814:         }
                   7815:         return $outcome;
                   7816:     }
                   7817:     return 'error';
                   7818: }
                   7819: 
1.521     raeburn  7820: sub auto_instcode_format {
1.793     albertel 7821:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7822: 	$cat_order) = @_;
1.521     raeburn  7823:     my $courses = '';
1.772     raeburn  7824:     my @homeservers;
1.521     raeburn  7825:     if ($caller eq 'global') {
1.841     albertel 7826: 	my %servers = &get_servers($codedom,'library');
                   7827: 	foreach my $tryserver (keys(%servers)) {
                   7828: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7829: 		push(@homeservers,$tryserver);
                   7830: 	    }
1.584     raeburn  7831:         }
1.1022    raeburn  7832:     } elsif ($caller eq 'requests') {
                   7833:         if ($codedom =~ /^$match_domain$/) {
                   7834:             my $chome = &domain($codedom,'primary');
                   7835:             unless ($chome eq 'no_host') {
                   7836:                 push(@homeservers,$chome);
                   7837:             }
                   7838:         }
1.521     raeburn  7839:     } else {
1.772     raeburn  7840:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7841:     }
1.793     albertel 7842:     foreach my $code (keys(%{$instcodes})) {
                   7843:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7844:     }
                   7845:     chop($courses);
1.772     raeburn  7846:     my $ok_response = 0;
                   7847:     my $response;
                   7848:     while (@homeservers > 0 && $ok_response == 0) {
                   7849:         my $server = shift(@homeservers); 
                   7850:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7851:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7852:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7853: 		split(/:/,$response);
1.772     raeburn  7854:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7855:             push(@{$codetitles},&str2array($codetitles_str));
                   7856:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7857:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7858:             $ok_response = 1;
                   7859:         }
                   7860:     }
                   7861:     if ($ok_response) {
1.521     raeburn  7862:         return 'ok';
1.772     raeburn  7863:     } else {
                   7864:         return $response;
1.521     raeburn  7865:     }
                   7866: }
                   7867: 
1.792     raeburn  7868: sub auto_instcode_defaults {
                   7869:     my ($domain,$returnhash,$code_order) = @_;
                   7870:     my @homeservers;
1.841     albertel 7871: 
                   7872:     my %servers = &get_servers($domain,'library');
                   7873:     foreach my $tryserver (keys(%servers)) {
                   7874: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7875: 	    push(@homeservers,$tryserver);
                   7876: 	}
1.792     raeburn  7877:     }
1.841     albertel 7878: 
1.792     raeburn  7879:     my $response;
1.841     albertel 7880:     foreach my $server (@homeservers) {
1.792     raeburn  7881:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7882:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7883: 	
                   7884: 	foreach my $pair (split(/\&/,$response)) {
                   7885: 	    my ($name,$value)=split(/\=/,$pair);
                   7886: 	    if ($name eq 'code_order') {
                   7887: 		@{$code_order} = split(/\&/,&unescape($value));
                   7888: 	    } else {
                   7889: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7890: 	    }
                   7891: 	}
                   7892: 	return 'ok';
1.792     raeburn  7893:     }
1.841     albertel 7894: 
                   7895:     return $response;
1.1003    raeburn  7896: }
                   7897: 
                   7898: sub auto_possible_instcodes {
1.1007    raeburn  7899:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7900:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7901:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7902:         return;
                   7903:     }
1.1003    raeburn  7904:     my (@homeservers,$uhome);
                   7905:     if (defined(&domain($domain,'primary'))) {
                   7906:         $uhome=&domain($domain,'primary');
                   7907:         push(@homeservers,&domain($domain,'primary'));
                   7908:     } else {
                   7909:         my %servers = &get_servers($domain,'library');
                   7910:         foreach my $tryserver (keys(%servers)) {
                   7911:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7912:                 push(@homeservers,$tryserver);
                   7913:             }
                   7914:         }
                   7915:     }
                   7916:     my $response;
                   7917:     foreach my $server (@homeservers) {
                   7918:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7919:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7920:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7921:             split(':',$response);
                   7922:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7923:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7924:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7925:             my ($name,$value)=split('=',$item);
                   7926:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7927:         }
                   7928:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7929:             my ($name,$value)=split('=',$item);
                   7930:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7931:         }
                   7932:         return 'ok';
                   7933:     }
                   7934:     return $response;
                   7935: }
1.792     raeburn  7936: 
1.1010    raeburn  7937: sub auto_courserequest_checks {
                   7938:     my ($dom) = @_;
1.1020    raeburn  7939:     my ($homeserver,%validations);
                   7940:     if ($dom =~ /^$match_domain$/) {
                   7941:         $homeserver = &domain($dom,'primary');
                   7942:     }
                   7943:     unless ($homeserver eq 'no_host') {
                   7944:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7945:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7946:             my @items = split(/&/,$response);
                   7947:             foreach my $item (@items) {
                   7948:                 my ($key,$value) = split('=',$item);
                   7949:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7950:             }
                   7951:         }
                   7952:     }
1.1010    raeburn  7953:     return %validations; 
                   7954: }
                   7955: 
1.1020    raeburn  7956: sub auto_courserequest_validation {
1.1255    raeburn  7957:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  7958:     my ($homeserver,$response);
                   7959:     if ($dom =~ /^$match_domain$/) {
                   7960:         $homeserver = &domain($dom,'primary');
                   7961:     }
1.1255    raeburn  7962:     unless ($homeserver eq 'no_host') {
                   7963:         my $customdata;
                   7964:         if (ref($custominfo) eq 'HASH') {
                   7965:             $customdata = &freeze_escape($custominfo);
                   7966:         }
1.1020    raeburn  7967:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7968:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  7969:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   7970:                                     $customdata,$homeserver));
1.1020    raeburn  7971:     }
                   7972:     return $response;
                   7973: }
                   7974: 
1.777     albertel 7975: sub auto_validate_class_sec {
1.918     raeburn  7976:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7977:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7978:     my $ownerlist;
                   7979:     if (ref($owners) eq 'ARRAY') {
                   7980:         $ownerlist = join(',',@{$owners});
                   7981:     } else {
                   7982:         $ownerlist = $owners;
                   7983:     }
1.773     raeburn  7984:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7985:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7986:     return $response;
                   7987: }
                   7988: 
1.1248    raeburn  7989: sub auto_crsreq_update {
                   7990:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  7991:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  7992:     my ($homeserver,%crsreqresponse);
                   7993:     if ($cdom =~ /^$match_domain$/) {
                   7994:         $homeserver = &domain($cdom,'primary');
                   7995:     }
                   7996:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   7997:         my $info;
                   7998:         if (ref($inbound) eq 'HASH') {
                   7999:             $info = &freeze_escape($inbound);
                   8000:         }
                   8001:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8002:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8003:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8004:                             &escape($title).':'.&escape($code).':'.
                   8005:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8006:                             $homeserver);
1.1248    raeburn  8007:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8008:             my @items = split(/&/,$response);
                   8009:             foreach my $item (@items) {
                   8010:                 my ($key,$value) = split('=',$item);
                   8011:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8012:             }
                   8013:         }
                   8014:     }
                   8015:     return \%crsreqresponse;
                   8016: }
                   8017: 
1.679     raeburn  8018: # ------------------------------------------------------- Course Group routines
                   8019: 
                   8020: sub get_coursegroups {
1.809     raeburn  8021:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8022:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8023: }
                   8024: 
1.679     raeburn  8025: sub modify_coursegroup {
                   8026:     my ($cdom,$cnum,$groupsettings) = @_;
                   8027:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8028: }
                   8029: 
1.809     raeburn  8030: sub toggle_coursegroup_status {
                   8031:     my ($cdom,$cnum,$group,$action) = @_;
                   8032:     my ($from_namespace,$to_namespace);
                   8033:     if ($action eq 'delete') {
                   8034:         $from_namespace = 'coursegroups';
                   8035:         $to_namespace = 'deleted_groups';
                   8036:     } else {
                   8037:         $from_namespace = 'deleted_groups';
                   8038:         $to_namespace = 'coursegroups';
                   8039:     }
                   8040:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8041:     if (my $tmp = &error(%curr_group)) {
                   8042:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8043:         return ('read error',$tmp);
                   8044:     } else {
                   8045:         my %savedsettings = %curr_group; 
1.809     raeburn  8046:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8047:         my $deloutcome;
                   8048:         if ($result eq 'ok') {
1.809     raeburn  8049:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8050:         } else {
                   8051:             return ('write error',$result);
                   8052:         }
                   8053:         if ($deloutcome eq 'ok') {
                   8054:             return 'ok';
                   8055:         } else {
                   8056:             return ('delete error',$deloutcome);
                   8057:         }
                   8058:     }
                   8059: }
                   8060: 
1.679     raeburn  8061: sub modify_group_roles {
1.957     raeburn  8062:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8063:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8064:     my $role = 'gr/'.&escape($userprivs);
                   8065:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8066:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8067:     if ($result eq 'ok') {
                   8068:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8069:     }
1.679     raeburn  8070:     return $result;
                   8071: }
                   8072: 
                   8073: sub modify_coursegroup_membership {
                   8074:     my ($cdom,$cnum,$membership) = @_;
                   8075:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8076:     return $result;
                   8077: }
                   8078: 
1.682     raeburn  8079: sub get_active_groups {
                   8080:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8081:     my $now = time;
                   8082:     my %groups = ();
                   8083:     foreach my $key (keys(%env)) {
1.811     albertel 8084:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8085:             my ($start,$end) = split(/\./,$env{$key});
                   8086:             if (($end!=0) && ($end<$now)) { next; }
                   8087:             if (($start!=0) && ($start>$now)) { next; }
                   8088:             if ($1 eq $cdom && $2 eq $cnum) {
                   8089:                 $groups{$3} = $env{$key} ;
                   8090:             }
                   8091:         }
                   8092:     }
                   8093:     return %groups;
                   8094: }
                   8095: 
1.683     raeburn  8096: sub get_group_membership {
                   8097:     my ($cdom,$cnum,$group) = @_;
                   8098:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8099: }
                   8100: 
                   8101: sub get_users_groups {
                   8102:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8103:     my @usersgroups;
1.683     raeburn  8104:     my $cachetime=1800;
                   8105: 
                   8106:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8107:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8108:     if (defined($cached)) {
1.734     albertel 8109:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8110:     } else {  
                   8111:         $grouplist = '';
1.816     raeburn  8112:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8113:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8114:         my $access_end = $env{'course.'.$courseid.
                   8115:                               '.default_enrollment_end_date'};
                   8116:         my $now = time;
                   8117:         foreach my $key (keys(%roleshash)) {
                   8118:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8119:                 my $group = $1;
                   8120:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8121:                     my $start = $2;
                   8122:                     my $end = $1;
                   8123:                     if ($start == -1) { next; } # deleted from group
                   8124:                     if (($start!=0) && ($start>$now)) { next; }
                   8125:                     if (($end!=0) && ($end<$now)) {
                   8126:                         if ($access_end && $access_end < $now) {
                   8127:                             if ($access_end - $end < 86400) {
                   8128:                                 push(@usersgroups,$group);
1.733     raeburn  8129:                             }
                   8130:                         }
1.817     raeburn  8131:                         next;
1.733     raeburn  8132:                     }
1.817     raeburn  8133:                     push(@usersgroups,$group);
1.683     raeburn  8134:                 }
                   8135:             }
                   8136:         }
1.817     raeburn  8137:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8138:         $grouplist = join(':',@usersgroups);
                   8139:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8140:     }
1.733     raeburn  8141:     return @usersgroups;
1.683     raeburn  8142: }
                   8143: 
                   8144: sub devalidate_getgroups_cache {
                   8145:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8146:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8147: 
1.683     raeburn  8148:     my $hashid="$udom:$uname:$courseid";
                   8149:     &devalidate_cache_new('getgroups',$hashid);
                   8150: }
                   8151: 
1.12      www      8152: # ------------------------------------------------------------------ Plain Text
                   8153: 
                   8154: sub plaintext {
1.988     raeburn  8155:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8156:     if ($short =~ m{^cr/}) {
1.758     albertel 8157: 	return (split('/',$short))[-1];
                   8158:     }
1.742     raeburn  8159:     if (!defined($cid)) {
                   8160:         $cid = $env{'request.course.id'};
                   8161:     }
                   8162:     my %rolenames = (
1.1008    raeburn  8163:                       Course    => 'std',
                   8164:                       Community => 'alt1',
1.742     raeburn  8165:                     );
1.1037    raeburn  8166:     if ($cid ne '') {
                   8167:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8168:             unless ($forcedefault) {
                   8169:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8170:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8171:                 return &Apache::lonlocal::mt($roletext);
                   8172:             }
                   8173:         }
                   8174:     }
                   8175:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8176:         (defined($rolenames{$type})) && 
                   8177:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8178:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8179:     } elsif ($cid ne '') {
                   8180:         my $crstype = $env{'course.'.$cid.'.type'};
                   8181:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8182:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8183:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8184:         }
1.742     raeburn  8185:     }
1.1037    raeburn  8186:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8187: }
                   8188: 
                   8189: # ----------------------------------------------------------------- Assign Role
                   8190: 
                   8191: sub assignrole {
1.957     raeburn  8192:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8193:         $context)=@_;
1.21      www      8194:     my $mrole;
                   8195:     if ($role =~ /^cr\//) {
1.393     www      8196:         my $cwosec=$url;
1.811     albertel 8197:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8198: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8199:            my $refused = 1;
                   8200:            if ($context eq 'requestcourses') {
                   8201:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8202:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8203:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8204:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8205:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8206:                            if ($crsenv{'internal.courseowner'} eq
                   8207:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8208:                                $refused = '';
                   8209:                            }
                   8210:                        }
                   8211:                    }
                   8212:                }
                   8213:            }
                   8214:            if ($refused) {
                   8215:                &logthis('Refused custom assignrole: '.
                   8216:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8217:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8218:                return 'refused';
                   8219:            }
1.104     www      8220:         }
1.21      www      8221:         $mrole='cr';
1.678     raeburn  8222:     } elsif ($role =~ /^gr\//) {
                   8223:         my $cwogrp=$url;
1.811     albertel 8224:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8225:         unless (&allowed('mdg',$cwogrp)) {
                   8226:             &logthis('Refused group assignrole: '.
                   8227:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8228:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8229:             return 'refused';
                   8230:         }
                   8231:         $mrole='gr';
1.21      www      8232:     } else {
1.82      www      8233:         my $cwosec=$url;
1.811     albertel 8234:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8235:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8236:             my $refused;
                   8237:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8238:                 if (!(&allowed('c'.$role,$url))) {
                   8239:                     $refused = 1;
                   8240:                 }
                   8241:             } else {
                   8242:                 $refused = 1;
                   8243:             }
1.947     raeburn  8244:             if ($refused) {
1.1045    raeburn  8245:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8246:                 if (!$selfenroll && $context eq 'course') {
                   8247:                     my %crsenv;
                   8248:                     if ($role eq 'cc' || $role eq 'co') {
                   8249:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8250:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8251:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8252:                                 if ($crsenv{'internal.courseowner'} eq 
                   8253:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8254:                                     $refused = '';
                   8255:                                 }
                   8256:                             }
                   8257:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8258:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8259:                                 if ($crsenv{'internal.courseowner'} eq 
                   8260:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8261:                                     $refused = '';
                   8262:                                 }
                   8263:                             }
                   8264:                         }
                   8265:                     }
                   8266:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8267:                     $refused = '';
1.1017    raeburn  8268:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8269:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8270:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8271:                         my $wrongcc;
                   8272:                         if ($cnum =~ /^$match_community$/) {
                   8273:                             $wrongcc = 1 if ($role eq 'cc');
                   8274:                         } else {
                   8275:                             $wrongcc = 1 if ($role eq 'co');
                   8276:                         }
                   8277:                         unless ($wrongcc) {
                   8278:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8279:                             if ($crsenv{'internal.courseowner'} eq 
                   8280:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8281:                                 $refused = '';
                   8282:                             }
1.1017    raeburn  8283:                         }
                   8284:                     }
1.1183    raeburn  8285:                 } elsif ($context eq 'requestauthor') {
                   8286:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8287:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8288:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8289:                             $refused = '';
                   8290:                         } else {
                   8291:                             my %domdefaults = &get_domain_defaults($udom);
                   8292:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8293:                                 my $checkbystatus;
                   8294:                                 if ($env{'user.adv'}) { 
                   8295:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8296:                                     if ($disposition eq 'automatic') {
                   8297:                                         $refused = '';
                   8298:                                     } elsif ($disposition eq '') {
                   8299:                                         $checkbystatus = 1;
                   8300:                                     } 
                   8301:                                 } else {
                   8302:                                     $checkbystatus = 1;
                   8303:                                 }
                   8304:                                 if ($checkbystatus) {
                   8305:                                     if ($env{'environment.inststatus'}) {
                   8306:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8307:                                         foreach my $type (@inststatuses) {
                   8308:                                             if (($type ne '') &&
                   8309:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8310:                                                 $refused = '';
                   8311:                                             }
                   8312:                                         }
                   8313:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8314:                                         $refused = '';
                   8315:                                     }
                   8316:                                 }
                   8317:                             }
                   8318:                         }
                   8319:                     }
1.1017    raeburn  8320:                 }
                   8321:                 if ($refused) {
1.947     raeburn  8322:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8323:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8324: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8325:                     return 'refused';
                   8326:                 }
1.932     raeburn  8327:             }
1.1131    raeburn  8328:         } elsif ($role eq 'au') {
                   8329:             if ($url ne '/'.$udom.'/') {
                   8330:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8331:                          ' to assign author role for '.$uname.':'.$udom.
                   8332:                          ' in domain: '.$url.' refused (wrong domain).');
                   8333:                 return 'refused';
                   8334:             }
1.104     www      8335:         }
1.21      www      8336:         $mrole=$role;
                   8337:     }
1.620     albertel 8338:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8339:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8340:     if ($end) { $command.='_'.$end; }
1.21      www      8341:     if ($start) {
                   8342: 	if ($end) { 
1.81      www      8343:            $command.='_'.$start; 
1.21      www      8344:         } else {
1.81      www      8345:            $command.='_0_'.$start;
1.21      www      8346:         }
                   8347:     }
1.739     raeburn  8348:     my $origstart = $start;
                   8349:     my $origend = $end;
1.957     raeburn  8350:     my $delflag;
1.357     www      8351: # actually delete
                   8352:     if ($deleteflag) {
1.373     www      8353: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8354: # modify command to delete the role
1.620     albertel 8355:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8356:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8357: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8358: # set start and finish to negative values for userrolelog
                   8359:            $start=-1;
                   8360:            $end=-1;
1.957     raeburn  8361:            $delflag = 1;
1.357     www      8362:         }
                   8363:     }
                   8364: # send command
1.349     www      8365:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8366: # log new user role if status is ok
1.349     www      8367:     if ($answer eq 'ok') {
1.663     raeburn  8368: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8369:         if (($role eq 'cc') || ($role eq 'in') ||
                   8370:             ($role eq 'ep') || ($role eq 'ad') ||
                   8371:             ($role eq 'ta') || ($role eq 'st') ||
                   8372:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8373:             ($role eq 'co')) {
1.1200    raeburn  8374: # for course roles, perform group memberships changes triggered by role change.
                   8375:             unless ($role =~ /^gr/) {
                   8376:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8377:                                                  $origstart,$selfenroll,$context);
                   8378:             }
1.1184    raeburn  8379:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8380:                            $selfenroll,$context);
                   8381:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8382:                  ($role eq 'au') || ($role eq 'dc')) {
                   8383:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8384:                            $context);
                   8385:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8386:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8387:                              $context); 
                   8388:         }
1.1053    raeburn  8389:         if ($role eq 'cc') {
                   8390:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8391:         }
1.349     www      8392:     }
                   8393:     return $answer;
1.169     harris41 8394: }
                   8395: 
1.1053    raeburn  8396: sub autoupdate_coowners {
                   8397:     my ($url,$end,$start,$uname,$udom) = @_;
                   8398:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8399:     if (($cdom ne '') && ($cnum ne '')) {
                   8400:         my $now = time;
                   8401:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8402:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8403:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8404:             my $instcode = $coursehash{'internal.coursecode'};
                   8405:             if ($instcode ne '') {
1.1056    raeburn  8406:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8407:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8408:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8409:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8410:                         if ($result eq 'valid') {
                   8411:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8412:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8413:                                     push(@newcoowners,$coowner);
                   8414:                                 }
                   8415:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8416:                                     push(@newcoowners,$uname.':'.$udom);
                   8417:                                 }
                   8418:                                 @newcoowners = sort(@newcoowners);
                   8419:                             } else {
                   8420:                                 push(@newcoowners,$uname.':'.$udom);
                   8421:                             }
                   8422:                         } else {
                   8423:                             if ($coursehash{'internal.co-owners'}) {
                   8424:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8425:                                     unless ($coowner eq $uname.':'.$udom) {
                   8426:                                         push(@newcoowners,$coowner);
                   8427:                                     }
                   8428:                                 }
                   8429:                                 unless (@newcoowners > 0) {
                   8430:                                     $delcoowners = 1;
                   8431:                                     $coowners = '';
                   8432:                                 }
                   8433:                             }
                   8434:                         }
                   8435:                         if (@newcoowners || $delcoowners) {
                   8436:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8437:                                             $delcoowners,@newcoowners);
                   8438:                         }
                   8439:                     }
                   8440:                 }
                   8441:             }
                   8442:         }
                   8443:     }
                   8444: }
                   8445: 
                   8446: sub store_coowners {
                   8447:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8448:     my $cid = $cdom.'_'.$cnum;
                   8449:     my ($coowners,$delresult,$putresult);
                   8450:     if (@newcoowners) {
                   8451:         $coowners = join(',',@newcoowners);
                   8452:         my %coownershash = (
                   8453:                             'internal.co-owners' => $coowners,
                   8454:                            );
                   8455:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8456:         if ($putresult eq 'ok') {
                   8457:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8458:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8459:             }
                   8460:         }
                   8461:     }
                   8462:     if ($delcoowners) {
                   8463:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8464:         if ($delresult eq 'ok') {
                   8465:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8466:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8467:             }
                   8468:         }
                   8469:     }
                   8470:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8471:         my %crsinfo =
                   8472:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8473:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8474:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8475:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8476:         }
                   8477:     }
                   8478: }
                   8479: 
1.169     harris41 8480: # -------------------------------------------------- Modify user authentication
1.197     www      8481: # Overrides without validation
                   8482: 
1.169     harris41 8483: sub modifyuserauth {
                   8484:     my ($udom,$uname,$umode,$upass)=@_;
                   8485:     my $uhome=&homeserver($uname,$udom);
1.197     www      8486:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8487:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8488:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8489:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8490:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8491: 		     &escape($upass),$uhome);
1.620     albertel 8492:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8493:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8494:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8495:     &log($udom,,$uname,$uhome,
1.620     albertel 8496:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8497:                                      $env{'user.name'}.', '.$umode.
1.197     www      8498:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8499:     unless ($reply eq 'ok') {
1.197     www      8500:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8501: 	return 'error: '.$reply;
                   8502:     }   
1.170     harris41 8503:     return 'ok';
1.80      www      8504: }
                   8505: 
1.81      www      8506: # --------------------------------------------------------------- Modify a user
1.80      www      8507: 
1.81      www      8508: sub modifyuser {
1.206     matthew  8509:     my ($udom,    $uname, $uid,
                   8510:         $umode,   $upass, $first,
                   8511:         $middle,  $last,  $gene,
1.1058    raeburn  8512:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8513:     $udom= &LONCAPA::clean_domain($udom);
                   8514:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8515:     my $showcandelete = 'none';
                   8516:     if (ref($candelete) eq 'ARRAY') {
                   8517:         if (@{$candelete} > 0) {
                   8518:             $showcandelete = join(', ',@{$candelete});
                   8519:         }
                   8520:     }
1.81      www      8521:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8522:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8523: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8524:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8525:                                      ' desiredhome not specified'). 
1.620     albertel 8526:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8527:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8528:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8529:     my $newuser;
                   8530:     if ($uhome eq 'no_host') {
                   8531:         $newuser = 1;
                   8532:     }
1.80      www      8533: # ----------------------------------------------------------------- Create User
1.406     albertel 8534:     if (($uhome eq 'no_host') && 
                   8535: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8536:         my $unhome='';
1.844     albertel 8537:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8538:             $unhome = $desiredhome;
1.620     albertel 8539: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8540: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8541:         } else { # load balancing routine for determining $unhome
1.81      www      8542:             my $loadm=10000000;
1.841     albertel 8543: 	    my %servers = &get_servers($udom,'library');
                   8544: 	    foreach my $tryserver (keys(%servers)) {
                   8545: 		my $answer=reply('load',$tryserver);
                   8546: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8547: 		    $loadm=$answer;
                   8548: 		    $unhome=$tryserver;
                   8549: 		}
1.80      www      8550: 	    }
                   8551:         }
                   8552:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8553: 	    return 'error: unable to find a home server for '.$uname.
                   8554:                    ' in domain '.$udom;
1.80      www      8555:         }
                   8556:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8557:                          &escape($upass),$unhome);
                   8558: 	unless ($reply eq 'ok') {
                   8559:             return 'error: '.$reply;
                   8560:         }   
1.230     stredwic 8561:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8562:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8563: 	    return 'error: unable verify users home machine.';
1.80      www      8564:         }
1.209     matthew  8565:     }   # End of creation of new user
1.80      www      8566: # ---------------------------------------------------------------------- Add ID
                   8567:     if ($uid) {
                   8568:        $uid=~tr/A-Z/a-z/;
                   8569:        my %uidhash=&idrget($udom,$uname);
1.196     www      8570:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8571:          && (!$forceid)) {
1.80      www      8572: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8573: 	      return 'error: user id "'.$uid.'" does not match '.
                   8574:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8575:           }
                   8576:        } else {
                   8577: 	  &idput($udom,($uname => $uid));
                   8578:        }
                   8579:     }
                   8580: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8581:     my @tmp=&get('environment',
1.899     raeburn  8582: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8583:                     'permanentemail','inststatus'],
1.134     albertel 8584: 		   $udom,$uname);
1.1075    raeburn  8585:     my (%names,%oldnames);
1.313     matthew  8586:     if ($tmp[0] =~ m/^error:.*/) { 
                   8587:         %names=(); 
                   8588:     } else {
                   8589:         %names = @tmp;
1.1075    raeburn  8590:         %oldnames = %names;
1.313     matthew  8591:     }
1.388     www      8592: #
1.1058    raeburn  8593: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8594: # of users did not contain them), do not overwrite existing values
                   8595: # unless field is in $candelete array ref.  
                   8596: #
                   8597: 
                   8598:     my @fields = ('firstname','middlename','lastname','generation',
                   8599:                   'permanentemail','id');
                   8600:     my %newvalues;
                   8601:     if (ref($candelete) eq 'ARRAY') {
                   8602:         foreach my $field (@fields) {
                   8603:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8604:                 if ($field eq 'firstname') {
                   8605:                     $names{$field} = $first;
                   8606:                 } elsif ($field eq 'middlename') {
                   8607:                     $names{$field} = $middle;
                   8608:                 } elsif ($field eq 'lastname') {
                   8609:                     $names{$field} = $last;
                   8610:                 } elsif ($field eq 'generation') { 
                   8611:                     $names{$field} = $gene;
                   8612:                 } elsif ($field eq 'permanentemail') {
                   8613:                     $names{$field} = $email;
                   8614:                 } elsif ($field eq 'id') {
                   8615:                     $names{$field}  = $uid;
                   8616:                 }
                   8617:             }
                   8618:         }
                   8619:     }
1.388     www      8620:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8621:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8622:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8623:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8624:     if ($email) {
                   8625:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8626:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8627:     }
1.899     raeburn  8628:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8629:     if (defined($inststatus)) {
                   8630:         $names{'inststatus'} = '';
                   8631:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8632:         if (ref($usertypes) eq 'HASH') {
                   8633:             my @okstatuses; 
                   8634:             foreach my $item (split(/:/,$inststatus)) {
                   8635:                 if (defined($usertypes->{$item})) {
                   8636:                     push(@okstatuses,$item);  
                   8637:                 }
                   8638:             }
                   8639:             if (@okstatuses) {
                   8640:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8641:             }
                   8642:         }
                   8643:     }
1.1075    raeburn  8644:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8645:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8646:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8647:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8648:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8649:     } else {
                   8650:         $logmsg .= ' during self creation';
                   8651:     }
1.1075    raeburn  8652:     my $changed;
                   8653:     if ($newuser) {
                   8654:         $changed = 1;
                   8655:     } else {
                   8656:         foreach my $field (@fields) {
                   8657:             if ($names{$field} ne $oldnames{$field}) {
                   8658:                 $changed = 1;
                   8659:                 last;
                   8660:             }
                   8661:         }
                   8662:     }
                   8663:     unless ($changed) {
                   8664:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8665:         &logthis($logmsg);
                   8666:         return 'ok';
                   8667:     }
                   8668:     my $reply = &put('environment', \%names, $udom,$uname);
                   8669:     if ($reply ne 'ok') { 
                   8670:         return 'error: '.$reply;
                   8671:     }
1.1087    raeburn  8672:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8673:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8674:     }
1.1075    raeburn  8675:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8676:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8677:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8678:     &logthis($logmsg);
1.134     albertel 8679:     return 'ok';
1.80      www      8680: }
                   8681: 
1.81      www      8682: # -------------------------------------------------------------- Modify student
1.80      www      8683: 
1.81      www      8684: sub modifystudent {
                   8685:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8686:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8687:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8688:     if (!$cid) {
1.620     albertel 8689: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8690: 	    return 'not_in_class';
                   8691: 	}
1.80      www      8692:     }
                   8693: # --------------------------------------------------------------- Make the user
1.81      www      8694:     my $reply=&modifyuser
1.209     matthew  8695: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8696:          $desiredhome,$email,$inststatus);
1.80      www      8697:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8698:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8699:     # student's environment
1.297     matthew  8700:     $uid = undef if (!$forceid);
1.455     albertel 8701:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8702:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8703:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8704:     return $reply;
                   8705: }
                   8706: 
                   8707: sub modify_student_enrollment {
1.1216    raeburn  8708:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8709:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8710:     my ($cdom,$cnum,$chome);
                   8711:     if (!$cid) {
1.620     albertel 8712: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8713: 	    return 'not_in_class';
                   8714: 	}
1.620     albertel 8715: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8716: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8717:     } else {
                   8718: 	($cdom,$cnum)=split(/_/,$cid);
                   8719:     }
1.620     albertel 8720:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8721:     if (!$chome) {
1.457     raeburn  8722: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8723:     }
1.455     albertel 8724:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8725:     # Make sure the user exists
1.81      www      8726:     my $uhome=&homeserver($uname,$udom);
                   8727:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8728: 	return 'error: no such user';
                   8729:     }
1.297     matthew  8730:     # Get student data if we were not given enough information
                   8731:     if (!defined($first)  || $first  eq '' || 
                   8732:         !defined($last)   || $last   eq '' || 
                   8733:         !defined($uid)    || $uid    eq '' || 
                   8734:         !defined($middle) || $middle eq '' || 
                   8735:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8736:         # They did not supply us with enough data to enroll the student, so
                   8737:         # we need to pick up more information.
1.297     matthew  8738:         my %tmp = &get('environment',
1.294     matthew  8739:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8740:                        ,$udom,$uname);
                   8741: 
1.800     albertel 8742:         #foreach my $key (keys(%tmp)) {
                   8743:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8744:         #}
1.294     matthew  8745:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8746:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8747:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8748:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8749:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8750:     }
1.556     albertel 8751:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8752:     my $user = "$uname:$udom";
                   8753:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8754:     my $reply=cput('classlist',
1.1148    raeburn  8755: 		   {$user => 
1.1216    raeburn  8756: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8757: 		   $cdom,$cnum);
1.1148    raeburn  8758:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8759:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8760:     } else { 
1.81      www      8761: 	return 'error: '.$reply;
                   8762:     }
1.297     matthew  8763:     # Add student role to user
1.83      www      8764:     my $uurl='/'.$cid;
1.81      www      8765:     $uurl=~s/\_/\//g;
                   8766:     if ($usec) {
                   8767: 	$uurl.='/'.$usec;
                   8768:     }
1.1148    raeburn  8769:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8770:                              $selfenroll,$context);
                   8771:     if ($result ne 'ok') {
                   8772:         if ($old_entry{$user} ne '') {
                   8773:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8774:         } else {
                   8775:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8776:         }
                   8777:     }
                   8778:     return $result; 
1.21      www      8779: }
                   8780: 
1.556     albertel 8781: sub format_name {
                   8782:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8783:     my $name;
                   8784:     if ($first ne 'lastname') {
                   8785: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8786:     } else {
                   8787: 	if ($lastname=~/\S/) {
                   8788: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8789: 	    $name=~s/\s+,/,/;
                   8790: 	} else {
                   8791: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8792: 	}
                   8793:     }
                   8794:     $name=~s/^\s+//;
                   8795:     $name=~s/\s+$//;
                   8796:     $name=~s/\s+/ /g;
                   8797:     return $name;
                   8798: }
                   8799: 
1.84      www      8800: # ------------------------------------------------- Write to course preferences
                   8801: 
                   8802: sub writecoursepref {
                   8803:     my ($courseid,%prefs)=@_;
                   8804:     $courseid=~s/^\///;
                   8805:     $courseid=~s/\_/\//g;
                   8806:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8807:     my $chome=homeserver($cnum,$cdomain);
                   8808:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8809: 	return 'error: no such course';
                   8810:     }
                   8811:     my $cstring='';
1.800     albertel 8812:     foreach my $pref (keys(%prefs)) {
                   8813: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8814:     }
1.84      www      8815:     $cstring=~s/\&$//;
                   8816:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8817: }
                   8818: 
                   8819: # ---------------------------------------------------------- Make/modify course
                   8820: 
                   8821: sub createcourse {
1.741     raeburn  8822:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8823:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8824:     $url=&declutter($url);
                   8825:     my $cid='';
1.1028    raeburn  8826:     if ($context eq 'requestcourses') {
                   8827:         my $can_create = 0;
                   8828:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8829:         if ($udom eq $ownerdom) {
                   8830:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8831:                                   $context)) {
                   8832:                 $can_create = 1;
                   8833:             }
                   8834:         } else {
                   8835:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8836:                                            $category);
                   8837:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8838:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8839:                 if (@curr > 0) {
                   8840:                     my @options = qw(approval validate autolimit);
                   8841:                     my $optregex = join('|',@options);
                   8842:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8843:                         $can_create = 1;
                   8844:                     }
                   8845:                 }
                   8846:             }
                   8847:         }
                   8848:         if ($can_create) {
                   8849:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8850:                 unless (&allowed('ccc',$udom)) {
                   8851:                     return 'refused'; 
                   8852:                 }
1.1017    raeburn  8853:             }
                   8854:         } else {
                   8855:             return 'refused';
                   8856:         }
1.1028    raeburn  8857:     } elsif (!&allowed('ccc',$udom)) {
                   8858:         return 'refused';
1.84      www      8859:     }
1.1011    raeburn  8860: # --------------------------------------------------------------- Get Unique ID
                   8861:     my $uname;
                   8862:     if ($cnum =~ /^$match_courseid$/) {
                   8863:         my $chome=&homeserver($cnum,$udom,'true');
                   8864:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8865:             $uname = $cnum;
                   8866:         } else {
1.1038    raeburn  8867:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8868:         }
                   8869:     } else {
1.1038    raeburn  8870:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8871:     }
                   8872:     return $uname if ($uname =~ /^error/);
                   8873: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8874:     if (!defined($course_server)) {
                   8875:         if (defined(&domain($udom,'primary'))) {
                   8876:             $course_server = &domain($udom,'primary');
                   8877:         } else {
                   8878:             $course_server = $env{'user.home'}; 
                   8879:         }
                   8880:     }
                   8881:     my %host_servers =
                   8882:         &Apache::lonnet::get_servers($udom,'library');
                   8883:     unless ($host_servers{$course_server}) {
                   8884:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8885:     }
1.84      www      8886: # ------------------------------------------------------------- Make the course
                   8887:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8888:                       $course_server);
1.84      www      8889:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8890:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8891:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8892: 	return 'error: no such course';
                   8893:     }
1.271     www      8894: # ----------------------------------------------------------------- Course made
1.516     raeburn  8895: # log existence
1.1029    raeburn  8896:     my $now = time;
1.918     raeburn  8897:     my $newcourse = {
                   8898:                     $udom.'_'.$uname => {
1.921     raeburn  8899:                                      description => $description,
                   8900:                                      inst_code   => $inst_code,
                   8901:                                      owner       => $course_owner,
                   8902:                                      type        => $crstype,
1.1029    raeburn  8903:                                      creator     => $env{'user.name'}.':'.
                   8904:                                                     $env{'user.domain'},
                   8905:                                      created     => $now,
                   8906:                                      context     => $context,
1.918     raeburn  8907:                                                 },
                   8908:                     };
1.921     raeburn  8909:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8910: # set toplevel url
1.271     www      8911:     my $topurl=$url;
                   8912:     unless ($nonstandard) {
                   8913: # ------------------------------------------ For standard courses, make top url
                   8914:         my $mapurl=&clutter($url);
1.278     www      8915:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8916:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8917: <map>
                   8918: <resource id="1" type="start"></resource>
                   8919: <resource id="2" src="$mapurl"></resource>
                   8920: <resource id="3" type="finish"></resource>
                   8921: <link index="1" from="1" to="2"></link>
                   8922: <link index="2" from="2" to="3"></link>
                   8923: </map>
                   8924: ENDINITMAP
                   8925:         $topurl=&declutter(
1.638     albertel 8926:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8927:                           );
                   8928:     }
                   8929: # ----------------------------------------------------------- Write preferences
1.84      www      8930:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8931:                      ('description'              => $description,
                   8932:                       'url'                      => $topurl,
                   8933:                       'internal.creator'         => $env{'user.name'}.':'.
                   8934:                                                     $env{'user.domain'},
                   8935:                       'internal.created'         => $now,
                   8936:                       'internal.creationcontext' => $context)
                   8937:                     );
1.84      www      8938:     return '/'.$udom.'/'.$uname;
                   8939: }
                   8940: 
1.1011    raeburn  8941: # ------------------------------------------------------------------- Create ID
                   8942: sub generate_coursenum {
1.1038    raeburn  8943:     my ($udom,$crstype) = @_;
1.1011    raeburn  8944:     my $domdesc = &domain($udom);
                   8945:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8946:     my $first;
                   8947:     if ($crstype eq 'Community') {
                   8948:         $first = '0';
                   8949:     } else {
                   8950:         $first = int(1+rand(9)); 
                   8951:     } 
                   8952:     my $uname=$first.
1.1011    raeburn  8953:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8954:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8955:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8956: # ----------------------------------------------- Make sure that does not exist
                   8957:     my $uhome=&homeserver($uname,$udom,'true');
                   8958:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8959:         if ($crstype eq 'Community') {
                   8960:             $first = '0';
                   8961:         } else {
                   8962:             $first = int(1+rand(9));
                   8963:         }
                   8964:         $uname=$first.
1.1011    raeburn  8965:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8966:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8967:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8968:         $uhome=&homeserver($uname,$udom,'true');
                   8969:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8970:             return 'error: unable to generate unique course-ID';
                   8971:         }
                   8972:     }
                   8973:     return $uname;
                   8974: }
                   8975: 
1.813     albertel 8976: sub is_course {
1.1167    droeschl 8977:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8978:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8979: 
                   8980:     return unless $cdom and $cnum;
                   8981: 
                   8982:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8983:         '.');
                   8984: 
1.1219    raeburn  8985:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8986:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8987: }
                   8988: 
1.1015    raeburn  8989: sub store_userdata {
                   8990:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8991:     my $result;
1.1016    raeburn  8992:     if ($datakey ne '') {
1.1013    raeburn  8993:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8994:             if ($udom eq '' || $uname eq '') {
                   8995:                 $udom = $env{'user.domain'};
                   8996:                 $uname = $env{'user.name'};
                   8997:             }
                   8998:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8999:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9000:                 $result = 'error: no_host';
                   9001:             } else {
                   9002:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9003:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9004: 
                   9005:                 my $namevalue='';
                   9006:                 foreach my $key (keys(%{$storehash})) {
                   9007:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9008:                 }
                   9009:                 $namevalue=~s/\&$//;
1.1224    raeburn  9010:                 unless ($namespace eq 'courserequests') {
                   9011:                     $datakey = &escape($datakey);
                   9012:                 }
1.1105    raeburn  9013:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9014:                                   $namevalue,$uhome);
1.1013    raeburn  9015:             }
                   9016:         } else {
                   9017:             $result = 'error: data to store was not a hash reference'; 
                   9018:         }
                   9019:     } else {
                   9020:         $result= 'error: invalid requestkey'; 
                   9021:     }
                   9022:     return $result;
                   9023: }
                   9024: 
1.21      www      9025: # ---------------------------------------------------------- Assign Custom Role
                   9026: 
                   9027: sub assigncustomrole {
1.957     raeburn  9028:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9029:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9030:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9031: }
                   9032: 
                   9033: # ----------------------------------------------------------------- Revoke Role
                   9034: 
                   9035: sub revokerole {
1.957     raeburn  9036:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9037:     my $now=time;
1.965     raeburn  9038:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9039: }
                   9040: 
                   9041: # ---------------------------------------------------------- Revoke Custom Role
                   9042: 
                   9043: sub revokecustomrole {
1.957     raeburn  9044:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9045:     my $now=time;
1.357     www      9046:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9047:            $deleteflag,$selfenroll,$context);
1.17      www      9048: }
                   9049: 
1.533     banghart 9050: # ------------------------------------------------------------ Disk usage
1.535     albertel 9051: sub diskusage {
1.955     raeburn  9052:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9053:     $directorypath =~ s/\/$//;
                   9054:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9055:                        .&escape($getpropath).':'.&escape($uname).':'
                   9056:                        .&escape($udom),homeserver($uname,$udom));
                   9057:     if ($listing eq 'unknown_cmd') {
                   9058:         if ($getpropath) {
                   9059:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9060:         }
                   9061:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9062:     }
1.514     albertel 9063:     return $listing;
1.512     banghart 9064: }
                   9065: 
1.566     banghart 9066: sub is_locked {
1.1096    raeburn  9067:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9068:     my @check;
                   9069:     my $is_locked;
1.1093    raeburn  9070:     push (@check,$file_name);
1.613     albertel 9071:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9072: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9073:     my ($tmp)=keys(%locked);
                   9074:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9075:     
1.566     banghart 9076:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9077:         $is_locked = 'false';
                   9078:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9079:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9080:                $is_locked = 'true';
1.1096    raeburn  9081:                if (ref($which) eq 'ARRAY') {
                   9082:                    push(@{$which},$entry);
                   9083:                } else {
                   9084:                    last;
                   9085:                }
1.745     raeburn  9086:            }
                   9087:        }
1.566     banghart 9088:     } else {
                   9089:         $is_locked = 'false';
                   9090:     }
1.1093    raeburn  9091:     return $is_locked;
1.566     banghart 9092: }
                   9093: 
1.759     albertel 9094: sub declutter_portfile {
                   9095:     my ($file) = @_;
1.833     albertel 9096:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9097:     return $file;
                   9098: }
                   9099: 
1.559     banghart 9100: # ------------------------------------------------------------- Mark as Read Only
                   9101: 
                   9102: sub mark_as_readonly {
                   9103:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9104:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9105:     my ($tmp)=keys(%current_permissions);
                   9106:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9107:     foreach my $file (@{$files}) {
1.759     albertel 9108: 	$file = &declutter_portfile($file);
1.561     banghart 9109:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9110:     }
1.613     albertel 9111:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9112:     return;
                   9113: }
                   9114: 
1.572     banghart 9115: # ------------------------------------------------------------Save Selected Files
                   9116: 
                   9117: sub save_selected_files {
                   9118:     my ($user, $path, @files) = @_;
                   9119:     my $filename = $user."savedfiles";
1.573     banghart 9120:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9121:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9122:     foreach my $file (@files) {
1.620     albertel 9123:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9124:     }
                   9125:     foreach my $file (@other_files) {
1.574     banghart 9126:         print (OUT $file."\n");
1.572     banghart 9127:     }
1.574     banghart 9128:     close (OUT);
1.572     banghart 9129:     return 'ok';
                   9130: }
                   9131: 
1.574     banghart 9132: sub clear_selected_files {
                   9133:     my ($user) = @_;
                   9134:     my $filename = $user."savedfiles";
1.1117    foxr     9135:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9136:     print (OUT undef);
                   9137:     close (OUT);
                   9138:     return ("ok");    
                   9139: }
                   9140: 
1.572     banghart 9141: sub files_in_path {
                   9142:     my ($user, $path) = @_;
                   9143:     my $filename = $user."savedfiles";
                   9144:     my %return_files;
1.1117    foxr     9145:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9146:     while (my $line_in = <IN>) {
1.574     banghart 9147:         chomp ($line_in);
                   9148:         my @paths_and_file = split (m!/!, $line_in);
                   9149:         my $file_part = pop (@paths_and_file);
                   9150:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9151:         $path_part.='/';
                   9152:         my $path_and_file = $path_part.$file_part;
                   9153:         if ($path_part eq $path) {
                   9154:             $return_files{$file_part}= 'selected';
                   9155:         }
                   9156:     }
1.574     banghart 9157:     close (IN);
                   9158:     return (\%return_files);
1.572     banghart 9159: }
                   9160: 
                   9161: # called in portfolio select mode, to show files selected NOT in current directory
                   9162: sub files_not_in_path {
                   9163:     my ($user, $path) = @_;
                   9164:     my $filename = $user."savedfiles";
                   9165:     my @return_files;
                   9166:     my $path_part;
1.1117    foxr     9167:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9168:     while (my $line = <IN>) {
1.572     banghart 9169:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9170:         my @paths_and_file = split(m|/|, $line);
                   9171:         my $file_part = pop(@paths_and_file);
                   9172:         chomp($file_part);
                   9173:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9174:         $path_part .= '/';
                   9175:         my $path_and_file = $path_part.$file_part;
                   9176:         if ($path_part ne $path) {
1.800     albertel 9177:             push(@return_files, ($path_and_file));
1.572     banghart 9178:         }
                   9179:     }
1.800     albertel 9180:     close(OUT);
1.574     banghart 9181:     return (@return_files);
1.572     banghart 9182: }
                   9183: 
1.1273    raeburn  9184: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9185:  
                   9186: sub portfiles_versioning {
                   9187:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9188:     my $portfolio_root = '/userfiles/portfolio';
                   9189:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9190:     foreach my $file (@{$portfiles}) {
                   9191:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9192:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9193:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9194:         my $getpropath = 1;
                   9195:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9196:                                              $stu_name,$getpropath);
                   9197:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9198:         my $new_answer = 
                   9199:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9200:         if ($new_answer ne 'problem getting file') {
                   9201:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9202:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9203:                               [$symb,$env{'request.course.id'},'graded']);
                   9204:         }
                   9205:     }
                   9206: }
                   9207: 
                   9208: sub get_next_version {
                   9209:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9210:     my $version;
                   9211:     if (ref($dir_list) eq 'ARRAY') {
                   9212:         foreach my $row (@{$dir_list}) {
                   9213:             my ($file) = split(/\&/,$row,2);
                   9214:             my ($file_name,$file_version,$file_ext) =
                   9215:                 &file_name_version_ext($file);
                   9216:             if (($file_name eq $answer_name) &&
                   9217:                 ($file_ext eq $answer_ext)) {
                   9218:                      # gets here if filename and extension match,
                   9219:                      # regardless of version
                   9220:                 if ($file_version ne '') {
                   9221:                     # a versioned file is found  so save it for later
                   9222:                     if ($file_version > $version) {
                   9223:                         $version = $file_version;
                   9224:                     }
                   9225:                 }
                   9226:             }
                   9227:         }
                   9228:     }
                   9229:     $version ++;
                   9230:     return($version);
                   9231: }
                   9232: 
                   9233: sub version_selected_portfile {
                   9234:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9235:     my ($answer_name,$answer_ver,$answer_ext) =
                   9236:         &file_name_version_ext($file_name);
                   9237:     my $new_answer;
                   9238:     $env{'form.copy'} =
                   9239:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9240:     if($env{'form.copy'} eq '-1') {
                   9241:         $new_answer = 'problem getting file';
                   9242:     } else {
                   9243:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9244:         my $copy_result = 
                   9245:             &finishuserfileupload($stu_name,$domain,'copy',
                   9246:                                   '/portfolio'.$directory.$new_answer);
                   9247:     }
                   9248:     undef($env{'form.copy'});
                   9249:     return ($new_answer);
                   9250: }
                   9251: 
                   9252: sub file_name_version_ext {
                   9253:     my ($file)=@_;
                   9254:     my @file_parts = split(/\./, $file);
                   9255:     my ($name,$version,$ext);
                   9256:     if (@file_parts > 1) {
                   9257:         $ext=pop(@file_parts);
                   9258:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9259:             $version=pop(@file_parts);
                   9260:         }
                   9261:         $name=join('.',@file_parts);
                   9262:     } else {
                   9263:         $name=join('.',@file_parts);
                   9264:     }
                   9265:     return($name,$version,$ext);
                   9266: }
                   9267: 
1.745     raeburn  9268: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9269: 
1.745     raeburn  9270: sub get_portfile_permissions {
                   9271:     my ($domain,$user) = @_;
1.613     albertel 9272:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9273:     my ($tmp)=keys(%current_permissions);
                   9274:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9275:     return \%current_permissions;
                   9276: }
                   9277: 
                   9278: #---------------------------------------------Get portfolio file access controls
                   9279: 
1.749     raeburn  9280: sub get_access_controls {
1.745     raeburn  9281:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9282:     my %access;
                   9283:     my $real_file = $file;
                   9284:     $file =~ s/\.meta$//;
1.745     raeburn  9285:     if (defined($file)) {
1.749     raeburn  9286:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9287:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9288:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9289:             }
                   9290:         }
1.745     raeburn  9291:     } else {
1.749     raeburn  9292:         foreach my $key (keys(%{$current_permissions})) {
                   9293:             if ($key =~ /\0accesscontrol$/) {
                   9294:                 if (defined($group)) {
                   9295:                     if ($key !~ m-^\Q$group\E/-) {
                   9296:                         next;
                   9297:                     }
                   9298:                 }
                   9299:                 my ($fullpath) = split(/\0/,$key);
                   9300:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9301:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9302:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9303:                     }
                   9304:                 }
                   9305:             }
                   9306:         }
                   9307:     }
                   9308:     return %access;
                   9309: }
                   9310: 
                   9311: sub modify_access_controls {
                   9312:     my ($file_name,$changes,$domain,$user)=@_;
                   9313:     my ($outcome,$deloutcome);
                   9314:     my %store_permissions;
                   9315:     my %new_values;
                   9316:     my %new_control;
                   9317:     my %translation;
                   9318:     my @deletions = ();
                   9319:     my $now = time;
                   9320:     if (exists($$changes{'activate'})) {
                   9321:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9322:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9323:             my $numnew = scalar(@newitems);
                   9324:             for (my $i=0; $i<$numnew; $i++) {
                   9325:                 my $newkey = $newitems[$i];
                   9326:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9327:                 if ($newkey =~ /^\d+:/) { 
                   9328:                     $newkey =~ s/^(\d+)/$newid/;
                   9329:                     $translation{$1} = $newid;
                   9330:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9331:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9332:                     $translation{$1} = $newid;
                   9333:                 }
1.749     raeburn  9334:                 $new_values{$file_name."\0".$newkey} = 
                   9335:                                           $$changes{'activate'}{$newitems[$i]};
                   9336:                 $new_control{$newkey} = $now;
                   9337:             }
                   9338:         }
                   9339:     }
                   9340:     my %todelete;
                   9341:     my %changed_items;
                   9342:     foreach my $action ('delete','update') {
                   9343:         if (exists($$changes{$action})) {
                   9344:             if (ref($$changes{$action}) eq 'HASH') {
                   9345:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9346:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9347:                     if ($action eq 'delete') { 
                   9348:                         $todelete{$itemnum} = 1;
                   9349:                     } else {
                   9350:                         $changed_items{$itemnum} = $key;
                   9351:                     }
                   9352:                 }
1.745     raeburn  9353:             }
                   9354:         }
1.749     raeburn  9355:     }
                   9356:     # get lock on access controls for file.
                   9357:     my $lockhash = {
                   9358:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9359:                                                        ':'.$env{'user.domain'},
                   9360:                    }; 
                   9361:     my $tries = 0;
                   9362:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9363:    
                   9364:     while (($gotlock ne 'ok') && $tries <3) {
                   9365:         $tries ++;
                   9366:         sleep 1;
                   9367:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9368:     }
                   9369:     if ($gotlock eq 'ok') {
                   9370:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9371:         my ($tmp)=keys(%curr_permissions);
                   9372:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9373:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9374:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9375:             if (ref($curr_controls) eq 'HASH') {
                   9376:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9377:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9378:                     if (defined($todelete{$itemnum})) {
                   9379:                         push(@deletions,$file_name."\0".$control_item);
                   9380:                     } else {
                   9381:                         if (defined($changed_items{$itemnum})) {
                   9382:                             $new_control{$changed_items{$itemnum}} = $now;
                   9383:                             push(@deletions,$file_name."\0".$control_item);
                   9384:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9385:                         } else {
                   9386:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9387:                         }
                   9388:                     }
1.745     raeburn  9389:                 }
                   9390:             }
                   9391:         }
1.970     raeburn  9392:         my ($group);
                   9393:         if (&is_course($domain,$user)) {
                   9394:             ($group,my $file) = split(/\//,$file_name,2);
                   9395:         }
1.749     raeburn  9396:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9397:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9398:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9399:         #  remove lock
                   9400:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9401:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9402:         my $sqlresult =
1.970     raeburn  9403:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9404:                                     $group);
1.749     raeburn  9405:     } else {
                   9406:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9407:     }
1.749     raeburn  9408:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9409: }
                   9410: 
1.827     raeburn  9411: sub make_public_indefinitely {
1.1271    raeburn  9412:     my (@requrl) = @_;
                   9413:     return &automated_portfile_access('public',\@requrl);
                   9414: }
                   9415: 
                   9416: sub automated_portfile_access {
                   9417:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9418:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9419:         return 'invalid';
                   9420:     }
1.1271    raeburn  9421:     my %urls;
                   9422:     if (ref($addsref) eq 'ARRAY') {
                   9423:         foreach my $requrl (@{$addsref}) {
                   9424:             if (&is_portfolio_url($requrl)) {
                   9425:                 unless (exists($urls{$requrl})) {
                   9426:                     $urls{$requrl} = 'add';
                   9427:                 }
                   9428:             }
                   9429:         }
                   9430:     }
                   9431:     if (ref($delsref) eq 'ARRAY') {
                   9432:         foreach my $requrl (@{$delsref}) { 
                   9433:             if (&is_portfolio_url($requrl)) {
                   9434:                 unless (exists($urls{$requrl})) {
                   9435:                     $urls{$requrl} = 'delete'; 
                   9436:                 }
                   9437:             }
                   9438:         }
                   9439:     }
                   9440:     unless (keys(%urls)) {
                   9441:         return 'invalid';
                   9442:     }
                   9443:     my $ip;
                   9444:     if ($accesstype eq 'ip') {
                   9445:         if (ref($info) eq 'HASH') {
                   9446:             if ($info->{'ip'} ne '') {
                   9447:                 $ip = $info->{'ip'};
                   9448:             }
                   9449:         }
                   9450:         if ($ip eq '') {
                   9451:             return 'invalid';
                   9452:         }
                   9453:     }
                   9454:     my $errors;
1.827     raeburn  9455:     my $now = time;
1.1271    raeburn  9456:     my %current_perms;
                   9457:     foreach my $requrl (sort(keys(%urls))) {
                   9458:         my $action;
                   9459:         if ($urls{$requrl} eq 'add') {
                   9460:             $action = 'activate';
                   9461:         } else {
                   9462:             $action = 'none';
                   9463:         }
                   9464:         my $aclnum = 0;
1.827     raeburn  9465:         my (undef,$udom,$unum,$file_name,$group) =
                   9466:             &parse_portfolio_url($requrl);
1.1271    raeburn  9467:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9468:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9469:         }
                   9470:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9471:                                                    $group,$file_name);
                   9472:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9473:             my ($num,$scope,$end,$start) = 
                   9474:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9475:             if ($scope eq $accesstype) {
                   9476:                 if (($start <= $now) && ($end == 0)) {
                   9477:                     if ($accesstype eq 'ip') {
                   9478:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9479:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9480:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9481:                                     if ($urls{$requrl} eq 'add') {
                   9482:                                         $action = 'none';
                   9483:                                         last;
                   9484:                                     } else {
                   9485:                                         $action = 'delete';
                   9486:                                         $aclnum = $num;
                   9487:                                         last;
                   9488:                                     }
                   9489:                                 }
                   9490:                             }
                   9491:                         }
                   9492:                     } elsif ($accesstype eq 'public') {
                   9493:                         if ($urls{$requrl} eq 'add') {
                   9494:                             $action = 'none';
                   9495:                             last;
                   9496:                         } else {
                   9497:                             $action = 'delete';
                   9498:                             $aclnum = $num;
                   9499:                             last;
                   9500:                         }
                   9501:                     }
                   9502:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9503:                     $action = 'update';
                   9504:                     $aclnum = $num;
1.1271    raeburn  9505:                     last;
1.827     raeburn  9506:                 }
                   9507:             }
                   9508:         }
                   9509:         if ($action eq 'none') {
1.1271    raeburn  9510:             next;
1.827     raeburn  9511:         } else {
                   9512:             my %changes;
                   9513:             my $newend = 0;
                   9514:             my $newstart = $now;
1.1271    raeburn  9515:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9516:             $changes{$action}{$newkey} = {
1.1271    raeburn  9517:                 type => $accesstype,
1.827     raeburn  9518:                 time => {
                   9519:                     start => $newstart,
                   9520:                     end   => $newend,
                   9521:                 },
                   9522:             };
1.1271    raeburn  9523:             if ($accesstype eq 'ip') {
                   9524:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9525:             }
1.827     raeburn  9526:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9527:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9528:             unless ($outcome eq 'ok') {
                   9529:                 $errors .= $outcome.' ';
                   9530:             }
1.827     raeburn  9531:         }
1.1271    raeburn  9532:     }
                   9533:     if ($errors) {
                   9534:         $errors =~ s/\s$//;
                   9535:         return $errors;
1.827     raeburn  9536:     } else {
1.1271    raeburn  9537:         return 'ok';
1.827     raeburn  9538:     }
                   9539: }
                   9540: 
1.745     raeburn  9541: #------------------------------------------------------Get Marked as Read Only
                   9542: 
                   9543: sub get_marked_as_readonly {
                   9544:     my ($domain,$user,$what,$group) = @_;
                   9545:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9546:     my @readonly_files;
1.629     banghart 9547:     my $cmp1=$what;
                   9548:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9549:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9550:         if (defined($group)) {
                   9551:             if ($file_name !~ m-^\Q$group\E/-) {
                   9552:                 next;
                   9553:             }
                   9554:         }
1.561     banghart 9555:         if (ref($value) eq "ARRAY"){
                   9556:             foreach my $stored_what (@{$value}) {
1.629     banghart 9557:                 my $cmp2=$stored_what;
1.759     albertel 9558:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9559:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9560:                 }
1.629     banghart 9561:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9562:                     push(@readonly_files, $file_name);
1.745     raeburn  9563:                     last;
1.563     banghart 9564:                 } elsif (!defined($what)) {
                   9565:                     push(@readonly_files, $file_name);
1.745     raeburn  9566:                     last;
1.561     banghart 9567:                 }
                   9568:             }
1.745     raeburn  9569:         }
1.561     banghart 9570:     }
                   9571:     return @readonly_files;
                   9572: }
1.577     banghart 9573: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9574: 
1.577     banghart 9575: sub get_marked_as_readonly_hash {
1.745     raeburn  9576:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9577:     my %readonly_files;
1.745     raeburn  9578:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9579:         if (defined($group)) {
                   9580:             if ($file_name !~ m-^\Q$group\E/-) {
                   9581:                 next;
                   9582:             }
                   9583:         }
1.577     banghart 9584:         if (ref($value) eq "ARRAY"){
                   9585:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9586:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9587:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9588:                         if ($lock_descriptor eq 'graded') {
                   9589:                             $readonly_files{$file_name} = 'graded';
                   9590:                         } elsif ($lock_descriptor eq 'handback') {
                   9591:                             $readonly_files{$file_name} = 'handback';
                   9592:                         } else {
                   9593:                             if (!exists($readonly_files{$file_name})) {
                   9594:                                 $readonly_files{$file_name} = 'locked';
                   9595:                             }
                   9596:                         }
1.745     raeburn  9597:                     }
1.750     banghart 9598:                 } 
1.577     banghart 9599:             }
                   9600:         } 
                   9601:     }
                   9602:     return %readonly_files;
                   9603: }
1.559     banghart 9604: # ------------------------------------------------------------ Unmark as Read Only
                   9605: 
                   9606: sub unmark_as_readonly {
1.629     banghart 9607:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9608:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9609:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9610:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9611:     my $symb_crs = $what;
                   9612:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9613:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9614:     my ($tmp)=keys(%current_permissions);
                   9615:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9616:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9617:     foreach my $file (@readonly_files) {
1.759     albertel 9618: 	my $clean_file = &declutter_portfile($file);
                   9619: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9620: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9621:         my @new_locks;
                   9622:         my @del_keys;
                   9623:         if (ref($current_locks) eq "ARRAY"){
                   9624:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9625:                 my $compare=$locker;
1.749     raeburn  9626:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9627:                     $compare=join('',@{$locker});
1.746     raeburn  9628:                     if ($compare ne $symb_crs) {
                   9629:                         push(@new_locks, $locker);
                   9630:                     }
1.563     banghart 9631:                 }
                   9632:             }
1.650     albertel 9633:             if (scalar(@new_locks) > 0) {
1.563     banghart 9634:                 $current_permissions{$file} = \@new_locks;
                   9635:             } else {
                   9636:                 push(@del_keys, $file);
1.613     albertel 9637:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9638:                 delete($current_permissions{$file});
1.563     banghart 9639:             }
                   9640:         }
1.561     banghart 9641:     }
1.613     albertel 9642:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9643:     return;
                   9644: }
1.512     banghart 9645: 
1.17      www      9646: # ------------------------------------------------------------ Directory lister
                   9647: 
                   9648: sub dirlist {
1.955     raeburn  9649:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9650:     $uri=~s/^\///;
                   9651:     $uri=~s/\/$//;
1.253     stredwic 9652:     my ($udom, $uname);
1.955     raeburn  9653:     if ($getuserdir) {
1.253     stredwic 9654:         $udom = $userdomain;
                   9655:         $uname = $username;
1.955     raeburn  9656:     } else {
                   9657:         (undef,$udom,$uname)=split(/\//,$uri);
                   9658:         if(defined($userdomain)) {
                   9659:             $udom = $userdomain;
                   9660:         }
                   9661:         if(defined($username)) {
                   9662:             $uname = $username;
                   9663:         }
1.253     stredwic 9664:     }
1.955     raeburn  9665:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9666: 
1.955     raeburn  9667:     $dirRoot = $perlvar{'lonDocRoot'};
                   9668:     if (defined($getpropath)) {
                   9669:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9670:         $dirRoot =~ s/\/$//;
1.955     raeburn  9671:     } elsif (defined($getuserdir)) {
                   9672:         my $subdir=$uname.'__';
                   9673:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9674:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9675:                    ."/$udom/$subdir/$uname";
                   9676:     } elsif (defined($alternateRoot)) {
                   9677:         $dirRoot = $alternateRoot;
1.751     banghart 9678:     }
1.253     stredwic 9679: 
                   9680:     if($udom) {
                   9681:         if($uname) {
1.1135    raeburn  9682:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9683:             if ($uhome eq 'no_host') {
                   9684:                 return ([],'no_host');
                   9685:             }
1.955     raeburn  9686:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9687:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9688:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9689:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9690:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9691:             } else {
                   9692:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9693:             }
1.605     matthew  9694:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9695:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9696:                 @listing_results = split(/:/,$listing);
                   9697:             } else {
                   9698:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9699:             }
1.1135    raeburn  9700:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9701:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9702:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9703:                 return ([],$listing);
                   9704:             } else {
                   9705:                 return (\@listing_results);
1.1135    raeburn  9706:             }
1.955     raeburn  9707:         } elsif(!$alternateRoot) {
1.1136    raeburn  9708:             my (%allusers,%listerror);
1.841     albertel 9709: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9710:  	    foreach my $tryserver (keys(%servers)) {
                   9711:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9712:                                   &escape($udom),$tryserver);
                   9713:                 if ($listing eq 'unknown_cmd') {
                   9714: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9715: 				      $udom, $tryserver);
                   9716:                 } else {
                   9717:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9718:                 }
1.841     albertel 9719: 		if ($listing eq 'unknown_cmd') {
                   9720: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9721: 				      $udom, $tryserver);
                   9722: 		    @listing_results = split(/:/,$listing);
                   9723: 		} else {
                   9724: 		    @listing_results =
                   9725: 			map { &unescape($_); } split(/:/,$listing);
                   9726: 		}
1.1136    raeburn  9727:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9728:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9729:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9730:                     $listerror{$tryserver} = $listing;
                   9731:                 } else {
1.841     albertel 9732: 		    foreach my $line (@listing_results) {
                   9733: 			my ($entry) = split(/&/,$line,2);
                   9734: 			$allusers{$entry} = 1;
                   9735: 		    }
                   9736: 		}
1.253     stredwic 9737:             }
1.1136    raeburn  9738:             my @alluserslist=();
1.800     albertel 9739:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9740:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9741:             }
1.1136    raeburn  9742:             return (\@alluserslist);
1.253     stredwic 9743:         } else {
1.1136    raeburn  9744:             return ([],'missing username');
1.253     stredwic 9745:         }
1.955     raeburn  9746:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9747:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9748:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9749:         return (\@all_domains);
1.955     raeburn  9750:     } else {
1.1136    raeburn  9751:         return ([],'missing domain');
1.275     stredwic 9752:     }
                   9753: }
                   9754: 
                   9755: # --------------------------------------------- GetFileTimestamp
                   9756: # This function utilizes dirlist and returns the date stamp for
                   9757: # when it was last modified.  It will also return an error of -1
                   9758: # if an error occurs
                   9759: 
                   9760: sub GetFileTimestamp {
1.955     raeburn  9761:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9762:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9763:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9764:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9765:                                     undef,$getuserdir);
                   9766:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9767:         return -1;
                   9768:     }
                   9769:     if (ref($fileref) eq 'ARRAY') {
                   9770:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9771:         # @stats contains first the filename, then the stat output
                   9772:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9773:     } else {
                   9774:         return -1;
1.253     stredwic 9775:     }
1.26      www      9776: }
                   9777: 
1.712     albertel 9778: sub stat_file {
                   9779:     my ($uri) = @_;
1.787     albertel 9780:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9781: 
1.955     raeburn  9782:     my ($udom,$uname,$file);
1.712     albertel 9783:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9784: 	($udom,$uname,$file) =
1.811     albertel 9785: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9786: 	$file = 'userfiles/'.$file;
                   9787:     }
                   9788:     if ($uri =~ m-^/res/-) {
                   9789: 	($udom,$uname) = 
1.807     albertel 9790: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9791: 	$file = $uri;
                   9792:     }
                   9793: 
                   9794:     if (!$udom || !$uname || !$file) {
                   9795: 	# unable to handle the uri
                   9796: 	return ();
                   9797:     }
1.956     raeburn  9798:     my $getpropath;
                   9799:     if ($file =~ /^userfiles\//) {
                   9800:         $getpropath = 1;
                   9801:     }
1.1136    raeburn  9802:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9803:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9804:         return ();
                   9805:     } else {
                   9806:         if (ref($listref) eq 'ARRAY') {
                   9807:             my @stats = split('&',$listref->[0]);
                   9808: 	    shift(@stats); #filename is first
                   9809: 	    return @stats;
                   9810:         }
1.712     albertel 9811:     }
                   9812:     return ();
                   9813: }
                   9814: 
1.26      www      9815: # -------------------------------------------------------- Value of a Condition
                   9816: 
1.713     albertel 9817: # gets the value of a specific preevaluated condition
                   9818: #    stored in the string  $env{user.state.<cid>}
                   9819: # or looks up a condition reference in the bighash and if if hasn't
                   9820: # already been evaluated recurses into docondval to get the value of
                   9821: # the condition, then memoizing it to 
                   9822: #   $env{user.state.<cid>.<condition>}
1.40      www      9823: sub directcondval {
                   9824:     my $number=shift;
1.620     albertel 9825:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9826: 	&Apache::lonuserstate::evalstate();
                   9827:     }
1.713     albertel 9828:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9829: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9830:     } elsif ($number =~ /^_/) {
                   9831: 	my $sub_condition;
                   9832: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9833: 		&GDBM_READER(),0640)) {
                   9834: 	    $sub_condition=$bighash{'conditions'.$number};
                   9835: 	    untie(%bighash);
                   9836: 	}
                   9837: 	my $value = &docondval($sub_condition);
1.949     raeburn  9838: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9839: 	return $value;
                   9840:     }
1.620     albertel 9841:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9842:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9843:     } else {
                   9844:        return 2;
                   9845:     }
                   9846: }
                   9847: 
1.713     albertel 9848: # get the collection of conditions for this resource
1.26      www      9849: sub condval {
                   9850:     my $condidx=shift;
1.54      www      9851:     my $allpathcond='';
1.713     albertel 9852:     foreach my $cond (split(/\|/,$condidx)) {
                   9853: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9854: 	    $allpathcond.=
                   9855: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9856: 	}
1.191     harris41 9857:     }
1.54      www      9858:     $allpathcond=~s/\|$//;
1.713     albertel 9859:     return &docondval($allpathcond);
                   9860: }
                   9861: 
                   9862: #evaluates an expression of conditions
                   9863: sub docondval {
                   9864:     my ($allpathcond) = @_;
                   9865:     my $result=0;
                   9866:     if ($env{'request.course.id'}
                   9867: 	&& defined($allpathcond)) {
                   9868: 	my $operand='|';
                   9869: 	my @stack;
                   9870: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9871: 	    if ($chunk eq '(') {
                   9872: 		push @stack,($operand,$result);
                   9873: 	    } elsif ($chunk eq ')') {
                   9874: 		my $before=pop @stack;
                   9875: 		if (pop @stack eq '&') {
                   9876: 		    $result=$result>$before?$before:$result;
                   9877: 		} else {
                   9878: 		    $result=$result>$before?$result:$before;
                   9879: 		}
                   9880: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9881: 		$operand=$chunk;
                   9882: 	    } else {
                   9883: 		my $new=directcondval($chunk);
                   9884: 		if ($operand eq '&') {
                   9885: 		    $result=$result>$new?$new:$result;
                   9886: 		} else {
                   9887: 		    $result=$result>$new?$result:$new;
                   9888: 		}
                   9889: 	    }
                   9890: 	}
1.26      www      9891:     }
                   9892:     return $result;
1.421     albertel 9893: }
                   9894: 
                   9895: # ---------------------------------------------------- Devalidate courseresdata
                   9896: 
                   9897: sub devalidatecourseresdata {
                   9898:     my ($coursenum,$coursedomain)=@_;
                   9899:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9900:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9901: }
                   9902: 
1.763     www      9903: 
1.200     www      9904: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9905: #
                   9906: #  Parameters:
                   9907: #      $coursenum    - Number of the course.
                   9908: #      $coursedomain - Domain at which the course was created.
                   9909: #  Returns:
                   9910: #     A hash of the course parameters along (I think) with timestamps
                   9911: #     and version info.
1.877     foxr     9912: 
1.624     albertel 9913: sub get_courseresdata {
                   9914:     my ($coursenum,$coursedomain)=@_;
1.200     www      9915:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9916:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9917:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9918:     my %dumpreply;
1.417     albertel 9919:     unless (defined($cached)) {
1.624     albertel 9920: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9921: 	$result=\%dumpreply;
1.251     albertel 9922: 	my ($tmp) = keys(%dumpreply);
                   9923: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9924: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9925: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9926: 	    return $tmp;
1.416     albertel 9927: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9928: 	    $result=undef;
1.599     albertel 9929: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9930: 	}
                   9931:     }
1.624     albertel 9932:     return $result;
                   9933: }
                   9934: 
1.633     albertel 9935: sub devalidateuserresdata {
                   9936:     my ($uname,$udom)=@_;
                   9937:     my $hashid="$udom:$uname";
                   9938:     &devalidate_cache_new('userres',$hashid);
                   9939: }
                   9940: 
1.624     albertel 9941: sub get_userresdata {
                   9942:     my ($uname,$udom)=@_;
                   9943:     #most student don\'t have any data set, check if there is some data
                   9944:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9945: 
                   9946:     my $hashid="$udom:$uname";
                   9947:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9948:     if (!defined($cached)) {
                   9949: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9950: 	$result=\%resourcedata;
                   9951: 	&do_cache_new('userres',$hashid,$result,600);
                   9952:     }
                   9953:     my ($tmp)=keys(%$result);
                   9954:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9955: 	return $result;
                   9956:     }
                   9957:     #error 2 occurs when the .db doesn't exist
                   9958:     if ($tmp!~/error: 2 /) {
1.672     albertel 9959: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9960: 		 " Trying to get resource data for ".
                   9961: 		 $uname." at ".$udom.": ".
                   9962: 		 $tmp."</font>");
                   9963:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9964: 	#&EXT_cache_set($udom,$uname);
                   9965: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9966: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9967:     }
                   9968:     return $tmp;
                   9969: }
1.879     foxr     9970: #----------------------------------------------- resdata - return resource data
                   9971: #  Purpose:
                   9972: #    Return resource data for either users or for a course.
                   9973: #  Parameters:
                   9974: #     $name      - Course/user name.
                   9975: #     $domain    - Name of the domain the user/course is registered on.
                   9976: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9977: #     @which     - Array of names of resources desired.
                   9978: #  Returns:
                   9979: #     The value of the first reasource in @which that is found in the
                   9980: #     resource hash.
                   9981: #  Exceptional Conditions:
                   9982: #     If the $type passed in is not valid (not the string 'course' or 
                   9983: #     'user', an undefined  reference is returned.
                   9984: #     If none of the resources are found, an undef is returned
1.624     albertel 9985: sub resdata {
                   9986:     my ($name,$domain,$type,@which)=@_;
                   9987:     my $result;
                   9988:     if ($type eq 'course') {
                   9989: 	$result=&get_courseresdata($name,$domain);
                   9990:     } elsif ($type eq 'user') {
                   9991: 	$result=&get_userresdata($name,$domain);
                   9992:     }
                   9993:     if (!ref($result)) { return $result; }    
1.251     albertel 9994:     foreach my $item (@which) {
1.927     albertel 9995: 	if (defined($result->{$item->[0]})) {
                   9996: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9997: 	}
1.250     albertel 9998:     }
1.291     albertel 9999:     return undef;
1.200     www      10000: }
                   10001: 
1.1236    raeburn  10002: sub get_numsuppfiles {
                   10003:     my ($cnum,$cdom,$ignorecache)=@_;
                   10004:     my $hashid=$cnum.':'.$cdom;
                   10005:     my ($suppcount,$cached);
                   10006:     unless ($ignorecache) {
                   10007:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10008:     }
                   10009:     unless (defined($cached)) {
                   10010:         my $chome=&homeserver($cnum,$cdom);
                   10011:         unless ($chome eq 'no_host') {
                   10012:             ($suppcount,my $errors) = (0,0);
                   10013:             my $suppmap = 'supplemental.sequence';
                   10014:             ($suppcount,$errors) = 
                   10015:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10016:         }
                   10017:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10018:     }
                   10019:     return $suppcount;
                   10020: }
                   10021: 
1.379     matthew  10022: #
                   10023: # EXT resource caching routines
                   10024: #
                   10025: 
                   10026: sub clear_EXT_cache_status {
1.383     albertel 10027:     &delenv('cache.EXT.');
1.379     matthew  10028: }
                   10029: 
                   10030: sub EXT_cache_status {
                   10031:     my ($target_domain,$target_user) = @_;
1.383     albertel 10032:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10033:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10034:         # We know already the user has no data
                   10035:         return 1;
                   10036:     } else {
                   10037:         return 0;
                   10038:     }
                   10039: }
                   10040: 
                   10041: sub EXT_cache_set {
                   10042:     my ($target_domain,$target_user) = @_;
1.383     albertel 10043:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10044:     #&appenv({$cachename => time});
1.379     matthew  10045: }
                   10046: 
1.28      www      10047: # --------------------------------------------------------- Value of a Variable
1.58      www      10048: sub EXT {
1.715     albertel 10049: 
1.1228    raeburn  10050:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10051:     unless ($varname) { return ''; }
1.218     albertel 10052:     #get real user name/domain, courseid and symb
                   10053:     my $courseid;
1.359     albertel 10054:     my $publicuser;
1.427     www      10055:     if ($symbparm) {
                   10056: 	$symbparm=&get_symb_from_alias($symbparm);
                   10057:     }
1.218     albertel 10058:     if (!($uname && $udom)) {
1.790     albertel 10059:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10060:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10061:     } else {
1.620     albertel 10062: 	$courseid=$env{'request.course.id'};
1.218     albertel 10063:     }
1.48      www      10064:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10065:     my $rest;
1.320     albertel 10066:     if (defined($therest[0])) {
1.48      www      10067:        $rest=join('.',@therest);
                   10068:     } else {
                   10069:        $rest='';
                   10070:     }
1.320     albertel 10071: 
1.57      www      10072:     my $qualifierrest=$qualifier;
                   10073:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10074:     my $spacequalifierrest=$space;
                   10075:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10076:     if ($realm eq 'user') {
1.48      www      10077: # --------------------------------------------------------------- user.resource
                   10078: 	if ($space eq 'resource') {
1.651     albertel 10079: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10080: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10081: 		 &&
1.744     albertel 10082: 		 ($symbparm eq &symbread()) ) {	
                   10083: 		# if we are in the middle of processing the resource the
                   10084: 		# get the value we are planning on committing
                   10085:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10086:                     return $Apache::lonhomework::results{$qualifierrest};
                   10087:                 } else {
                   10088:                     return $Apache::lonhomework::history{$qualifierrest};
                   10089:                 }
1.335     albertel 10090: 	    } else {
1.359     albertel 10091: 		my %restored;
1.620     albertel 10092: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10093: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10094: 		} else {
                   10095: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10096: 		}
1.335     albertel 10097: 		return $restored{$qualifierrest};
                   10098: 	    }
1.48      www      10099: # ----------------------------------------------------------------- user.access
                   10100:         } elsif ($space eq 'access') {
1.218     albertel 10101: 	    # FIXME - not supporting calls for a specific user
1.48      www      10102:             return &allowed($qualifier,$rest);
                   10103: # ------------------------------------------ user.preferences, user.environment
                   10104:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10105: 	    if (($uname eq $env{'user.name'}) &&
                   10106: 		($udom eq $env{'user.domain'})) {
                   10107: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10108: 	    } else {
1.359     albertel 10109: 		my %returnhash;
                   10110: 		if (!$publicuser) {
                   10111: 		    %returnhash=&userenvironment($udom,$uname,
                   10112: 						 $qualifierrest);
                   10113: 		}
1.218     albertel 10114: 		return $returnhash{$qualifierrest};
                   10115: 	    }
1.48      www      10116: # ----------------------------------------------------------------- user.course
                   10117:         } elsif ($space eq 'course') {
1.218     albertel 10118: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10119:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10120: # ------------------------------------------------------------------- user.role
                   10121:         } elsif ($space eq 'role') {
1.218     albertel 10122: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10123:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10124:             if ($qualifier eq 'value') {
                   10125: 		return $role;
                   10126:             } elsif ($qualifier eq 'extent') {
                   10127:                 return $where;
                   10128:             }
                   10129: # ----------------------------------------------------------------- user.domain
                   10130:         } elsif ($space eq 'domain') {
1.218     albertel 10131:             return $udom;
1.48      www      10132: # ------------------------------------------------------------------- user.name
                   10133:         } elsif ($space eq 'name') {
1.218     albertel 10134:             return $uname;
1.48      www      10135: # ---------------------------------------------------- Any other user namespace
1.29      www      10136:         } else {
1.359     albertel 10137: 	    my %reply;
                   10138: 	    if (!$publicuser) {
                   10139: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10140: 	    }
                   10141: 	    return $reply{$qualifierrest};
1.48      www      10142:         }
1.236     www      10143:     } elsif ($realm eq 'query') {
                   10144: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10145:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10146: 						[$spacequalifierrest]);
1.620     albertel 10147: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10148:    } elsif ($realm eq 'request') {
1.48      www      10149: # ------------------------------------------------------------- request.browser
                   10150:         if ($space eq 'browser') {
1.1145    bisitz   10151:             return $env{'browser.'.$qualifier};
1.57      www      10152: # ------------------------------------------------------------ request.filename
                   10153:         } else {
1.620     albertel 10154:             return $env{'request.'.$spacequalifierrest};
1.29      www      10155:         }
1.28      www      10156:     } elsif ($realm eq 'course') {
1.48      www      10157: # ---------------------------------------------------------- course.description
1.620     albertel 10158:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10159:     } elsif ($realm eq 'resource') {
1.165     www      10160: 
1.620     albertel 10161: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10162: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10163: 	}
1.693     albertel 10164: 
1.1232    raeburn  10165:         if ($qualifier eq '') {
                   10166: 	    if ($space eq 'title') {
                   10167: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10168: 	        return &gettitle($symbparm);
                   10169: 	    }
1.693     albertel 10170: 	
1.1232    raeburn  10171: 	    if ($space eq 'map') {
                   10172: 	        my ($map) = &decode_symb($symbparm);
                   10173: 	        return &symbread($map);
                   10174: 	    }
                   10175:             if ($space eq 'maptitle') {
                   10176:                 my ($map) = &decode_symb($symbparm);
                   10177:                 return &gettitle($map);
                   10178:             }
                   10179: 	    if ($space eq 'filename') {
                   10180: 	        if ($symbparm) {
                   10181: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10182: 	        }
                   10183: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10184: 	    }
1.1232    raeburn  10185: 
1.1233    raeburn  10186:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10187:                 if ($space eq 'visibleparts') {
                   10188:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10189:                     my $item;
                   10190:                     if (ref($navmap)) {
                   10191:                         my $res = $navmap->getBySymb($symbparm);
                   10192:                         my $parts = $res->parts();
                   10193:                         if (ref($parts) eq 'ARRAY') {
                   10194:                             $item = join(',',@{$parts});
                   10195:                         }
                   10196:                         undef($navmap);
1.1232    raeburn  10197:                     }
1.1233    raeburn  10198:                     return $item;
1.1232    raeburn  10199:                 }
                   10200:             }
                   10201:         }
1.693     albertel 10202: 
                   10203: 	my ($section, $group, @groups);
1.593     albertel 10204: 	my ($courselevelm,$courselevel);
1.1228    raeburn  10205:         if (($courseid eq '') && ($cid)) {
                   10206:             $courseid = $cid;
                   10207:         }
                   10208: 	if (($symbparm && $courseid) && 
                   10209: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10210: 
1.218     albertel 10211: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10212: 
1.60      www      10213: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10214: 	    my $symbp=$symbparm;
1.735     albertel 10215: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10216: 
                   10217: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10218: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10219: 
1.620     albertel 10220: 	    if (($env{'user.name'} eq $uname) &&
                   10221: 		($env{'user.domain'} eq $udom)) {
                   10222: 		$section=$env{'request.course.sec'};
1.733     raeburn  10223:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10224:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10225: 	    } else {
1.539     albertel 10226: 		if (! defined($usection)) {
1.551     albertel 10227: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10228: 		} else {
                   10229: 		    $section = $usection;
                   10230: 		}
1.733     raeburn  10231:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10232: 	    }
                   10233: 
                   10234: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10235: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10236: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10237: 
1.593     albertel 10238: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10239: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10240: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10241: 
1.60      www      10242: # ----------------------------------------------------------- first, check user
1.624     albertel 10243: 
                   10244: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10245: 				       ([$courselevelr,'resource'],
                   10246: 					[$courselevelm,'map'     ],
                   10247: 					[$courselevel, 'course'  ]));
1.931     albertel 10248: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10249: 
1.594     albertel 10250: # ------------------------------------------------ second, check some of course
1.684     raeburn  10251:             my $coursereply;
1.691     raeburn  10252:             if (@groups > 0) {
                   10253:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10254:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10255:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10256:             }
1.96      www      10257: 
1.684     raeburn  10258: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10259: 				  $env{'course.'.$courseid.'.domain'},
                   10260: 				  'course',
                   10261: 				  ([$seclevelr,   'resource'],
                   10262: 				   [$seclevelm,   'map'     ],
                   10263: 				   [$seclevel,    'course'  ],
                   10264: 				   [$courselevelr,'resource']));
                   10265: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10266: 
1.60      www      10267: # ------------------------------------------------------ third, check map parms
1.218     albertel 10268: 	    my %parmhash=();
                   10269: 	    my $thisparm='';
                   10270: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10271: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10272: 		    &GDBM_READER(),0640)) {
1.218     albertel 10273: 		$thisparm=$parmhash{$symbparm};
                   10274: 		untie(%parmhash);
                   10275: 	    }
1.927     albertel 10276: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10277: 	}
1.594     albertel 10278: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10279: 
1.218     albertel 10280: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10281: 	my $filename;
                   10282: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10283: 	if ($symbparm) {
1.409     www      10284: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10285: 	} else {
1.620     albertel 10286: 	    $filename=$env{'request.filename'};
1.282     albertel 10287: 	}
                   10288: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10289: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10290: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10291: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10292: 
1.927     albertel 10293: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10294: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10295: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10296: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10297: 				     $env{'course.'.$courseid.'.domain'},
                   10298: 				     'course',
1.927     albertel 10299: 				     ([$courselevelm,'map'   ],
                   10300: 				      [$courselevel, 'course']));
                   10301: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10302: 	}
1.145     www      10303: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10304: 	unless ($space eq '0') {
1.336     albertel 10305: 	    my @parts=split(/_/,$space);
                   10306: 	    my $id=pop(@parts);
                   10307: 	    my $part=join('_',@parts);
                   10308: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10309: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10310: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10311: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10312: 	}
1.395     albertel 10313: 	if ($recurse) { return undef; }
                   10314: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10315: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10316: # ---------------------------------------------------- Any other user namespace
                   10317:     } elsif ($realm eq 'environment') {
                   10318: # ----------------------------------------------------------------- environment
1.620     albertel 10319: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10320: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10321: 	} else {
1.770     albertel 10322: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10323: 		return '';
                   10324: 	    }
1.219     albertel 10325: 	    my %returnhash=&userenvironment($udom,$uname,
                   10326: 					    $spacequalifierrest);
                   10327: 	    return $returnhash{$spacequalifierrest};
                   10328: 	}
1.28      www      10329:     } elsif ($realm eq 'system') {
1.48      www      10330: # ----------------------------------------------------------------- system.time
                   10331: 	if ($space eq 'time') {
                   10332: 	    return time;
                   10333:         }
1.696     albertel 10334:     } elsif ($realm eq 'server') {
                   10335: # ----------------------------------------------------------------- system.time
                   10336: 	if ($space eq 'name') {
                   10337: 	    return $ENV{'SERVER_NAME'};
                   10338:         }
1.28      www      10339:     }
1.48      www      10340:     return '';
1.61      www      10341: }
                   10342: 
1.927     albertel 10343: sub get_reply {
                   10344:     my ($reply_value) = @_;
1.940     raeburn  10345:     if (ref($reply_value) eq 'ARRAY') {
                   10346:         if (wantarray) {
                   10347: 	    return @$reply_value;
                   10348:         }
                   10349:         return $reply_value->[0];
                   10350:     } else {
                   10351:         return $reply_value;
1.927     albertel 10352:     }
                   10353: }
                   10354: 
1.691     raeburn  10355: sub check_group_parms {
                   10356:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10357:     my @groupitems = ();
                   10358:     my $resultitem;
1.927     albertel 10359:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10360:     foreach my $group (@{$groups}) {
                   10361:         foreach my $level (@levels) {
1.927     albertel 10362:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10363:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10364:         }
                   10365:     }
                   10366:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10367:                             $env{'course.'.$courseid.'.domain'},
                   10368:                                      'course',@groupitems);
                   10369:     return $coursereply;
                   10370: }
                   10371: 
                   10372: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10373:     my ($courseid,@groups) = @_;
                   10374:     @groups = sort(@groups);
1.691     raeburn  10375:     return @groups;
                   10376: }
                   10377: 
1.395     albertel 10378: sub packages_tab_default {
                   10379:     my ($uri,$varname)=@_;
                   10380:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10381: 
                   10382:     my (@extension,@specifics,$do_default);
                   10383:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10384: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10385: 	if ($pack_type eq 'default') {
                   10386: 	    $do_default=1;
                   10387: 	} elsif ($pack_type eq 'extension') {
                   10388: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10389: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10390: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10391: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10392: 	}
                   10393:     }
                   10394:     # first look for a package that matches the requested part id
                   10395:     foreach my $package (@specifics) {
                   10396: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10397: 	next if ($pack_part ne $part);
                   10398: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10399: 	    return $packagetab{"$pack_type&$name&default"};
                   10400: 	}
                   10401:     }
                   10402:     # look for any possible matching non extension_ package
                   10403:     foreach my $package (@specifics) {
                   10404: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10405: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10406: 	    return $packagetab{"$pack_type&$name&default"};
                   10407: 	}
1.585     albertel 10408: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10409: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10410: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10411: 	}
                   10412:     }
1.738     albertel 10413:     # look for any posible extension_ match
                   10414:     foreach my $package (@extension) {
                   10415: 	my ($package,$pack_type)=@{$package};
                   10416: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10417: 	    return $packagetab{"$pack_type&$name&default"};
                   10418: 	}
                   10419: 	if (defined($packagetab{$package."&$name&default"})) {
                   10420: 	    return $packagetab{$package."&$name&default"};
                   10421: 	}
                   10422:     }
                   10423:     # look for a global default setting
                   10424:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10425: 	return $packagetab{"default&$name&default"};
                   10426:     }
1.395     albertel 10427:     return undef;
                   10428: }
                   10429: 
1.334     albertel 10430: sub add_prefix_and_part {
                   10431:     my ($prefix,$part)=@_;
                   10432:     my $keyroot;
                   10433:     if (defined($prefix) && $prefix !~ /^__/) {
                   10434: 	# prefix that has a part already
                   10435: 	$keyroot=$prefix;
                   10436:     } elsif (defined($prefix)) {
                   10437: 	# prefix that is missing a part
                   10438: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10439:     } else {
                   10440: 	# no prefix at all
                   10441: 	if (defined($part)) { $keyroot='_'.$part; }
                   10442:     }
                   10443:     return $keyroot;
                   10444: }
                   10445: 
1.71      www      10446: # ---------------------------------------------------------------- Get metadata
                   10447: 
1.599     albertel 10448: my %metaentry;
1.1070    www      10449: my %importedpartids;
1.71      www      10450: sub metadata {
1.176     www      10451:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10452:     $uri=&declutter($uri);
1.288     albertel 10453:     # if it is a non metadata possible uri return quickly
1.529     albertel 10454:     if (($uri eq '') || 
                   10455: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10456: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10457:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10458: 	return undef;
                   10459:     }
1.1261    raeburn  10460:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10461: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10462: 	return undef;
1.288     albertel 10463:     }
1.73      www      10464:     my $filename=$uri;
                   10465:     $uri=~s/\.meta$//;
1.172     www      10466: #
                   10467: # Is the metadata already cached?
1.177     www      10468: # Look at timestamp of caching
1.172     www      10469: # Everything is cached by the main uri, libraries are never directly cached
                   10470: #
1.428     albertel 10471:     if (!defined($liburi)) {
1.599     albertel 10472: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10473: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10474:     }
                   10475:     {
1.1069    www      10476: # Imported parts would go here
1.1070    www      10477:         my %importedids=();
                   10478:         my @origfileimportpartids=();
1.1069    www      10479:         my $importedparts=0;
1.172     www      10480: #
                   10481: # Is this a recursive call for a library?
                   10482: #
1.599     albertel 10483: #	if (! exists($metacache{$uri})) {
                   10484: #	    $metacache{$uri}={};
                   10485: #	}
1.924     albertel 10486: 	my $cachetime = 60*60;
1.171     www      10487:         if ($liburi) {
                   10488: 	    $liburi=&declutter($liburi);
                   10489:             $filename=$liburi;
1.401     bowersj2 10490:         } else {
1.599     albertel 10491: 	    &devalidate_cache_new('meta',$uri);
                   10492: 	    undef(%metaentry);
1.401     bowersj2 10493: 	}
1.140     www      10494:         my %metathesekeys=();
1.73      www      10495:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10496: 	my $metastring;
1.1140    www      10497: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10498: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10499: 	    $metastring = 
1.929     albertel 10500: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10501: 					  ('grade_target' => 'meta'));
                   10502: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10503: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10504:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10505: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10506: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10507: 	    $metastring=&getfile($file);
1.489     albertel 10508: 	}
1.208     albertel 10509:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10510:         my $token;
1.140     www      10511:         undef %metathesekeys;
1.71      www      10512:         while ($token=$parser->get_token) {
1.339     albertel 10513: 	    if ($token->[0] eq 'S') {
                   10514: 		if (defined($token->[2]->{'package'})) {
1.172     www      10515: #
                   10516: # This is a package - get package info
                   10517: #
1.339     albertel 10518: 		    my $package=$token->[2]->{'package'};
                   10519: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10520: 		    if (defined($token->[2]->{'id'})) { 
                   10521: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10522: 		    }
1.599     albertel 10523: 		    if ($metaentry{':packages'}) {
                   10524: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10525: 		    } else {
1.599     albertel 10526: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10527: 		    }
1.736     albertel 10528: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10529: 			my $part=$keyroot;
                   10530: 			$part=~s/^\_//;
1.736     albertel 10531: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10532: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10533: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10534: 			    # ignore package.tab specified default values
                   10535:                             # here &package_tab_default() will fetch those
                   10536: 			    if ($subp eq 'default') { next; }
1.736     albertel 10537: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10538: 			    my $unikey;
                   10539: 			    if ($pack =~ /_0$/) {
                   10540: 				$unikey='parameter_0_'.$name;
                   10541: 				$part=0;
                   10542: 			    } else {
                   10543: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10544: 			    }
1.339     albertel 10545: 			    if ($subp eq 'display') {
                   10546: 				$value.=' [Part: '.$part.']';
                   10547: 			    }
1.599     albertel 10548: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10549: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10550: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10551: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10552: 			    }
1.599     albertel 10553: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10554: 				$metaentry{':'.$unikey}=
                   10555: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10556: 			    }
1.339     albertel 10557: 			}
                   10558: 		    }
                   10559: 		} else {
1.172     www      10560: #
                   10561: # This is not a package - some other kind of start tag
1.339     albertel 10562: #
                   10563: 		    my $entry=$token->[1];
1.1068    www      10564: 		    my $unikey='';
1.175     www      10565: 
1.339     albertel 10566: 		    if ($entry eq 'import') {
1.175     www      10567: #
                   10568: # Importing a library here
1.339     albertel 10569: #
1.1067    www      10570:                         my $location=$parser->get_text('/import');
                   10571:                         my $dir=$filename;
                   10572:                         $dir=~s|[^/]*$||;
                   10573:                         $location=&filelocation($dir,$location);
1.1069    www      10574:                        
1.1068    www      10575:                         my $importmode=$token->[2]->{'importmode'};
                   10576:                         if ($importmode eq 'problem') {
1.1069    www      10577: # Import as problem/response
1.1068    www      10578:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10579:                         } elsif ($importmode eq 'part') {
                   10580: # Import as part(s)
1.1069    www      10581:                            $importedparts=1;
                   10582: # We need to get the original file and the imported file to get the part order correct
                   10583: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10584: # Load and inspect original file
1.1070    www      10585:                            if ($#origfileimportpartids<0) {
                   10586:                               undef(%importedpartids);
                   10587:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10588:                               my $origfile=&getfile($origfilelocation);
                   10589:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10590:                            }
                   10591: 
1.1069    www      10592: # Load and inspect imported file
                   10593:                            my $impfile=&getfile($location);
                   10594:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10595:                            if ($#impfilepartids>=0) {
                   10596: # This problem had parts
1.1070    www      10597:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10598:                            } else {
                   10599: # Importing by turning a single problem into a problem part
                   10600: # It gets the import-tags ID as part-ID
                   10601:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10602:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10603:                            }
1.1068    www      10604:                         } else {
                   10605: # Normal import
                   10606:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10607:                            if (defined($token->[2]->{'id'})) {
                   10608:                               $unikey.='_'.$token->[2]->{'id'};
                   10609:                            }
1.1067    www      10610:                         }
                   10611: 
1.339     albertel 10612: 			if ($depthcount<20) {
1.736     albertel 10613: 			    my $metadata = 
                   10614: 				&metadata($uri,'keys', $location,$unikey,
                   10615: 					  $depthcount+1);
                   10616: 			    foreach my $meta (split(',',$metadata)) {
                   10617: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10618: 				$metathesekeys{$meta}=1;
1.339     albertel 10619: 			    }
1.1068    www      10620: 			
                   10621:                         }
1.1067    www      10622: 		    } else {
                   10623: #
                   10624: # Not importing, some other kind of non-package, non-library start tag
                   10625: # 
                   10626:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10627:                         if (defined($token->[2]->{'id'})) {
                   10628:                             $unikey.='_'.$token->[2]->{'id'};
                   10629:                         }
1.339     albertel 10630: 			if (defined($token->[2]->{'name'})) { 
                   10631: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10632: 			}
                   10633: 			$metathesekeys{$unikey}=1;
1.736     albertel 10634: 			foreach my $param (@{$token->[3]}) {
                   10635: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10636: 				$token->[2]->{$param};
1.339     albertel 10637: 			}
                   10638: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10639: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10640: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10641: 		 # only ws inside the tag, and not in default, so use default
                   10642: 		 # as value
1.599     albertel 10643: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10644: 			} elsif ( $internaltext =~ /\S/ ) {
                   10645: 		  # something interesting inside the tag
                   10646: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10647: 			} else {
1.908     albertel 10648: 		  # no interesting values, don't set a default
1.339     albertel 10649: 			}
1.172     www      10650: # end of not-a-package not-a-library import
1.339     albertel 10651: 		    }
1.172     www      10652: # end of not-a-package start tag
1.339     albertel 10653: 		}
1.172     www      10654: # the next is the end of "start tag"
1.339     albertel 10655: 	    }
                   10656: 	}
1.483     albertel 10657: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10658: 	$extension = lc($extension);
                   10659: 	if ($extension eq 'htm') { $extension='html'; }
                   10660: 
1.737     albertel 10661: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10662: 	    #no specific packages #how's our extension
                   10663: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10664: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10665: 					 \%metathesekeys);
                   10666: 	}
1.883     albertel 10667: 
                   10668: 	if (!exists($metaentry{':packages'})
                   10669: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10670: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10671: 		#no specific packages well let's get default then
                   10672: 		if ($key!~/^default&/) { next; }
1.488     albertel 10673: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10674: 					     \%metathesekeys);
                   10675: 	    }
                   10676: 	}
1.338     www      10677: # are there custom rights to evaluate
1.599     albertel 10678: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10679: 
1.338     www      10680:     #
                   10681:     # Importing a rights file here
1.339     albertel 10682:     #
                   10683: 	    unless ($depthcount) {
1.599     albertel 10684: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10685: 		my $dir=$filename;
                   10686: 		$dir=~s|[^/]*$||;
                   10687: 		$location=&filelocation($dir,$location);
1.736     albertel 10688: 		my $rights_metadata =
                   10689: 		    &metadata($uri,'keys',$location,'_rights',
                   10690: 			      $depthcount+1);
                   10691: 		foreach my $rights (split(',',$rights_metadata)) {
                   10692: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10693: 		    $metathesekeys{$rights}=1;
1.339     albertel 10694: 		}
                   10695: 	    }
                   10696: 	}
1.737     albertel 10697: 	# uniqifiy package listing
                   10698: 	my %seen;
                   10699: 	my @uniq_packages =
                   10700: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10701: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10702: 
1.1070    www      10703:         if ($importedparts) {
                   10704: # We had imported parts and need to rebuild partorder
                   10705:            $metaentry{':partorder'}='';
                   10706:            $metathesekeys{'partorder'}=1;
                   10707:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10708:                if ($origfileimportpartids[$index] eq 'part') {
                   10709: # original part, part of the problem
                   10710:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10711:                } else {
                   10712: # we have imported parts at this position
                   10713:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10714:                }
                   10715:            }
                   10716:            $metaentry{':partorder'}=~s/^\,//;
                   10717:         }
                   10718: 
1.737     albertel 10719: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10720: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  10721: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10722: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10723: # this is the end of "was not already recently cached
1.71      www      10724:     }
1.599     albertel 10725:     return $metaentry{':'.$what};
1.261     albertel 10726: }
                   10727: 
1.488     albertel 10728: sub metadata_create_package_def {
1.483     albertel 10729:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10730:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10731:     if ($subp eq 'default') { next; }
                   10732:     
1.599     albertel 10733:     if (defined($metaentry{':packages'})) {
                   10734: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10735:     } else {
1.599     albertel 10736: 	$metaentry{':packages'}=$package;
1.483     albertel 10737:     }
                   10738:     my $value=$packagetab{$key};
                   10739:     my $unikey;
                   10740:     $unikey='parameter_0_'.$name;
1.599     albertel 10741:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10742:     $$metathesekeys{$unikey}=1;
1.599     albertel 10743:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10744: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10745:     }
1.599     albertel 10746:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10747: 	$metaentry{':'.$unikey}=
                   10748: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10749:     }
                   10750: }
                   10751: 
1.261     albertel 10752: sub metadata_generate_part0 {
                   10753:     my ($metadata,$metacache,$uri) = @_;
                   10754:     my %allnames;
1.737     albertel 10755:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10756: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10757: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10758: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10759: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10760: 	    $allnames{$name}=$part;
                   10761: 	  }
                   10762: 	}
                   10763:     }
                   10764:     foreach my $name (keys(%allnames)) {
                   10765:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10766:       my $key=":parameter_0_$name";
1.261     albertel 10767:       $$metacache{"$key.part"}='0';
                   10768:       $$metacache{"$key.name"}=$name;
1.428     albertel 10769:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10770: 					   $allnames{$name}.'_'.$name.
                   10771: 					   '.type'};
1.428     albertel 10772:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10773: 			     '.display'};
1.644     www      10774:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10775:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10776:       $$metacache{"$key.display"}=$olddis;
                   10777:     }
1.71      www      10778: }
                   10779: 
1.764     albertel 10780: # ------------------------------------------------------ Devalidate title cache
                   10781: 
                   10782: sub devalidate_title_cache {
                   10783:     my ($url)=@_;
                   10784:     if (!$env{'request.course.id'}) { return; }
                   10785:     my $symb=&symbread($url);
                   10786:     if (!$symb) { return; }
                   10787:     my $key=$env{'request.course.id'}."\0".$symb;
                   10788:     &devalidate_cache_new('title',$key);
                   10789: }
                   10790: 
1.1014    droeschl 10791: # ------------------------------------------------- Get the title of a course
                   10792: 
                   10793: sub current_course_title {
                   10794:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10795: }
1.301     www      10796: # ------------------------------------------------- Get the title of a resource
                   10797: 
                   10798: sub gettitle {
                   10799:     my $urlsymb=shift;
                   10800:     my $symb=&symbread($urlsymb);
1.534     albertel 10801:     if ($symb) {
1.620     albertel 10802: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10803: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10804: 	if (defined($cached)) { 
                   10805: 	    return $result;
                   10806: 	}
1.534     albertel 10807: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10808: 	my $title='';
1.907     albertel 10809: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10810: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10811: 	} else {
                   10812: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10813: 		    &GDBM_READER(),0640)) {
                   10814: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10815: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10816: 		untie(%bighash);
                   10817: 	    }
1.534     albertel 10818: 	}
                   10819: 	$title=~s/\&colon\;/\:/gs;
                   10820: 	if ($title) {
1.1159    www      10821: # Remember both $symb and $title for dynamic metadata
                   10822:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10823:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10824: # Cache this title and then return it
1.599     albertel 10825: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10826: 	}
                   10827: 	$urlsymb=$url;
                   10828:     }
                   10829:     my $title=&metadata($urlsymb,'title');
                   10830:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10831:     return $title;
1.301     www      10832: }
1.613     albertel 10833: 
1.614     albertel 10834: sub get_slot {
                   10835:     my ($which,$cnum,$cdom)=@_;
                   10836:     if (!$cnum || !$cdom) {
1.790     albertel 10837: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10838: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10839: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10840:     }
1.703     albertel 10841:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10842:     my %slotinfo;
                   10843:     if (exists($remembered{$key})) {
                   10844: 	$slotinfo{$which} = $remembered{$key};
                   10845:     } else {
                   10846: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10847: 	&Apache::lonhomework::showhash(%slotinfo);
                   10848: 	my ($tmp)=keys(%slotinfo);
                   10849: 	if ($tmp=~/^error:/) { return (); }
                   10850: 	$remembered{$key} = $slotinfo{$which};
                   10851:     }
1.616     albertel 10852:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10853: 	return %{$slotinfo{$which}};
                   10854:     }
                   10855:     return $slotinfo{$which};
1.614     albertel 10856: }
1.1150    raeburn  10857: 
                   10858: sub get_reservable_slots {
                   10859:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10860:     my $now = time;
                   10861:     my $reservable_info;
                   10862:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10863:     if (exists($remembered{$key})) {
                   10864:         $reservable_info = $remembered{$key};
                   10865:     } else {
                   10866:         my %resv;
                   10867:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10868:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10869:         $reservable_info = \%resv;
                   10870:         $remembered{$key} = $reservable_info;
                   10871:     }
                   10872:     return $reservable_info;
                   10873: }
                   10874: 
                   10875: sub get_course_slots {
                   10876:     my ($cnum,$cdom) = @_;
                   10877:     my $hashid=$cnum.':'.$cdom;
                   10878:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10879:     if (defined($cached)) {
                   10880:         if (ref($result) eq 'HASH') {
                   10881:             return %{$result};
                   10882:         }
                   10883:     } else {
                   10884:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10885:         my ($tmp) = keys(%slots);
                   10886:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10887:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10888:             return %slots;
                   10889:         }
                   10890:     }
                   10891:     return;
                   10892: }
                   10893: 
                   10894: sub devalidate_slots_cache {
                   10895:     my ($cnum,$cdom)=@_;
                   10896:     my $hashid=$cnum.':'.$cdom;
                   10897:     &devalidate_cache_new('allslots',$hashid);
                   10898: }
                   10899: 
1.1181    raeburn  10900: sub get_coursechange {
                   10901:     my ($cdom,$cnum) = @_;
                   10902:     if ($cdom eq '' || $cnum eq '') {
                   10903:         return unless ($env{'request.course.id'});
                   10904:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10905:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10906:     }
                   10907:     my $hashid=$cdom.'_'.$cnum;
                   10908:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10909:     if ((defined($cached)) && ($change ne '')) {
                   10910:         return $change;
                   10911:     } else {
                   10912:         my %crshash;
                   10913:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10914:         if ($crshash{'internal.contentchange'} eq '') {
                   10915:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10916:             if ($change eq '') {
                   10917:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10918:                 $change = $crshash{'internal.created'};
                   10919:             }
                   10920:         } else {
                   10921:             $change = $crshash{'internal.contentchange'};
                   10922:         }
                   10923:         my $cachetime = 600;
                   10924:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10925:     }
                   10926:     return $change;
                   10927: }
                   10928: 
                   10929: sub devalidate_coursechange_cache {
                   10930:     my ($cnum,$cdom)=@_;
                   10931:     my $hashid=$cnum.':'.$cdom;
                   10932:     &devalidate_cache_new('crschange',$hashid);
                   10933: }
                   10934: 
1.31      www      10935: # ------------------------------------------------- Update symbolic store links
                   10936: 
                   10937: sub symblist {
                   10938:     my ($mapname,%newhash)=@_;
1.438     www      10939:     $mapname=&deversion(&declutter($mapname));
1.31      www      10940:     my %hash;
1.620     albertel 10941:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10942:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10943:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10944: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10945: 		next if ($url eq 'last_known'
                   10946: 			 && $env{'form.no_update_last_known'});
                   10947: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10948: 						    $newhash{$url}->[1],
                   10949: 						    $newhash{$url}->[0]);
1.191     harris41 10950:             }
1.31      www      10951:             if (untie(%hash)) {
                   10952: 		return 'ok';
                   10953:             }
                   10954:         }
                   10955:     }
                   10956:     return 'error';
1.212     www      10957: }
                   10958: 
                   10959: # --------------------------------------------------------------- Verify a symb
                   10960: 
                   10961: sub symbverify {
1.1190    raeburn  10962:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10963:     my $thisfn=$thisurl;
1.439     www      10964:     $thisfn=&declutter($thisfn);
1.215     www      10965: # direct jump to resource in page or to a sequence - will construct own symbs
                   10966:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10967: # check URL part
1.409     www      10968:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10969: 
1.431     www      10970:     unless ($url eq $thisfn) { return 0; }
1.213     www      10971: 
1.216     www      10972:     $symb=&symbclean($symb);
1.510     www      10973:     $thisurl=&deversion($thisurl);
1.439     www      10974:     $thisfn=&deversion($thisfn);
1.213     www      10975: 
                   10976:     my %bighash;
                   10977:     my $okay=0;
1.431     www      10978: 
1.620     albertel 10979:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10980:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10981:         my $noclutter;
1.1032    raeburn  10982:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10983:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10984:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10985:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10986:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10987:                 $noclutter = 1;
                   10988:             }
                   10989:         }
                   10990:         my $ids;
                   10991:         if ($noclutter) {
                   10992:             $ids=$bighash{'ids_'.$thisurl};
                   10993:         } else {
                   10994:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10995:         }
1.1102    raeburn  10996:         unless ($ids) {
                   10997:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10998:             $ids=$bighash{$idkey};
1.216     www      10999:         }
                   11000:         if ($ids) {
                   11001: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11002:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11003:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11004:             }
1.800     albertel 11005: 	    foreach my $id (split(/\,/,$ids)) {
                   11006: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11007:                if (
                   11008:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11009:    eq $symb) {
                   11010:                    if (ref($encstate)) {
                   11011:                        $$encstate = $bighash{'encrypted_'.$id};
                   11012:                    }
1.620     albertel 11013: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11014: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11015:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11016: 		       $okay=1;
1.1202    raeburn  11017:                        last;
1.582     albertel 11018: 		   }
                   11019: 	       }
1.216     www      11020: 	   }
                   11021:         }
1.213     www      11022: 	untie(%bighash);
                   11023:     }
                   11024:     return $okay;
1.31      www      11025: }
                   11026: 
1.210     www      11027: # --------------------------------------------------------------- Clean-up symb
                   11028: 
                   11029: sub symbclean {
                   11030:     my $symb=shift;
1.568     albertel 11031:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11032: # remove version from map
                   11033:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11034: 
1.210     www      11035: # remove version from URL
                   11036:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11037: 
1.507     www      11038: # remove wrapper
                   11039: 
1.510     www      11040:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11041:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11042:     return $symb;
1.409     www      11043: }
                   11044: 
                   11045: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11046: 
                   11047: sub encode_symb {
                   11048:     my ($map,$resid,$url)=@_;
                   11049:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11050: }
1.409     www      11051: 
                   11052: sub decode_symb {
1.568     albertel 11053:     my $symb=shift;
                   11054:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11055:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11056:     return (&fixversion($map),$resid,&fixversion($url));
                   11057: }
                   11058: 
                   11059: sub fixversion {
                   11060:     my $fn=shift;
1.609     banghart 11061:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11062:     my %bighash;
                   11063:     my $uri=&clutter($fn);
1.620     albertel 11064:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11065: # is this cached?
1.599     albertel 11066:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11067:     if (defined($cached)) { return $result; }
                   11068: # unfortunately not cached, or expired
1.620     albertel 11069:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11070: 	    &GDBM_READER(),0640)) {
                   11071:  	if ($bighash{'version_'.$uri}) {
                   11072:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11073:  	    unless (($version eq 'mostrecent') || 
                   11074: 		    ($version==&getversion($uri))) {
1.440     www      11075:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11076:  	    }
                   11077:  	}
                   11078:  	untie %bighash;
1.413     www      11079:     }
1.599     albertel 11080:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11081: }
                   11082: 
                   11083: sub deversion {
                   11084:     my $url=shift;
                   11085:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11086:     return $url;
1.210     www      11087: }
                   11088: 
1.31      www      11089: # ------------------------------------------------------ Return symb list entry
                   11090: 
                   11091: sub symbread {
1.249     www      11092:     my ($thisfn,$donotrecurse)=@_;
1.1265    raeburn  11093:     my $cache_str='request.symbread.cached.'.$thisfn;
                   11094:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      11095: # no filename provided? try from environment
1.1265    raeburn  11096:     unless ($thisfn) {
1.620     albertel 11097:         if ($env{'request.symb'}) {
                   11098: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11099: 	}
1.620     albertel 11100: 	$thisfn=$env{'request.filename'};
1.44      www      11101:     }
1.569     albertel 11102:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11103: # is that filename actually a symb? Verify, clean, and return
                   11104:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11105: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11106: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11107: 	}
1.242     www      11108:     }
1.44      www      11109:     $thisfn=declutter($thisfn);
1.31      www      11110:     my %hash;
1.37      www      11111:     my %bighash;
                   11112:     my $syval='';
1.620     albertel 11113:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11114:         my $targetfn = $thisfn;
1.609     banghart 11115:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11116:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11117:         }
1.687     albertel 11118: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11119: 	    $targetfn=$1;
                   11120: 	}
1.620     albertel 11121:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11122:                       &GDBM_READER(),0640)) {
1.481     raeburn  11123: 	    $syval=$hash{$targetfn};
1.37      www      11124:             untie(%hash);
                   11125:         }
                   11126: # ---------------------------------------------------------- There was an entry
                   11127:         if ($syval) {
1.601     albertel 11128: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11129: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11130: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11131: 		    #return $env{$cache_str}='';
1.601     albertel 11132: 		#}    
                   11133: 		#$syval.=$1;
                   11134: 	    #}
1.37      www      11135:         } else {
                   11136: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11137:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11138:                             &GDBM_READER(),0640)) {
1.37      www      11139: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11140:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11141:               unless ($ids) { 
                   11142:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11143:               }
                   11144:               unless ($ids) {
                   11145: # alias?
                   11146: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11147:               }
1.37      www      11148:               if ($ids) {
                   11149: # ------------------------------------------------------------------- Has ID(s)
                   11150:                  my @possibilities=split(/\,/,$ids);
1.39      www      11151:                  if ($#possibilities==0) {
                   11152: # ----------------------------------------------- There is only one possibility
1.37      www      11153: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11154: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11155: 						    $resid,$thisfn);
1.249     www      11156:                  } elsif (!$donotrecurse) {
1.39      www      11157: # ------------------------------------------ There is more than one possibility
                   11158:                      my $realpossible=0;
1.800     albertel 11159:                      foreach my $id (@possibilities) {
                   11160: 			 my $file=$bighash{'src_'.$id};
1.39      www      11161:                          if (&allowed('bre',$file)) {
1.800     albertel 11162:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      11163:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11164: 				$realpossible++;
1.626     albertel 11165:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11166: 						    $resid,$thisfn);
1.39      www      11167:                             }
                   11168: 			 }
1.191     harris41 11169:                      }
1.39      www      11170: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11171:                  } else {
                   11172:                      $syval='';
1.37      www      11173:                  }
                   11174: 	      }
                   11175:               untie(%bighash)
1.481     raeburn  11176:            }
1.31      www      11177:         }
1.62      www      11178:         if ($syval) {
1.620     albertel 11179: 	    return $env{$cache_str}=$syval;
1.62      www      11180:         }
1.31      www      11181:     }
1.949     raeburn  11182:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11183:     return $env{$cache_str}='';
1.31      www      11184: }
                   11185: 
                   11186: # ---------------------------------------------------------- Return random seed
                   11187: 
1.32      www      11188: sub numval {
                   11189:     my $txt=shift;
                   11190:     $txt=~tr/A-J/0-9/;
                   11191:     $txt=~tr/a-j/0-9/;
                   11192:     $txt=~tr/K-T/0-9/;
                   11193:     $txt=~tr/k-t/0-9/;
                   11194:     $txt=~tr/U-Z/0-5/;
                   11195:     $txt=~tr/u-z/0-5/;
                   11196:     $txt=~s/\D//g;
1.564     albertel 11197:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11198:     return int($txt);
1.368     albertel 11199: }
                   11200: 
1.484     albertel 11201: sub numval2 {
                   11202:     my $txt=shift;
                   11203:     $txt=~tr/A-J/0-9/;
                   11204:     $txt=~tr/a-j/0-9/;
                   11205:     $txt=~tr/K-T/0-9/;
                   11206:     $txt=~tr/k-t/0-9/;
                   11207:     $txt=~tr/U-Z/0-5/;
                   11208:     $txt=~tr/u-z/0-5/;
                   11209:     $txt=~s/\D//g;
                   11210:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11211:     my $total;
                   11212:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11213:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11214:     return int($total);
                   11215: }
                   11216: 
1.575     albertel 11217: sub numval3 {
                   11218:     use integer;
                   11219:     my $txt=shift;
                   11220:     $txt=~tr/A-J/0-9/;
                   11221:     $txt=~tr/a-j/0-9/;
                   11222:     $txt=~tr/K-T/0-9/;
                   11223:     $txt=~tr/k-t/0-9/;
                   11224:     $txt=~tr/U-Z/0-5/;
                   11225:     $txt=~tr/u-z/0-5/;
                   11226:     $txt=~s/\D//g;
                   11227:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11228:     my $total;
                   11229:     foreach my $val (@txts) { $total+=$val; }
                   11230:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11231:     return $total;
                   11232: }
                   11233: 
1.675     albertel 11234: sub digest {
                   11235:     my ($data)=@_;
                   11236:     my $digest=&Digest::MD5::md5($data);
                   11237:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11238:     my ($e,$f);
                   11239:     {
                   11240:         use integer;
                   11241:         $e=($a+$b);
                   11242:         $f=($c+$d);
                   11243:         if ($_64bit) {
                   11244:             $e=(($e<<32)>>32);
                   11245:             $f=(($f<<32)>>32);
                   11246:         }
                   11247:     }
                   11248:     if (wantarray) {
                   11249: 	return ($e,$f);
                   11250:     } else {
                   11251: 	my $g;
                   11252: 	{
                   11253: 	    use integer;
                   11254: 	    $g=($e+$f);
                   11255: 	    if ($_64bit) {
                   11256: 		$g=(($g<<32)>>32);
                   11257: 	    }
                   11258: 	}
                   11259: 	return $g;
                   11260:     }
                   11261: }
                   11262: 
1.368     albertel 11263: sub latest_rnd_algorithm_id {
1.675     albertel 11264:     return '64bit5';
1.366     albertel 11265: }
1.32      www      11266: 
1.503     albertel 11267: sub get_rand_alg {
                   11268:     my ($courseid)=@_;
1.790     albertel 11269:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11270:     if ($courseid) {
1.620     albertel 11271: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11272:     }
                   11273:     return &latest_rnd_algorithm_id();
                   11274: }
                   11275: 
1.562     albertel 11276: sub validCODE {
                   11277:     my ($CODE)=@_;
                   11278:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11279:     return 0;
                   11280: }
                   11281: 
1.491     albertel 11282: sub getCODE {
1.620     albertel 11283:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11284:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11285: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11286: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11287: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11288:     }
                   11289:     return undef;
                   11290: }
1.1133    foxr     11291: #
                   11292: #  Determines the random seed for a specific context:
                   11293: #
                   11294: # parameters:
                   11295: #   symb      - in course context the symb for the seed.
                   11296: #   course_id - The course id of the form domain_coursenum.
                   11297: #   domain    - Domain for the user.
                   11298: #   course    - Course for the user.
                   11299: #   cenv      - environment of the course.
                   11300: #
                   11301: # NOTE:
                   11302: #   All parameters are picked out of the environment if missing
                   11303: #   or not defined.
                   11304: #   If a symb cannot be determined the current time is used instead.
                   11305: #
                   11306: #  For a given well defined symb, courside, domain, username,
                   11307: #  and course environment, the seed is reproducible.
                   11308: #
1.31      www      11309: sub rndseed {
1.1133    foxr     11310:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11311:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11312:     if (!defined($symb)) {
1.366     albertel 11313: 	unless ($symb=$wsymb) { return time; }
                   11314:     }
1.1146    foxr     11315:     if (!defined $courseid) { 
                   11316: 	$courseid=$wcourseid; 
                   11317:     }
                   11318:     if (!defined $domain) { $domain=$wdomain; }
                   11319:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11320: 
                   11321:     my $which;
                   11322:     if (defined($cenv->{'rndseed'})) {
                   11323: 	$which = $cenv->{'rndseed'};
                   11324:     } else {
                   11325: 	$which =&get_rand_alg($courseid);
                   11326:     }
1.491     albertel 11327:     if (defined(&getCODE())) {
1.1133    foxr     11328: 
1.675     albertel 11329: 	if ($which eq '64bit5') {
                   11330: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11331: 	} elsif ($which eq '64bit4') {
1.575     albertel 11332: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11333: 	} else {
                   11334: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11335: 	}
1.675     albertel 11336:     } elsif ($which eq '64bit5') {
                   11337: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11338:     } elsif ($which eq '64bit4') {
                   11339: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11340:     } elsif ($which eq '64bit3') {
                   11341: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11342:     } elsif ($which eq '64bit2') {
                   11343: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11344:     } elsif ($which eq '64bit') {
                   11345: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11346:     }
                   11347:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11348: }
                   11349: 
                   11350: sub rndseed_32bit {
                   11351:     my ($symb,$courseid,$domain,$username)=@_;
                   11352:     {
                   11353: 	use integer;
                   11354: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11355: 	my $symbseed=numval($symb) << 22;
                   11356: 	my $namechck=unpack("%32C*",$username) << 17;
                   11357: 	my $nameseed=numval($username) << 12;
                   11358: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11359: 	my $courseseed=unpack("%32C*",$courseid);
                   11360: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11361: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11362: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11363: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11364: 	return $num;
                   11365:     }
                   11366: }
                   11367: 
                   11368: sub rndseed_64bit {
                   11369:     my ($symb,$courseid,$domain,$username)=@_;
                   11370:     {
                   11371: 	use integer;
                   11372: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11373: 	my $symbseed=numval($symb) << 10;
                   11374: 	my $namechck=unpack("%32S*",$username);
                   11375: 	
                   11376: 	my $nameseed=numval($username) << 21;
                   11377: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11378: 	my $courseseed=unpack("%32S*",$courseid);
                   11379: 	
                   11380: 	my $num1=$symbchck+$symbseed+$namechck;
                   11381: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11382: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11383: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11384: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11385: 	return "$num1,$num2";
1.155     albertel 11386:     }
1.366     albertel 11387: }
                   11388: 
1.443     albertel 11389: sub rndseed_64bit2 {
                   11390:     my ($symb,$courseid,$domain,$username)=@_;
                   11391:     {
                   11392: 	use integer;
                   11393: 	# strings need to be an even # of cahracters long, it it is odd the
                   11394:         # last characters gets thrown away
                   11395: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11396: 	my $symbseed=numval($symb) << 10;
                   11397: 	my $namechck=unpack("%32S*",$username.' ');
                   11398: 	
                   11399: 	my $nameseed=numval($username) << 21;
1.501     albertel 11400: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11401: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11402: 	
                   11403: 	my $num1=$symbchck+$symbseed+$namechck;
                   11404: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11405: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11406: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11407: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11408: 	return "$num1,$num2";
                   11409:     }
                   11410: }
                   11411: 
                   11412: sub rndseed_64bit3 {
                   11413:     my ($symb,$courseid,$domain,$username)=@_;
                   11414:     {
                   11415: 	use integer;
                   11416: 	# strings need to be an even # of cahracters long, it it is odd the
                   11417:         # last characters gets thrown away
                   11418: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11419: 	my $symbseed=numval2($symb) << 10;
                   11420: 	my $namechck=unpack("%32S*",$username.' ');
                   11421: 	
                   11422: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11423: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11424: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11425: 	
                   11426: 	my $num1=$symbchck+$symbseed+$namechck;
                   11427: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11428: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11429: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11430: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11431: 	
1.503     albertel 11432: 	return "$num1:$num2";
1.443     albertel 11433:     }
                   11434: }
                   11435: 
1.575     albertel 11436: sub rndseed_64bit4 {
                   11437:     my ($symb,$courseid,$domain,$username)=@_;
                   11438:     {
                   11439: 	use integer;
                   11440: 	# strings need to be an even # of cahracters long, it it is odd the
                   11441:         # last characters gets thrown away
                   11442: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11443: 	my $symbseed=numval3($symb) << 10;
                   11444: 	my $namechck=unpack("%32S*",$username.' ');
                   11445: 	
                   11446: 	my $nameseed=numval3($username) << 21;
                   11447: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11448: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11449: 	
                   11450: 	my $num1=$symbchck+$symbseed+$namechck;
                   11451: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11452: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11453: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11454: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11455: 	
1.575     albertel 11456: 	return "$num1:$num2";
                   11457:     }
                   11458: }
                   11459: 
1.675     albertel 11460: sub rndseed_64bit5 {
                   11461:     my ($symb,$courseid,$domain,$username)=@_;
                   11462:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11463:     return "$num1:$num2";
                   11464: }
                   11465: 
1.366     albertel 11466: sub rndseed_CODE_64bit {
                   11467:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11468:     {
1.366     albertel 11469: 	use integer;
1.443     albertel 11470: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11471: 	my $symbseed=numval2($symb);
1.491     albertel 11472: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11473: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11474: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11475: 	my $num1=$symbseed+$CODEchck;
                   11476: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11477: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11478: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11479: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11480: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11481: 	return "$num1:$num2";
1.366     albertel 11482:     }
                   11483: }
                   11484: 
1.575     albertel 11485: sub rndseed_CODE_64bit4 {
                   11486:     my ($symb,$courseid,$domain,$username)=@_;
                   11487:     {
                   11488: 	use integer;
                   11489: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11490: 	my $symbseed=numval3($symb);
                   11491: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11492: 	my $CODEseed=numval3(&getCODE());
                   11493: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11494: 	my $num1=$symbseed+$CODEchck;
                   11495: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11496: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11497: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11498: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11499: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11500: 	return "$num1:$num2";
                   11501:     }
                   11502: }
                   11503: 
1.675     albertel 11504: sub rndseed_CODE_64bit5 {
                   11505:     my ($symb,$courseid,$domain,$username)=@_;
                   11506:     my $code = &getCODE();
                   11507:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11508:     return "$num1:$num2";
                   11509: }
                   11510: 
1.366     albertel 11511: sub setup_random_from_rndseed {
                   11512:     my ($rndseed)=@_;
1.503     albertel 11513:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11514:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11515:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11516:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11517:         } else {
                   11518:             &Math::Random::random_set_seed($num1,$num2);
                   11519:         }
1.366     albertel 11520:     } else {
                   11521: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11522:     }
1.36      albertel 11523: }
                   11524: 
1.474     albertel 11525: sub latest_receipt_algorithm_id {
1.835     albertel 11526:     return 'receipt3';
1.474     albertel 11527: }
                   11528: 
1.480     www      11529: sub recunique {
                   11530:     my $fucourseid=shift;
                   11531:     my $unique;
1.835     albertel 11532:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11533: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11534: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11535:     } else {
                   11536: 	$unique=$perlvar{'lonReceipt'};
                   11537:     }
                   11538:     return unpack("%32C*",$unique);
                   11539: }
                   11540: 
                   11541: sub recprefix {
                   11542:     my $fucourseid=shift;
                   11543:     my $prefix;
1.835     albertel 11544:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11545: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11546: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11547:     } else {
                   11548: 	$prefix=$perlvar{'lonHostID'};
                   11549:     }
                   11550:     return unpack("%32C*",$prefix);
                   11551: }
                   11552: 
1.76      www      11553: sub ireceipt {
1.474     albertel 11554:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11555: 
                   11556:     my $return =&recprefix($fucourseid).'-';
                   11557: 
                   11558:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11559: 	$env{'request.state'} eq 'construct') {
                   11560: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11561: 	return $return;
                   11562:     }
                   11563: 
1.76      www      11564:     my $cuname=unpack("%32C*",$funame);
                   11565:     my $cudom=unpack("%32C*",$fudom);
                   11566:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11567:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11568:     my $cunique=&recunique($fucourseid);
1.474     albertel 11569:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11570:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11571: 
1.790     albertel 11572: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11573: 			       
                   11574: 	$return.= ($cunique%$cuname+
                   11575: 		   $cunique%$cudom+
                   11576: 		   $cusymb%$cuname+
                   11577: 		   $cusymb%$cudom+
                   11578: 		   $cucourseid%$cuname+
                   11579: 		   $cucourseid%$cudom+
                   11580: 		   $cpart%$cuname+
                   11581: 		   $cpart%$cudom);
                   11582:     } else {
                   11583: 	$return.= ($cunique%$cuname+
                   11584: 		   $cunique%$cudom+
                   11585: 		   $cusymb%$cuname+
                   11586: 		   $cusymb%$cudom+
                   11587: 		   $cucourseid%$cuname+
                   11588: 		   $cucourseid%$cudom);
                   11589:     }
                   11590:     return $return;
1.76      www      11591: }
                   11592: 
                   11593: sub receipt {
1.474     albertel 11594:     my ($part)=@_;
1.790     albertel 11595:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11596:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11597: }
1.260     ng       11598: 
1.790     albertel 11599: sub whichuser {
                   11600:     my ($passedsymb)=@_;
                   11601:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11602:     if (defined($env{'form.grade_symb'})) {
                   11603: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11604: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11605: 	if (!$allowed &&
                   11606: 	    exists($env{'request.course.sec'}) &&
                   11607: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11608: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11609: 			      '/'.$env{'request.course.sec'});
                   11610: 	}
                   11611: 	if ($allowed) {
                   11612: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11613: 	    $courseid=$tmp_courseid;
                   11614: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11615: 	    ($name)=&get_env_multiple('form.grade_username');
                   11616: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11617: 	}
                   11618:     }
                   11619:     if (!$passedsymb) {
                   11620: 	$symb=&symbread();
                   11621:     } else {
                   11622: 	$symb=$passedsymb;
                   11623:     }
                   11624:     $courseid=$env{'request.course.id'};
                   11625:     $domain=$env{'user.domain'};
                   11626:     $name=$env{'user.name'};
                   11627:     if ($name eq 'public' && $domain eq 'public') {
                   11628: 	if (!defined($env{'form.username'})) {
                   11629: 	    $env{'form.username'}.=time.rand(10000000);
                   11630: 	}
                   11631: 	$name.=$env{'form.username'};
                   11632:     }
                   11633:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11634: 
                   11635: }
                   11636: 
1.36      albertel 11637: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11638: # returns either the contents of the file or 
                   11639: # -1 if the file doesn't exist
1.481     raeburn  11640: #
                   11641: # if the target is a file that was uploaded via DOCS, 
                   11642: # a check will be made to see if a current copy exists on the local server,
                   11643: # if it does this will be served, otherwise a copy will be retrieved from
                   11644: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11645: # the local server.   
1.472     albertel 11646: 
1.36      albertel 11647: sub getfile {
1.538     albertel 11648:     my ($file) = @_;
1.609     banghart 11649:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11650:     &repcopy($file);
                   11651:     return &readfile($file);
                   11652: }
                   11653: 
                   11654: sub repcopy_userfile {
                   11655:     my ($file)=@_;
1.1142    raeburn  11656:     my $londocroot = $perlvar{'lonDocRoot'};
                   11657:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11658:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11659:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11660: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11661:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11662:     if (-e "$file") {
1.828     www      11663: # we already have a local copy, check it out
1.538     albertel 11664: 	my @fileinfo = stat($file);
1.828     www      11665: 	my $rtncode;
                   11666: 	my $info;
1.538     albertel 11667: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11668: 	if ($lwpresp ne 'ok') {
1.828     www      11669: # there is no such file anymore, even though we had a local copy
1.482     albertel 11670: 	    if ($rtncode eq '404') {
1.538     albertel 11671: 		unlink($file);
1.482     albertel 11672: 	    }
                   11673: 	    return -1;
                   11674: 	}
                   11675: 	if ($info < $fileinfo[9]) {
1.828     www      11676: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11677: 	    return 'ok';
1.828     www      11678: 	} else {
                   11679: # the file is outdated, get rid of it
                   11680: 	    unlink($file);
1.482     albertel 11681: 	}
1.828     www      11682:     }
                   11683: # one way or the other, at this point, we don't have the file
                   11684: # construct the correct path for the file
                   11685:     my @parts = ($cdom,$cnum); 
                   11686:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11687: 	push @parts, split(/\//,$1);
                   11688:     }
                   11689:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11690:     foreach my $part (@parts) {
                   11691: 	$path .= '/'.$part;
                   11692: 	if (!-e $path) {
                   11693: 	    mkdir($path,0770);
1.482     albertel 11694: 	}
                   11695:     }
1.828     www      11696: # now the path exists for sure
                   11697: # get a user agent
                   11698:     my $ua=new LWP::UserAgent;
                   11699:     my $transferfile=$file.'.in.transfer';
                   11700: # FIXME: this should flock
                   11701:     if (-e $transferfile) { return 'ok'; }
                   11702:     my $request;
                   11703:     $uri=~s/^\///;
1.980     raeburn  11704:     my $homeserver = &homeserver($cnum,$cdom);
                   11705:     my $protocol = $protocol{$homeserver};
                   11706:     $protocol = 'http' if ($protocol ne 'https');
                   11707:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11708:     my $response=$ua->request($request,$transferfile);
                   11709: # did it work?
                   11710:     if ($response->is_error()) {
                   11711: 	unlink($transferfile);
                   11712: 	&logthis("Userfile repcopy failed for $uri");
                   11713: 	return -1;
                   11714:     }
                   11715: # worked, rename the transfer file
                   11716:     rename($transferfile,$file);
1.607     raeburn  11717:     return 'ok';
1.481     raeburn  11718: }
                   11719: 
1.517     albertel 11720: sub tokenwrapper {
                   11721:     my $uri=shift;
1.980     raeburn  11722:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11723:     $uri=~s|^/||;
1.620     albertel 11724:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11725:     my $token=$1;
1.552     albertel 11726:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11727:     if ($udom && $uname && $file) {
                   11728: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11729:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11730:         my $homeserver = &homeserver($uname,$udom);
                   11731:         my $protocol = $protocol{$homeserver};
                   11732:         $protocol = 'http' if ($protocol ne 'https');
                   11733:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11734:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11735:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11736:     } else {
                   11737:         return '/adm/notfound.html';
                   11738:     }
                   11739: }
                   11740: 
1.828     www      11741: # call with reqtype HEAD: get last modification time
                   11742: # call with reqtype GET: get the file contents
                   11743: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11744: #
1.481     raeburn  11745: sub getuploaded {
                   11746:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11747:     $uri=~s/^\///;
1.980     raeburn  11748:     my $homeserver = &homeserver($cnum,$cdom);
                   11749:     my $protocol = $protocol{$homeserver};
                   11750:     $protocol = 'http' if ($protocol ne 'https');
                   11751:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11752:     my $ua=new LWP::UserAgent;
                   11753:     my $request=new HTTP::Request($reqtype,$uri);
                   11754:     my $response=$ua->request($request);
                   11755:     $$rtncode = $response->code;
1.482     albertel 11756:     if (! $response->is_success()) {
                   11757: 	return 'failed';
                   11758:     }      
                   11759:     if ($reqtype eq 'HEAD') {
1.486     www      11760: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11761:     } elsif ($reqtype eq 'GET') {
                   11762: 	$$info = $response->content;
1.472     albertel 11763:     }
1.482     albertel 11764:     return 'ok';
1.36      albertel 11765: }
                   11766: 
1.481     raeburn  11767: sub readfile {
                   11768:     my $file = shift;
                   11769:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11770:     my $fh;
                   11771:     open($fh,"<$file");
                   11772:     my $a='';
1.800     albertel 11773:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11774:     return $a;
                   11775: }
                   11776: 
1.36      albertel 11777: sub filelocation {
1.590     banghart 11778:     my ($dir,$file) = @_;
                   11779:     my $location;
                   11780:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11781: 
                   11782:     if ($file =~ m-^/adm/-) {
                   11783: 	$file=~s-^/adm/wrapper/-/-;
                   11784: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11785:     }
1.882     albertel 11786: 
1.1139    www      11787:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11788:         $location = $file;
1.609     banghart 11789:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11790:         my ($udom,$uname,$filename)=
1.811     albertel 11791:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11792:         my $home=&homeserver($uname,$udom);
                   11793:         my $is_me=0;
                   11794:         my @ids=&current_machine_ids();
                   11795:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11796:         if ($is_me) {
1.1117    foxr     11797:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11798:         } else {
                   11799:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11800:   	      $udom.'/'.$uname.'/'.$filename;
                   11801:         }
1.882     albertel 11802:     } elsif ($file =~ m-^/adm/-) {
                   11803: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11804:     } else {
                   11805:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11806:         $file=~s:^/(res|priv)/:/:;
                   11807:         my $space=$1;
1.590     banghart 11808:         if ( !( $file =~ m:^/:) ) {
                   11809:             $location = $dir. '/'.$file;
                   11810:         } else {
1.1142    raeburn  11811:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11812:         }
1.59      albertel 11813:     }
1.590     banghart 11814:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11815:     while ($location=~m{/\.\./}) {
                   11816: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11817: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11818: 	} else {
                   11819: 	    $location=~ s{/\.\./}{/}g;
                   11820: 	}
                   11821:     } #remove dir/..
1.590     banghart 11822:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11823:     return $location;
1.46      www      11824: }
1.36      albertel 11825: 
1.46      www      11826: sub hreflocation {
                   11827:     my ($dir,$file)=@_;
1.980     raeburn  11828:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11829: 	$file=filelocation($dir,$file);
1.700     albertel 11830:     } elsif ($file=~m-^/adm/-) {
                   11831: 	$file=~s-^/adm/wrapper/-/-;
                   11832: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11833:     }
                   11834:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11835: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11836:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11837: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11838: 	        {/uploaded/$1/$2/}x;
1.46      www      11839:     }
1.913     albertel 11840:     if ($file=~ m{^/userfiles/}) {
                   11841: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11842:     }
1.462     albertel 11843:     return $file;
1.465     albertel 11844: }
                   11845: 
1.1139    www      11846: 
                   11847: 
                   11848: 
                   11849: 
1.465     albertel 11850: sub current_machine_domains {
1.853     albertel 11851:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11852: }
                   11853: 
                   11854: sub machine_domains {
                   11855:     my ($hostname) = @_;
1.465     albertel 11856:     my @domains;
1.838     albertel 11857:     my %hostname = &all_hostnames();
1.465     albertel 11858:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11859: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11860: 	if ($hostname eq $name) {
1.844     albertel 11861: 	    push(@domains,&host_domain($id));
1.465     albertel 11862: 	}
                   11863:     }
                   11864:     return @domains;
                   11865: }
                   11866: 
                   11867: sub current_machine_ids {
1.853     albertel 11868:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11869: }
                   11870: 
                   11871: sub machine_ids {
                   11872:     my ($hostname) = @_;
                   11873:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11874:     my @ids;
1.888     albertel 11875:     my %name_to_host = &all_names();
1.889     albertel 11876:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11877: 	return @{ $name_to_host{$hostname} };
                   11878:     }
                   11879:     return;
1.31      www      11880: }
                   11881: 
1.824     raeburn  11882: sub additional_machine_domains {
                   11883:     my @domains;
                   11884:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11885:     while( my $line = <$fh>) {
                   11886:         $line =~ s/\s//g;
                   11887:         push(@domains,$line);
                   11888:     }
                   11889:     return @domains;
                   11890: }
                   11891: 
                   11892: sub default_login_domain {
                   11893:     my $domain = $perlvar{'lonDefDomain'};
                   11894:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11895:     foreach my $posdom (&current_machine_domains(),
                   11896:                         &additional_machine_domains()) {
                   11897:         if (lc($posdom) eq lc($testdomain)) {
                   11898:             $domain=$posdom;
                   11899:             last;
                   11900:         }
                   11901:     }
                   11902:     return $domain;
                   11903: }
                   11904: 
1.31      www      11905: # ------------------------------------------------------------- Declutters URLs
                   11906: 
                   11907: sub declutter {
                   11908:     my $thisfn=shift;
1.569     albertel 11909:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  11910:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11911:         $thisfn=~s{^/home/httpd/html}{};
                   11912:     }
1.31      www      11913:     $thisfn=~s/^\///;
1.697     albertel 11914:     $thisfn=~s|^adm/wrapper/||;
                   11915:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11916:     $thisfn=~s/^res\///;
1.1172    bisitz   11917:     $thisfn=~s/^priv\///;
1.1032    raeburn  11918:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11919:         $thisfn=~s/\?.+$//;
                   11920:     }
1.268     www      11921:     return $thisfn;
                   11922: }
                   11923: 
                   11924: # ------------------------------------------------------------- Clutter up URLs
                   11925: 
                   11926: sub clutter {
                   11927:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11928:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11929: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11930:        $thisfn='/res'.$thisfn; 
                   11931:     }
1.1031    raeburn  11932:     if ($thisfn !~m|^/adm|) {
                   11933: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11934: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11935: 	} else {
                   11936: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11937: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11938: 	    if ($embstyle eq 'ssi'
                   11939: 		|| ($embstyle eq 'hdn')
                   11940: 		|| ($embstyle eq 'rat')
                   11941: 		|| ($embstyle eq 'prv')
                   11942: 		|| ($embstyle eq 'ign')) {
                   11943: 		#do nothing with these
                   11944: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11945: 		|| ($embstyle eq 'emb')
                   11946: 		|| ($embstyle eq 'wrp')) {
                   11947: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11948: 	    } elsif ($embstyle eq 'unk'
                   11949: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11950: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11951: 	    } else {
1.718     www      11952: #		&logthis("Got a blank emb style");
1.695     albertel 11953: 	    }
1.694     albertel 11954: 	}
                   11955:     }
1.31      www      11956:     return $thisfn;
1.12      www      11957: }
                   11958: 
1.787     albertel 11959: sub clutter_with_no_wrapper {
                   11960:     my $uri = &clutter(shift);
                   11961:     if ($uri =~ m-^/adm/-) {
                   11962: 	$uri =~ s-^/adm/wrapper/-/-;
                   11963: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11964:     }
                   11965:     return $uri;
                   11966: }
                   11967: 
1.557     albertel 11968: sub freeze_escape {
                   11969:     my ($value)=@_;
                   11970:     if (ref($value)) {
                   11971: 	$value=&nfreeze($value);
                   11972: 	return '__FROZEN__'.&escape($value);
                   11973:     }
                   11974:     return &escape($value);
                   11975: }
                   11976: 
1.11      www      11977: 
1.557     albertel 11978: sub thaw_unescape {
                   11979:     my ($value)=@_;
                   11980:     if ($value =~ /^__FROZEN__/) {
                   11981: 	substr($value,0,10,undef);
                   11982: 	$value=&unescape($value);
                   11983: 	return &thaw($value);
                   11984:     }
                   11985:     return &unescape($value);
                   11986: }
                   11987: 
1.436     albertel 11988: sub correct_line_ends {
                   11989:     my ($result)=@_;
                   11990:     $$result =~s/\r\n/\n/mg;
                   11991:     $$result =~s/\r/\n/mg;
1.415     albertel 11992: }
1.1       albertel 11993: # ================================================================ Main Program
                   11994: 
1.184     www      11995: sub goodbye {
1.204     albertel 11996:    &logthis("Starting Shut down");
1.443     albertel 11997: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11998:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11999: #converted
1.599     albertel 12000: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12001:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12002: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12003: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12004: #1.1 only
1.870     albertel 12005: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12006: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12007: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12008: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12009:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12010:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12011:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12012:    &flushcourselogs();
                   12013:    &logthis("Shutting down");
                   12014: }
                   12015: 
1.852     albertel 12016: sub get_dns {
1.1210    raeburn  12017:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12018:     if (!$ignore_cache) {
                   12019: 	my ($content,$cached)=
                   12020: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12021: 	if ($cached) {
1.1210    raeburn  12022: 	    &$func($content,$hashref);
1.869     albertel 12023: 	    return;
                   12024: 	}
                   12025:     }
                   12026: 
                   12027:     my %alldns;
1.852     albertel 12028:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12029:     foreach my $dns (<$config>) {
                   12030: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12031:         my $line = $1;
                   12032:         my ($host,$protocol) = split(/:/,$line);
                   12033:         if ($protocol ne 'https') {
                   12034:             $protocol = 'http';
                   12035:         }
                   12036: 	$alldns{$host} = $protocol;
1.869     albertel 12037:     }
                   12038:     while (%alldns) {
1.1263    raeburn  12039: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12040: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12041:         $ua->timeout(30);
1.979     raeburn  12042: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12043: 	my $response=$ua->request($request);
1.979     raeburn  12044:         delete($alldns{$dns});
1.852     albertel 12045: 	next if ($response->is_error());
                   12046: 	my @content = split("\n",$response->content);
1.1210    raeburn  12047: 	unless ($nocache) {
1.1219    raeburn  12048: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12049: 	}
                   12050: 	&$func(\@content,$hashref);
1.869     albertel 12051: 	return;
1.852     albertel 12052:     }
                   12053:     close($config);
1.871     albertel 12054:     my $which = (split('/',$url))[3];
                   12055:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12056:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12057:     my @content = <$config>;
1.1210    raeburn  12058:     &$func(\@content,$hashref);
                   12059:     return;
                   12060: }
                   12061: 
                   12062: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12063: sub parse_dns_checksums_tab {
1.1210    raeburn  12064:     my ($lines,$hashref) = @_;
1.1264    raeburn  12065:     my $lonhost = $perlvar{'lonHostID'};
                   12066:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12067:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12068:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12069:     my $webconfdir = '/etc/httpd/conf';
                   12070:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12071:         $webconfdir = '/etc/apache2';
                   12072:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12073:         if ($1 >= 10) {
                   12074:             $webconfdir = '/etc/apache2';
                   12075:         }
                   12076:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12077:         if ($1 >= 10.0) {
                   12078:             $webconfdir = '/etc/apache2';
                   12079:         }
                   12080:     }
1.1210    raeburn  12081:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12082:     my (%chksum,%revnum);
                   12083:     if (ref($lines) eq 'ARRAY') {
                   12084:         chomp(@{$lines});
1.1238    raeburn  12085:         my $version = shift(@{$lines});
                   12086:         if ($version eq $release) {  
1.1210    raeburn  12087:             foreach my $line (@{$lines}) {
1.1238    raeburn  12088:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12089:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12090:                     if ($webconfdir eq '/etc/apache2') {
                   12091:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12092:                     }
                   12093:                 }
1.1238    raeburn  12094:                 $chksum{$file} = $shasum;
                   12095:                 $revnum{$file} = $version;
1.1210    raeburn  12096:             }
                   12097:             if (ref($hashref) eq 'HASH') {
                   12098:                 %{$hashref} = (
                   12099:                                 sums     => \%chksum,
                   12100:                                 versions => \%revnum,
                   12101:                               );
                   12102:             }
                   12103:         }
                   12104:     }
1.869     albertel 12105:     return;
1.852     albertel 12106: }
1.1210    raeburn  12107: 
                   12108: sub fetch_dns_checksums {
1.1238    raeburn  12109:     my %checksums;
                   12110:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12111:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12112:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12113:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12114:              \%checksums);
1.1210    raeburn  12115:     return \%checksums;
                   12116: }
                   12117: 
1.327     albertel 12118: # ------------------------------------------------------------ Read domain file
                   12119: {
1.852     albertel 12120:     my $loaded;
1.846     albertel 12121:     my %domain;
                   12122: 
1.852     albertel 12123:     sub parse_domain_tab {
                   12124: 	my ($lines) = @_;
                   12125: 	foreach my $line (@$lines) {
                   12126: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12127: 
1.846     albertel 12128: 	    chomp($line);
1.852     albertel 12129: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12130: 	    my %this_domain;
                   12131: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12132: 			       'lang_def', 'city', 'longi', 'lati',
                   12133: 			       'primary') {
                   12134: 		$this_domain{$field} = shift(@elements);
                   12135: 	    }
                   12136: 	    $domain{$name} = \%this_domain;
1.852     albertel 12137: 	}
                   12138:     }
1.864     albertel 12139: 
                   12140:     sub reset_domain_info {
                   12141: 	undef($loaded);
                   12142: 	undef(%domain);
                   12143:     }
                   12144: 
1.852     albertel 12145:     sub load_domain_tab {
1.869     albertel 12146: 	my ($ignore_cache) = @_;
                   12147: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12148: 	my $fh;
                   12149: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12150: 	    my @lines = <$fh>;
                   12151: 	    &parse_domain_tab(\@lines);
1.448     albertel 12152: 	}
1.852     albertel 12153: 	close($fh);
                   12154: 	$loaded = 1;
1.327     albertel 12155:     }
1.846     albertel 12156: 
                   12157:     sub domain {
1.852     albertel 12158: 	&load_domain_tab() if (!$loaded);
                   12159: 
1.846     albertel 12160: 	my ($name,$what) = @_;
                   12161: 	return if ( !exists($domain{$name}) );
                   12162: 
                   12163: 	if (!$what) {
                   12164: 	    return $domain{$name}{'description'};
                   12165: 	}
                   12166: 	return $domain{$name}{$what};
                   12167:     }
1.974     raeburn  12168: 
                   12169:     sub domain_info {
                   12170:         &load_domain_tab() if (!$loaded);
                   12171:         return %domain;
                   12172:     }
                   12173: 
1.327     albertel 12174: }
                   12175: 
                   12176: 
1.1       albertel 12177: # ------------------------------------------------------------- Read hosts file
                   12178: {
1.838     albertel 12179:     my %hostname;
1.844     albertel 12180:     my %hostdom;
1.845     albertel 12181:     my %libserv;
1.852     albertel 12182:     my $loaded;
1.888     albertel 12183:     my %name_to_host;
1.1074    raeburn  12184:     my %internetdom;
1.1107    raeburn  12185:     my %LC_dns_serv;
1.852     albertel 12186: 
                   12187:     sub parse_hosts_tab {
                   12188: 	my ($file) = @_;
                   12189: 	foreach my $configline (@$file) {
                   12190: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12191:             chomp($configline);
                   12192: 	    if ($configline =~ /^\^/) {
                   12193:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12194:                     $LC_dns_serv{$1} = 1;
                   12195:                 }
                   12196:                 next;
                   12197:             }
1.1074    raeburn  12198: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12199: 	    $name=~s/\s//g;
                   12200: 	    if ($id && $domain && $role && $name) {
                   12201: 		$hostname{$id}=$name;
1.888     albertel 12202: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12203: 		$hostdom{$id}=$domain;
                   12204: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12205:                 if (defined($protocol)) {
                   12206:                     if ($protocol eq 'https') {
                   12207:                         $protocol{$id} = $protocol;
                   12208:                     } else {
                   12209:                         $protocol{$id} = 'http'; 
                   12210:                     }
1.968     raeburn  12211:                 } else {
1.969     raeburn  12212:                     $protocol{$id} = 'http';
1.968     raeburn  12213:                 }
1.1074    raeburn  12214:                 if (defined($intdom)) {
                   12215:                     $internetdom{$id} = $intdom;
                   12216:                 }
1.852     albertel 12217: 	    }
                   12218: 	}
                   12219:     }
1.864     albertel 12220:     
                   12221:     sub reset_hosts_info {
1.897     albertel 12222: 	&purge_remembered();
1.864     albertel 12223: 	&reset_domain_info();
                   12224: 	&reset_hosts_ip_info();
1.892     albertel 12225: 	undef(%name_to_host);
1.864     albertel 12226: 	undef(%hostname);
                   12227: 	undef(%hostdom);
                   12228: 	undef(%libserv);
                   12229: 	undef($loaded);
                   12230:     }
1.1       albertel 12231: 
1.852     albertel 12232:     sub load_hosts_tab {
1.869     albertel 12233: 	my ($ignore_cache) = @_;
                   12234: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12235: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12236: 	my @config = <$config>;
                   12237: 	&parse_hosts_tab(\@config);
                   12238: 	close($config);
                   12239: 	$loaded=1;
1.1       albertel 12240:     }
1.852     albertel 12241: 
1.838     albertel 12242:     sub hostname {
1.852     albertel 12243: 	&load_hosts_tab() if (!$loaded);
                   12244: 
1.838     albertel 12245: 	my ($lonid) = @_;
                   12246: 	return $hostname{$lonid};
                   12247:     }
1.845     albertel 12248: 
1.838     albertel 12249:     sub all_hostnames {
1.852     albertel 12250: 	&load_hosts_tab() if (!$loaded);
                   12251: 
1.838     albertel 12252: 	return %hostname;
                   12253:     }
1.845     albertel 12254: 
1.888     albertel 12255:     sub all_names {
                   12256: 	&load_hosts_tab() if (!$loaded);
                   12257: 
                   12258: 	return %name_to_host;
                   12259:     }
                   12260: 
1.974     raeburn  12261:     sub all_host_domain {
                   12262:         &load_hosts_tab() if (!$loaded);
                   12263:         return %hostdom;
                   12264:     }
                   12265: 
1.845     albertel 12266:     sub is_library {
1.852     albertel 12267: 	&load_hosts_tab() if (!$loaded);
                   12268: 
1.845     albertel 12269: 	return exists($libserv{$_[0]});
                   12270:     }
                   12271: 
                   12272:     sub all_library {
1.852     albertel 12273: 	&load_hosts_tab() if (!$loaded);
                   12274: 
1.845     albertel 12275: 	return %libserv;
                   12276:     }
                   12277: 
1.1062    droeschl 12278:     sub unique_library {
                   12279: 	#2x reverse removes all hostnames that appear more than once
                   12280:         my %unique = reverse &all_library();
                   12281:         return reverse %unique;
                   12282:     }
                   12283: 
1.841     albertel 12284:     sub get_servers {
1.852     albertel 12285: 	&load_hosts_tab() if (!$loaded);
                   12286: 
1.841     albertel 12287: 	my ($domain,$type) = @_;
                   12288: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12289: 	                                          : %hostname;
                   12290: 	my %result;
1.842     albertel 12291: 	if (ref($domain) eq 'ARRAY') {
                   12292: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12293: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12294: 		    $result{$host} = $hostname;
                   12295: 		}
                   12296: 	    }
                   12297: 	} else {
                   12298: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12299: 		if ($hostdom{$host} eq $domain) {
                   12300: 		    $result{$host} = $hostname;
                   12301: 		}
1.841     albertel 12302: 	    }
                   12303: 	}
                   12304: 	return %result;
                   12305:     }
1.845     albertel 12306: 
1.1062    droeschl 12307:     sub get_unique_servers {
                   12308:         my %unique = reverse &get_servers(@_);
                   12309: 	return reverse %unique;
                   12310:     }
                   12311: 
1.844     albertel 12312:     sub host_domain {
1.852     albertel 12313: 	&load_hosts_tab() if (!$loaded);
                   12314: 
1.844     albertel 12315: 	my ($lonid) = @_;
                   12316: 	return $hostdom{$lonid};
                   12317:     }
                   12318: 
1.841     albertel 12319:     sub all_domains {
1.852     albertel 12320: 	&load_hosts_tab() if (!$loaded);
                   12321: 
1.841     albertel 12322: 	my %seen;
                   12323: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12324: 	return @uniq;
                   12325:     }
1.1074    raeburn  12326: 
                   12327:     sub internet_dom {
                   12328:         &load_hosts_tab() if (!$loaded);
                   12329: 
                   12330:         my ($lonid) = @_;
                   12331:         return $internetdom{$lonid};
                   12332:     }
1.1107    raeburn  12333: 
                   12334:     sub is_LC_dns {
                   12335:         &load_hosts_tab() if (!$loaded);
                   12336: 
                   12337:         my ($hostname) = @_;
                   12338:         return exists($LC_dns_serv{$hostname});
                   12339:     }
                   12340: 
1.1       albertel 12341: }
                   12342: 
1.847     albertel 12343: { 
                   12344:     my %iphost;
1.856     albertel 12345:     my %name_to_ip;
                   12346:     my %lonid_to_ip;
1.869     albertel 12347: 
1.847     albertel 12348:     sub get_hosts_from_ip {
                   12349: 	my ($ip) = @_;
                   12350: 	my %iphosts = &get_iphost();
                   12351: 	if (ref($iphosts{$ip})) {
                   12352: 	    return @{$iphosts{$ip}};
                   12353: 	}
                   12354: 	return;
1.839     albertel 12355:     }
1.864     albertel 12356:     
                   12357:     sub reset_hosts_ip_info {
                   12358: 	undef(%iphost);
                   12359: 	undef(%name_to_ip);
                   12360: 	undef(%lonid_to_ip);
                   12361:     }
1.856     albertel 12362: 
                   12363:     sub get_host_ip {
                   12364: 	my ($lonid) = @_;
                   12365: 	if (exists($lonid_to_ip{$lonid})) {
                   12366: 	    return $lonid_to_ip{$lonid};
                   12367: 	}
                   12368: 	my $name=&hostname($lonid);
                   12369:    	my $ip = gethostbyname($name);
                   12370: 	return if (!$ip || length($ip) ne 4);
                   12371: 	$ip=inet_ntoa($ip);
                   12372: 	$name_to_ip{$name}   = $ip;
                   12373: 	$lonid_to_ip{$lonid} = $ip;
                   12374: 	return $ip;
                   12375:     }
1.847     albertel 12376:     
                   12377:     sub get_iphost {
1.869     albertel 12378: 	my ($ignore_cache) = @_;
1.894     albertel 12379: 
1.869     albertel 12380: 	if (!$ignore_cache) {
                   12381: 	    if (%iphost) {
                   12382: 		return %iphost;
                   12383: 	    }
                   12384: 	    my ($ip_info,$cached)=
                   12385: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12386: 	    if ($cached) {
                   12387: 		%iphost      = %{$ip_info->[0]};
                   12388: 		%name_to_ip  = %{$ip_info->[1]};
                   12389: 		%lonid_to_ip = %{$ip_info->[2]};
                   12390: 		return %iphost;
                   12391: 	    }
                   12392: 	}
1.894     albertel 12393: 
                   12394: 	# get yesterday's info for fallback
                   12395: 	my %old_name_to_ip;
                   12396: 	my ($ip_info,$cached)=
                   12397: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12398: 	if ($cached) {
                   12399: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12400: 	}
                   12401: 
1.888     albertel 12402: 	my %name_to_host = &all_names();
                   12403: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12404: 	    my $ip;
                   12405: 	    if (!exists($name_to_ip{$name})) {
                   12406: 		$ip = gethostbyname($name);
                   12407: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12408: 		    if (defined($old_name_to_ip{$name})) {
                   12409: 			$ip = $old_name_to_ip{$name};
                   12410: 			&logthis("Can't find $name defaulting to old $ip");
                   12411: 		    } else {
                   12412: 			&logthis("Name $name no IP found");
                   12413: 			next;
                   12414: 		    }
                   12415: 		} else {
                   12416: 		    $ip=inet_ntoa($ip);
1.847     albertel 12417: 		}
                   12418: 		$name_to_ip{$name} = $ip;
                   12419: 	    } else {
                   12420: 		$ip = $name_to_ip{$name};
1.653     albertel 12421: 	    }
1.888     albertel 12422: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12423: 		$lonid_to_ip{$id} = $ip;
                   12424: 	    }
                   12425: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12426: 	}
1.1219    raeburn  12427: 	&do_cache_new('iphost','iphost',
                   12428: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12429: 		      48*60*60);
1.869     albertel 12430: 
1.847     albertel 12431: 	return %iphost;
1.598     albertel 12432:     }
                   12433: 
1.992     raeburn  12434:     #
                   12435:     #  Given a DNS returns the loncapa host name for that DNS 
                   12436:     # 
                   12437:     sub host_from_dns {
                   12438:         my ($dns) = @_;
                   12439:         my @hosts;
                   12440:         my $ip;
                   12441: 
1.993     raeburn  12442:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12443:             $ip = $name_to_ip{$dns};
                   12444:         }
                   12445:         if (!$ip) {
                   12446:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12447:             if (length($ip) == 4) { 
                   12448: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12449:             }
                   12450:         }
                   12451:         if ($ip) {
                   12452: 	    @hosts = get_hosts_from_ip($ip);
                   12453: 	    return $hosts[0];
                   12454:         }
                   12455:         return undef;
1.986     foxr     12456:     }
1.992     raeburn  12457: 
1.1074    raeburn  12458:     sub get_internet_names {
                   12459:         my ($lonid) = @_;
                   12460:         return if ($lonid eq '');
                   12461:         my ($idnref,$cached)=
                   12462:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12463:         if ($cached) {
                   12464:             return $idnref;
                   12465:         }
                   12466:         my $ip = &get_host_ip($lonid);
                   12467:         my @hosts = &get_hosts_from_ip($ip);
                   12468:         my %iphost = &get_iphost();
                   12469:         my (@idns,%seen);
                   12470:         foreach my $id (@hosts) {
                   12471:             my $dom = &host_domain($id);
                   12472:             my $prim_id = &domain($dom,'primary');
                   12473:             my $prim_ip = &get_host_ip($prim_id);
                   12474:             next if ($seen{$prim_ip});
                   12475:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12476:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12477:                     my $intdom = &internet_dom($id);
                   12478:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12479:                         push(@idns,$intdom);
                   12480:                     }
                   12481:                 }
                   12482:             }
                   12483:             $seen{$prim_ip} = 1;
                   12484:         }
1.1219    raeburn  12485:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12486:     }
                   12487: 
1.986     foxr     12488: }
                   12489: 
1.1079    raeburn  12490: sub all_loncaparevs {
1.1249    raeburn  12491:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
1.1079    raeburn  12492: }
                   12493: 
1.1227    raeburn  12494: # ---------------------------------------------------------- Read loncaparev table
                   12495: {
                   12496:     sub load_loncaparevs { 
                   12497:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12498:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12499:                 while (my $configline=<$config>) {
                   12500:                     chomp($configline);
                   12501:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12502:                     $loncaparevs{$hostid}=$loncaparev;
                   12503:                 }
                   12504:                 close($config);
                   12505:             }
                   12506:         }
                   12507:     }
                   12508: }
                   12509: 
                   12510: # ---------------------------------------------------------- Read serverhostID table
                   12511: {
                   12512:     sub load_serverhomeIDs {
                   12513:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12514:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12515:                 while (my $configline=<$config>) {
                   12516:                     chomp($configline);
                   12517:                     my ($name,$id)=split(/:/,$configline);
                   12518:                     $serverhomeIDs{$name}=$id;
                   12519:                 }
                   12520:                 close($config);
                   12521:             }
                   12522:         }
                   12523:     }
                   12524: }
                   12525: 
                   12526: 
1.862     albertel 12527: BEGIN {
                   12528: 
                   12529: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12530:     unless ($readit) {
                   12531: {
                   12532:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12533:     %perlvar = (%perlvar,%{$configvars});
                   12534: }
                   12535: 
                   12536: 
1.1       albertel 12537: # ------------------------------------------------------ Read spare server file
                   12538: {
1.448     albertel 12539:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12540: 
                   12541:     while (my $configline=<$config>) {
                   12542:        chomp($configline);
1.284     matthew  12543:        if ($configline) {
1.784     albertel 12544: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12545: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12546: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12547:        }
                   12548:     }
1.448     albertel 12549:     close($config);
1.1       albertel 12550: }
1.11      www      12551: # ------------------------------------------------------------ Read permissions
                   12552: {
1.448     albertel 12553:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12554: 
                   12555:     while (my $configline=<$config>) {
1.448     albertel 12556: 	chomp($configline);
                   12557: 	if ($configline) {
                   12558: 	    my ($role,$perm)=split(/ /,$configline);
                   12559: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12560: 	}
1.11      www      12561:     }
1.448     albertel 12562:     close($config);
1.11      www      12563: }
                   12564: 
                   12565: # -------------------------------------------- Read plain texts for permissions
                   12566: {
1.448     albertel 12567:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12568: 
                   12569:     while (my $configline=<$config>) {
1.448     albertel 12570: 	chomp($configline);
                   12571: 	if ($configline) {
1.742     raeburn  12572: 	    my ($short,@plain)=split(/:/,$configline);
                   12573:             %{$prp{$short}} = ();
                   12574: 	    if (@plain > 0) {
                   12575:                 $prp{$short}{'std'} = $plain[0];
                   12576:                 for (my $i=1; $i<@plain; $i++) {
                   12577:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12578:                 }
                   12579:             }
1.448     albertel 12580: 	}
1.135     www      12581:     }
1.448     albertel 12582:     close($config);
1.135     www      12583: }
                   12584: 
                   12585: # ---------------------------------------------------------- Read package table
                   12586: {
1.448     albertel 12587:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12588: 
                   12589:     while (my $configline=<$config>) {
1.483     albertel 12590: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12591: 	chomp($configline);
                   12592: 	my ($short,$plain)=split(/:/,$configline);
                   12593: 	my ($pack,$name)=split(/\&/,$short);
                   12594: 	if ($plain ne '') {
                   12595: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12596: 	    $packagetab{$short}=$plain; 
                   12597: 	}
1.11      www      12598:     }
1.448     albertel 12599:     close($config);
1.329     matthew  12600: }
                   12601: 
1.1073    raeburn  12602: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12603: 
                   12604: &load_loncaparevs();
1.1073    raeburn  12605: 
1.1074    raeburn  12606: # ---------------------------------------------------------- Read serverhostID table
                   12607: 
1.1227    raeburn  12608: &load_serverhomeIDs();
                   12609: 
                   12610: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12611: {
                   12612:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12613:     if (-e $file) {
                   12614:         my $parser = HTML::LCParser->new($file);
                   12615:         while (my $token = $parser->get_token()) {
                   12616:             if ($token->[0] eq 'S') {
                   12617:                 my $item = $token->[1];
                   12618:                 my $name = $token->[2]{'name'};
                   12619:                 my $value = $token->[2]{'value'};
                   12620:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12621:                     my $release = $parser->get_text();
                   12622:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12623:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12624:                 }
                   12625:             }
                   12626:         }
                   12627:     }
1.1073    raeburn  12628: }
                   12629: 
1.1138    raeburn  12630: # ---------------------------------------------------------- Read managers table
                   12631: {
                   12632:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12633:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12634:             while (my $configline=<$config>) {
                   12635:                 chomp($configline);
                   12636:                 next if ($configline =~ /^\#/);
                   12637:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12638:                     $managerstab{$configline} = 1;
                   12639:                 }
                   12640:             }
                   12641:             close($config);
                   12642:         }
                   12643:     }
                   12644: }
                   12645: 
1.329     matthew  12646: # ------------- set up temporary directory
                   12647: {
1.1117    foxr     12648:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12649: 
1.11      www      12650: }
                   12651: 
1.794     albertel 12652: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12653: 				'compress_threshold'=> 20_000,
                   12654:  			        });
1.185     www      12655: 
1.281     www      12656: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12657: $dumpcount=0;
1.958     www      12658: $locknum=0;
1.22      www      12659: 
1.163     harris41 12660: &logtouch();
1.672     albertel 12661: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12662: $readit=1;
1.564     albertel 12663:     {
                   12664: 	use integer;
                   12665: 	my $test=(2**32)+1;
1.568     albertel 12666: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12667: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12668:     }
1.195     www      12669: }
1.1       albertel 12670: }
1.179     www      12671: 
1.1       albertel 12672: 1;
1.191     harris41 12673: __END__
                   12674: 
1.243     albertel 12675: =pod
                   12676: 
1.191     harris41 12677: =head1 NAME
                   12678: 
1.243     albertel 12679: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12680: 
                   12681: =head1 SYNOPSIS
                   12682: 
1.243     albertel 12683: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12684: 
                   12685:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12686: 
1.243     albertel 12687: Common parameters:
                   12688: 
                   12689: =over 4
                   12690: 
                   12691: =item *
                   12692: 
                   12693: $uname : an internal username (if $cname expecting a course Id specifically)
                   12694: 
                   12695: =item *
                   12696: 
                   12697: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12698: 
                   12699: =item *
                   12700: 
                   12701: $symb : a resource instance identifier
                   12702: 
                   12703: =item *
                   12704: 
                   12705: $namespace : the name of a .db file that contains the data needed or
                   12706: being set.
                   12707: 
                   12708: =back
                   12709: 
1.394     bowersj2 12710: =head1 OVERVIEW
1.191     harris41 12711: 
1.394     bowersj2 12712: lonnet provides subroutines which interact with the
                   12713: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12714: about classes, users, and resources.
1.243     albertel 12715: 
                   12716: For many of these objects you can also use this to store data about
                   12717: them or modify them in various ways.
1.191     harris41 12718: 
1.394     bowersj2 12719: =head2 Symbs
1.191     harris41 12720: 
1.394     bowersj2 12721: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12722: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12723: map, the resource number of the resource in the map, and the URL of
                   12724: the resource itself. The latter is somewhat redundant, but might help
                   12725: if maps change.
                   12726: 
                   12727: An example is
                   12728: 
                   12729:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12730: 
                   12731: The respective map entry is
                   12732: 
                   12733:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12734:   title="Problem 2">
                   12735:  </resource>
                   12736: 
                   12737: Symbs are used by the random number generator, as well as to store and
                   12738: restore data specific to a certain instance of for example a problem.
                   12739: 
                   12740: =head2 Storing And Retrieving Data
                   12741: 
                   12742: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12743: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12744: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12745: is is the non-critical message twin of cstore. These functions are for
                   12746: handlers to store a perl hash to a user's permanent data space in an
                   12747: easy manner, and to retrieve it again on another call. It is expected
                   12748: that a handler would use this once at the beginning to retrieve data,
                   12749: and then again once at the end to send only the new data back.
                   12750: 
                   12751: The data is stored in the user's data directory on the user's
                   12752: homeserver under the ID of the course.
                   12753: 
                   12754: The hash that is returned by restore will have all of the previous
                   12755: value for all of the elements of the hash.
                   12756: 
                   12757: Example:
                   12758: 
                   12759:  #creating a hash
                   12760:  my %hash;
                   12761:  $hash{'foo'}='bar';
                   12762: 
                   12763:  #storing it
                   12764:  &Apache::lonnet::cstore(\%hash);
                   12765: 
                   12766:  #changing a value
                   12767:  $hash{'foo'}='notbar';
                   12768: 
                   12769:  #adding a new value
                   12770:  $hash{'bar'}='foo';
                   12771:  &Apache::lonnet::cstore(\%hash);
                   12772: 
                   12773:  #retrieving the hash
                   12774:  my %history=&Apache::lonnet::restore();
                   12775: 
                   12776:  #print the hash
                   12777:  foreach my $key (sort(keys(%history))) {
                   12778:    print("\%history{$key} = $history{$key}");
                   12779:  }
                   12780: 
                   12781: Will print out:
1.191     harris41 12782: 
1.394     bowersj2 12783:  %history{1:foo} = bar
                   12784:  %history{1:keys} = foo:timestamp
                   12785:  %history{1:timestamp} = 990455579
                   12786:  %history{2:bar} = foo
                   12787:  %history{2:foo} = notbar
                   12788:  %history{2:keys} = foo:bar:timestamp
                   12789:  %history{2:timestamp} = 990455580
                   12790:  %history{bar} = foo
                   12791:  %history{foo} = notbar
                   12792:  %history{timestamp} = 990455580
                   12793:  %history{version} = 2
                   12794: 
                   12795: Note that the special hash entries C<keys>, C<version> and
                   12796: C<timestamp> were added to the hash. C<version> will be equal to the
                   12797: total number of versions of the data that have been stored. The
                   12798: C<timestamp> attribute will be the UNIX time the hash was
                   12799: stored. C<keys> is available in every historical section to list which
                   12800: keys were added or changed at a specific historical revision of a
                   12801: hash.
                   12802: 
                   12803: B<Warning>: do not store the hash that restore returns directly. This
                   12804: will cause a mess since it will restore the historical keys as if the
                   12805: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12806: 
1.394     bowersj2 12807: Calling convention:
1.191     harris41 12808: 
1.1225    raeburn  12809:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  12810:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 12811: 
1.394     bowersj2 12812: For more detailed information, see lonnet specific documentation.
1.191     harris41 12813: 
1.394     bowersj2 12814: =head1 RETURN MESSAGES
1.191     harris41 12815: 
1.394     bowersj2 12816: =over 4
1.191     harris41 12817: 
1.394     bowersj2 12818: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12819: 
1.394     bowersj2 12820: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12821: when the connection is brought back up
1.191     harris41 12822: 
1.394     bowersj2 12823: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12824: for later delivery
1.191     harris41 12825: 
1.967     bisitz   12826: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12827: 
1.394     bowersj2 12828: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12829: that was requested
1.191     harris41 12830: 
1.243     albertel 12831: =back
1.191     harris41 12832: 
1.243     albertel 12833: =head1 PUBLIC SUBROUTINES
1.191     harris41 12834: 
1.243     albertel 12835: =head2 Session Environment Functions
1.191     harris41 12836: 
1.243     albertel 12837: =over 4
1.191     harris41 12838: 
1.394     bowersj2 12839: =item * 
                   12840: X<appenv()>
1.949     raeburn  12841: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12842: the user envirnoment file, and will be restored for each access this
1.620     albertel 12843: user makes during this session, also modifies the %env for the current
1.949     raeburn  12844: process. Optional rolesarrayref - if defined contains a reference to an array
                   12845: of roles which are exempt from the restriction on modifying user.role entries 
                   12846: in the user's environment.db and in %env.    
1.191     harris41 12847: 
                   12848: =item *
1.394     bowersj2 12849: X<delenv()>
1.987     raeburn  12850: B<delenv($delthis,$regexp)>: removes all items from the session
                   12851: environment file that begin with $delthis. If the 
                   12852: optional second arg - $regexp - is true, $delthis is treated as a 
                   12853: regular expression, otherwise \Q$delthis\E is used. 
                   12854: The values are also deleted from the current processes %env.
1.191     harris41 12855: 
1.795     albertel 12856: =item * get_env_multiple($name) 
                   12857: 
                   12858: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12859: values may be defined and end up as an array ref.
                   12860: 
                   12861: returns an array of values
                   12862: 
1.243     albertel 12863: =back
                   12864: 
                   12865: =head2 User Information
1.191     harris41 12866: 
1.243     albertel 12867: =over 4
1.191     harris41 12868: 
                   12869: =item *
1.394     bowersj2 12870: X<queryauthenticate()>
                   12871: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12872: authentication scheme
                   12873: 
                   12874: =item *
1.394     bowersj2 12875: X<authenticate()>
1.1073    raeburn  12876: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12877: authenticate user from domain's lib servers (first use the current
                   12878: one). C<$upass> should be the users password.
1.1073    raeburn  12879: $checkdefauth is optional (value is 1 if a check should be made to
                   12880:    authenticate user using default authentication method, and allow
                   12881:    account creation if username does not have account in the domain).
                   12882: $clientcancheckhost is optional (value is 1 if checking whether the
                   12883:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12884: 
                   12885: =item *
1.394     bowersj2 12886: X<homeserver()>
                   12887: B<homeserver($uname,$udom)>: find the server which has
                   12888: the user's directory and files (there must be only one), this caches
                   12889: the answer, and also caches if there is a borken connection.
1.191     harris41 12890: 
                   12891: =item *
1.394     bowersj2 12892: X<idget()>
                   12893: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12894: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12895: username, and only 1 username per ID in a specific domain) (returns
                   12896: hash: id=>name,id=>name)
1.191     harris41 12897: 
                   12898: =item *
1.394     bowersj2 12899: X<idrget()>
                   12900: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12901: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12902: 
                   12903: =item *
1.394     bowersj2 12904: X<idput()>
                   12905: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12906: 
                   12907: =item *
1.394     bowersj2 12908: X<rolesinit()>
1.1169    droeschl 12909: B<rolesinit($udom,$username)>: get user privileges.
                   12910: returns user role, first access and timer interval hashes
1.243     albertel 12911: 
                   12912: =item *
1.1171    droeschl 12913: X<privileged()>
                   12914: B<privileged($username,$domain)>: returns a true if user has a
                   12915: privileged and active role (i.e. su or dc), false otherwise.
                   12916: 
                   12917: =item *
1.551     albertel 12918: X<getsection()>
                   12919: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12920: course $cname, return section name/number or '' for "not in course"
                   12921: and '-1' for "no section"
                   12922: 
                   12923: =item *
1.394     bowersj2 12924: X<userenvironment()>
                   12925: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12926: passed in @what from the requested user's environment, returns a hash
                   12927: 
1.858     raeburn  12928: =item * 
                   12929: X<userlog_query()>
1.859     albertel 12930: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12931: activity.log file. %filters defines filters applied when parsing the
                   12932: log file. These can be start or end timestamps, or the type of action
                   12933: - log to look for Login or Logout events, check for Checkin or
                   12934: Checkout, role for role selection. The response is in the form
                   12935: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12936: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12937: 
1.243     albertel 12938: =back
                   12939: 
                   12940: =head2 User Roles
                   12941: 
                   12942: =over 4
                   12943: 
                   12944: =item *
                   12945: 
1.810     raeburn  12946: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12947:  F: full access
                   12948:  U,I,K: authentication modes (cxx only)
                   12949:  '': forbidden
                   12950:  1: user needs to choose course
                   12951:  2: browse allowed
1.766     albertel 12952:  A: passphrase authentication needed
1.243     albertel 12953: 
                   12954: =item *
                   12955: 
1.1192    raeburn  12956: constructaccess($url,$setpriv) : check for access to construction space URL
                   12957: 
                   12958: See if the owner domain and name in the URL match those in the
                   12959: expected environment.  If so, return three element list
                   12960: ($ownername,$ownerdomain,$ownerhome).
                   12961: 
                   12962: Otherwise return the null string.
                   12963: 
                   12964: If second argument 'setpriv' is true, it assigns the privileges,
                   12965: and returns the same three element list, unless the owner has
                   12966: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12967: in which case the null string is returned.
                   12968: 
                   12969: =item *
                   12970: 
1.243     albertel 12971: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12972: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12973: and course level
                   12974: 
                   12975: =item *
                   12976: 
1.988     raeburn  12977: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12978: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12979: $type is Course (default) or Community.
1.988     raeburn  12980: If $forcedefault evaluates to true, text returned will be default 
                   12981: text for $type. Otherwise, if this is a course, the text returned 
                   12982: will be a custom name for the role (if defined in the course's 
                   12983: environment).  If no custom name is defined the default is returned.
                   12984:    
1.832     raeburn  12985: =item *
                   12986: 
1.1219    raeburn  12987: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12988: All arguments are optional. Returns a hash of a roles, either for
                   12989: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12990: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12991: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12992: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12993: For each key, value is set to colon-separated start and end times for
                   12994: the role.  If no username and domain are specified, will default to
1.934     raeburn  12995: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12996: of role statuses (active, future or previous), roles 
                   12997: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12998: to restrict the list of roles reported. If no array ref is 
                   12999: provided for types, will default to return only active roles.
1.834     albertel 13000: 
1.1195    raeburn  13001: =item *
                   13002: 
                   13003: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13004: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13005: 
                   13006: Additional optional arguments are: $type (if role checking is to be restricted 
                   13007: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13008: available roles) or future (roles available in the future), and
                   13009: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13010: have active Domain Coordinator role in course's domain or in additional
                   13011: domains (specified in 'Domains to check for privileged users' in course
                   13012: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13013: 
                   13014: =item *
                   13015: 
                   13016: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13017: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13018: $possdomains and $possroles are optional array refs -- to domains to check and
                   13019: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13020: users' roles.db to check for a dc or su role in any domain. This can be
                   13021: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13022: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13023: this then allows &privileged_by_domain() to be used, which caches the identity
                   13024: of privileged users, eliminating the need for repeated calls to &dump().
                   13025: 
                   13026: =item *
                   13027: 
                   13028: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13029: where the outer hash keys are domains specified in the $possdomains array ref,
                   13030: next inner hash keys are privileged roles specified in the $roles array ref,
                   13031: and the innermost hash contains key = value pairs for username:domain = end:start
                   13032: for active or future "privileged" users with that role in that domain. To avoid
                   13033: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13034: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13035: 
1.243     albertel 13036: =back
                   13037: 
                   13038: =head2 User Modification
                   13039: 
                   13040: =over 4
                   13041: 
                   13042: =item *
                   13043: 
1.957     raeburn  13044: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13045: user for the level given by URL.  Optional start and end dates (leave empty
                   13046: string or zero for "no date")
1.191     harris41 13047: 
                   13048: =item *
                   13049: 
1.243     albertel 13050: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13051: change a users, password, possible return values are: ok,
                   13052: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13053: refused
1.191     harris41 13054: 
                   13055: =item *
                   13056: 
1.243     albertel 13057: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13058: 
                   13059: =item *
                   13060: 
1.1058    raeburn  13061: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13062:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13063: 
                   13064: will update user information (firstname,middlename,lastname,generation,
                   13065: permanentemail), and if forceid is true, student/employee ID also.
                   13066: A user's institutional affiliation(s) can also be updated.
                   13067: User information fields will not be overwritten with empty entries 
                   13068: unless the field is included in the $candelete array reference.
                   13069: This array is included when a single user is modified via "Manage Users",
                   13070: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13071: 
                   13072: =item *
                   13073: 
1.286     matthew  13074: modifystudent
                   13075: 
1.957     raeburn  13076: modify a student's enrollment and identification information.
1.1235    raeburn  13077: The course id is resolved based on the current user's environment.  
                   13078: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13079: associated with a course.
                   13080: 
1.297     matthew  13081: This call is essentially a wrapper for lonnet::modifyuser and
                   13082: lonnet::modify_student_enrollment
1.286     matthew  13083: 
                   13084: Inputs: 
                   13085: 
                   13086: =over 4
                   13087: 
1.957     raeburn  13088: =item B<$udom> Student's loncapa domain
1.286     matthew  13089: 
1.957     raeburn  13090: =item B<$uname> Student's loncapa login name
1.286     matthew  13091: 
1.964     bisitz   13092: =item B<$uid> Student/Employee ID
1.286     matthew  13093: 
1.957     raeburn  13094: =item B<$umode> Student's authentication mode
1.286     matthew  13095: 
1.957     raeburn  13096: =item B<$upass> Student's password
1.286     matthew  13097: 
1.957     raeburn  13098: =item B<$first> Student's first name
1.286     matthew  13099: 
1.957     raeburn  13100: =item B<$middle> Student's middle name
1.286     matthew  13101: 
1.957     raeburn  13102: =item B<$last> Student's last name
1.286     matthew  13103: 
1.957     raeburn  13104: =item B<$gene> Student's generation
1.286     matthew  13105: 
1.957     raeburn  13106: =item B<$usec> Student's section in course
1.286     matthew  13107: 
                   13108: =item B<$end> Unix time of the roles expiration
                   13109: 
                   13110: =item B<$start> Unix time of the roles start date
                   13111: 
                   13112: =item B<$forceid> If defined, allow $uid to be changed
                   13113: 
                   13114: =item B<$desiredhome> server to use as home server for student
                   13115: 
1.957     raeburn  13116: =item B<$email> Student's permanent e-mail address
                   13117: 
                   13118: =item B<$type> Type of enrollment (auto or manual)
                   13119: 
1.963     raeburn  13120: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13121: 
                   13122: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13123: 
1.963     raeburn  13124: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13125: 
1.963     raeburn  13126: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13127: 
1.1216    raeburn  13128: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13129: 
                   13130: =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  13131: 
1.286     matthew  13132: =back
1.297     matthew  13133: 
                   13134: =item *
                   13135: 
                   13136: modify_student_enrollment
                   13137: 
1.1235    raeburn  13138: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13139: 'role.request.course' must be defined for this function to proceed.
                   13140: 
                   13141: Inputs:
                   13142: 
                   13143: =over 4
                   13144: 
1.1235    raeburn  13145: =item $udom, student's domain
1.297     matthew  13146: 
1.1235    raeburn  13147: =item $uname, student's name
1.297     matthew  13148: 
1.1235    raeburn  13149: =item $uid, student's user id
1.297     matthew  13150: 
1.1235    raeburn  13151: =item $first, student's first name
1.297     matthew  13152: 
                   13153: =item $middle
                   13154: 
                   13155: =item $last
                   13156: 
                   13157: =item $gene
                   13158: 
                   13159: =item $usec
                   13160: 
                   13161: =item $end
                   13162: 
                   13163: =item $start
                   13164: 
1.957     raeburn  13165: =item $type
                   13166: 
                   13167: =item $locktype
                   13168: 
                   13169: =item $cid
                   13170: 
                   13171: =item $selfenroll
                   13172: 
                   13173: =item $context
                   13174: 
1.1216    raeburn  13175: =item $credits, number of credits student will earn from this class
                   13176: 
1.297     matthew  13177: =back
                   13178: 
1.191     harris41 13179: 
                   13180: =item *
                   13181: 
1.243     albertel 13182: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13183: custom role; give a custom role to a user for the level given by URL.  Specify
                   13184: name and domain of role author, and role name
1.191     harris41 13185: 
                   13186: =item *
                   13187: 
1.243     albertel 13188: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13189: 
                   13190: =item *
                   13191: 
1.243     albertel 13192: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13193: 
                   13194: =back
                   13195: 
                   13196: =head2 Course Infomation
                   13197: 
                   13198: =over 4
1.191     harris41 13199: 
                   13200: =item *
                   13201: 
1.1118    foxr     13202: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13203: specified course id, including all environment settings for the
                   13204: course, the description of the course will be in the hash under the
                   13205: key 'description'
1.191     harris41 13206: 
1.1118    foxr     13207: $options is an optional parameter that if supplied is a hash reference that controls
                   13208: what how this function works.  It has the following key/values:
                   13209: 
                   13210: =over 4
                   13211: 
                   13212: =item freshen_cache
                   13213: 
                   13214: If defined, and the environment cache for the course is valid, it is 
                   13215: returned in the returned hash.
                   13216: 
                   13217: =item one_time
                   13218: 
                   13219: If defined, the last cache time is set to _now_
                   13220: 
                   13221: =item user
                   13222: 
                   13223: If defined, the supplied username is used instead of the current user.
                   13224: 
                   13225: 
                   13226: =back
                   13227: 
1.191     harris41 13228: =item *
                   13229: 
1.624     albertel 13230: resdata($name,$domain,$type,@which) : request for current parameter
                   13231: setting for a specific $type, where $type is either 'course' or 'user',
                   13232: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13233: answers for 10 minutes.
1.243     albertel 13234: 
1.877     foxr     13235: =item *
                   13236: 
                   13237: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13238: data base, returning a hash that is keyed by the resource name and has
                   13239: values that are the resource value.  I believe that the timestamps and
                   13240: versions are also returned.
                   13241: 
1.1236    raeburn  13242: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13243: supplemental content area. This routine caches the number of files for 
                   13244: 10 minutes.
                   13245: 
1.243     albertel 13246: =back
                   13247: 
                   13248: =head2 Course Modification
                   13249: 
                   13250: =over 4
1.191     harris41 13251: 
                   13252: =item *
                   13253: 
1.243     albertel 13254: writecoursepref($courseid,%prefs) : write preferences (environment
                   13255: database) for a course
1.191     harris41 13256: 
                   13257: =item *
                   13258: 
1.1011    raeburn  13259: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13260: 
                   13261: =item *
                   13262: 
1.1038    raeburn  13263: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13264: 
1.1167    droeschl 13265: =item *
                   13266: 
                   13267: is_course($courseid), is_course($cdom, $cnum)
                   13268: 
                   13269: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13270: two component version $cdom, $cnum. It checks if the specified course exists.
                   13271: 
                   13272: Returns:
                   13273:     undef if the course doesn't exist, otherwise
                   13274:     in scalar context the combined courseid.
                   13275:     in list context the two components of the course identifier, domain and 
                   13276:     courseid.    
                   13277: 
1.243     albertel 13278: =back
                   13279: 
                   13280: =head2 Resource Subroutines
                   13281: 
                   13282: =over 4
1.191     harris41 13283: 
                   13284: =item *
                   13285: 
1.243     albertel 13286: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13287: 
                   13288: =item *
                   13289: 
1.243     albertel 13290: repcopy($filename) : subscribes to the requested file, and attempts to
                   13291: replicate from the owning library server, Might return
1.607     raeburn  13292: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13293: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13294: resource. Expects the local filesystem pathname
                   13295: (/home/httpd/html/res/....)
                   13296: 
                   13297: =back
                   13298: 
                   13299: =head2 Resource Information
                   13300: 
                   13301: =over 4
1.191     harris41 13302: 
                   13303: =item *
                   13304: 
1.1228    raeburn  13305: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13306: and returns the value of a variety of different possible values,
                   13307: $varname should be a request string, and the other parameters can be
                   13308: used to specify who and what one is asking about. Ordinarily, $cid 
                   13309: does not need to be specified, as it is retrived from 
                   13310: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13311: within lonuserstate::loadmap() when initializing a course, before
                   13312: $env{'request.course.id'} has been set, so it needs to be provided
                   13313: in that one case.
1.243     albertel 13314: 
                   13315: Possible values for $varname are environment.lastname (or other item
                   13316: from the envirnment hash), user.name (or someother aspect about the
                   13317: user), resource.0.maxtries (or some other part and parameter of a
                   13318: resource)
1.204     albertel 13319: 
                   13320: =item *
                   13321: 
1.243     albertel 13322: directcondval($number) : get current value of a condition; reads from a state
                   13323: string
1.204     albertel 13324: 
                   13325: =item *
                   13326: 
1.243     albertel 13327: condval($condidx) : value of condition index based on state
1.204     albertel 13328: 
                   13329: =item *
                   13330: 
1.243     albertel 13331: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13332: resource's metadata, $what should be either a specific key, or either
                   13333: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13334: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13335: 
                   13336: this function automatically caches all requests
1.191     harris41 13337: 
                   13338: =item *
                   13339: 
1.243     albertel 13340: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13341: network of library servers; returns file handle of where SQL and regex results
                   13342: will be stored for query
1.191     harris41 13343: 
                   13344: =item *
                   13345: 
1.243     albertel 13346: symbread($filename) : return symbolic list entry (filename argument optional);
                   13347: returns the data handle
1.191     harris41 13348: 
                   13349: =item *
                   13350: 
1.1190    raeburn  13351: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13352: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13353: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13354: on failure, user must be in a course, as it assumes the existence of
                   13355: the course initial hash, and uses $env('request.course.id'}.  The third
                   13356: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13357: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13358: encrypted; otherwise it will be null.  
1.191     harris41 13359: 
                   13360: =item *
                   13361: 
1.243     albertel 13362: symbclean($symb) : removes versions numbers from a symb, returns the
                   13363: cleaned symb
1.191     harris41 13364: 
                   13365: =item *
                   13366: 
1.243     albertel 13367: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13368: course map, user must be in a course for it to work.
1.191     harris41 13369: 
                   13370: =item *
                   13371: 
1.243     albertel 13372: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13373: 
                   13374: =item *
                   13375: 
1.243     albertel 13376: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13377: a random seed, all arguments are optional, if they aren't sent it uses the
                   13378: environment to derive them. Note: if symb isn't sent and it can't get one
                   13379: from &symbread it will use the current time as its return value
1.191     harris41 13380: 
                   13381: =item *
                   13382: 
1.243     albertel 13383: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13384: unfakeable, receipt
1.191     harris41 13385: 
                   13386: =item *
                   13387: 
1.620     albertel 13388: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13389: 
                   13390: =item *
                   13391: 
1.243     albertel 13392: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13393: 
                   13394: =item *
                   13395: 
1.243     albertel 13396: 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 13397: 
                   13398: =item *
                   13399: 
1.243     albertel 13400: 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 13401: 
                   13402: =item *
                   13403: 
1.243     albertel 13404: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13405: 
                   13406: =item *
                   13407: 
1.243     albertel 13408: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13409: forcing spreadsheet to reevaluate the resource scores next time.
                   13410: 
1.1195    raeburn  13411: =item * 
                   13412: 
1.1196    raeburn  13413: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13414: when viewing in course context.
1.1195    raeburn  13415: 
1.1196    raeburn  13416:  input: six args -- filename (decluttered), course number, course domain,
                   13417:                     url, symb (if registered) and group (if this is a 
                   13418:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13419: 
1.1196    raeburn  13420:  output: array of five scalars --
1.1195    raeburn  13421:          $cfile -- url for file editing if editable on current server
                   13422:          $home -- homeserver of resource (i.e., for author if published,
                   13423:                                           or course if uploaded.).
                   13424:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13425:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13426:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13427: 
                   13428: =item *
                   13429: 
                   13430: is_course_upload($file,$cnum,$cdom)
                   13431: 
                   13432: Used in course context to determine if current file was uploaded to 
                   13433: the course (i.e., would be found in /userfiles/docs on the course's 
                   13434: homeserver.
                   13435: 
                   13436:   input: 3 args -- filename (decluttered), course number and course domain.
                   13437:   output: boolean -- 1 if file was uploaded.
                   13438: 
1.243     albertel 13439: =back
                   13440: 
                   13441: =head2 Storing/Retreiving Data
                   13442: 
                   13443: =over 4
1.191     harris41 13444: 
                   13445: =item *
                   13446: 
1.1269    raeburn  13447: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   13448: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13449: the remaining args aren't required and if they aren't passed or are '' they will
                   13450: be derived from the env (with the exception of $laststore, which is an 
                   13451: optional arg used when a user's submission is stored in grading).
                   13452: $laststore is $version=$timestamp, where $version is the most recent version
                   13453: number retrieved for the corresponding $symb in the $namespace db file, and
                   13454: $timestamp is the timestamp for that transaction (UNIX time).
                   13455: $laststore is currently only passed when cstore() is called by 
                   13456: structuretags::finalize_storage().
1.191     harris41 13457: 
                   13458: =item *
                   13459: 
1.1269    raeburn  13460: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   13461: but uses critical subroutine
1.191     harris41 13462: 
                   13463: =item *
                   13464: 
1.243     albertel 13465: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13466: all args are optional
1.191     harris41 13467: 
                   13468: =item *
                   13469: 
1.717     albertel 13470: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13471: dumps the complete (or key matching regexp) namespace into a hash
                   13472: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13473: normally &store()ed into
                   13474: 
                   13475: $range should be either an integer '100' (give me the first 100
                   13476:                                            matching records)
                   13477:               or be  two integers sperated by a - with no spaces
                   13478:                  '30-50' (give me the 30th through the 50th matching
                   13479:                           records)
                   13480: 
                   13481: 
                   13482: =item *
                   13483: 
1.1269    raeburn  13484: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13485: replaces a &store() version of data with a replacement set of data
                   13486: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  13487: reference. If $tolog is true, the transaction is logged in the courselog
                   13488: with an action=PUTSTORE.
1.717     albertel 13489: 
                   13490: =item *
                   13491: 
1.243     albertel 13492: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13493: works very similar to store/cstore, but all data is stored in a
                   13494: temporary location and can be reset using tmpreset, $storehash should
                   13495: be a hash reference, returns nothing on success
1.191     harris41 13496: 
                   13497: =item *
                   13498: 
1.243     albertel 13499: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13500: similar to restore, but all data is stored in a temporary location and
                   13501: can be reset using tmpreset. Returns a hash of values on success,
                   13502: error string otherwise.
1.191     harris41 13503: 
                   13504: =item *
                   13505: 
1.243     albertel 13506: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13507: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13508: 
                   13509: =item *
                   13510: 
1.243     albertel 13511: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13512: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13513: 
                   13514: =item *
                   13515: 
1.243     albertel 13516: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13517: namesp ($udom and $uname are optional)
1.191     harris41 13518: 
                   13519: =item *
                   13520: 
1.702     albertel 13521: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13522: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13523: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13524: 
1.702     albertel 13525: $range should be either an integer '100' (give me the first 100
                   13526:                                            matching records)
                   13527:               or be  two integers sperated by a - with no spaces
                   13528:                  '30-50' (give me the 30th through the 50th matching
                   13529:                           records)
1.449     matthew  13530: =item *
                   13531: 
                   13532: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13533: $store can be a scalar, an array reference, or if the amount to be 
                   13534: incremented is > 1, a hash reference.
                   13535: 
                   13536: ($udom and $uname are optional)
1.191     harris41 13537: 
                   13538: =item *
                   13539: 
1.243     albertel 13540: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13541: ($udom and $uname are optional)
1.191     harris41 13542: 
                   13543: =item *
                   13544: 
1.243     albertel 13545: cput($namespace,$storehash,$udom,$uname) : critical put
                   13546: ($udom and $uname are optional)
1.191     harris41 13547: 
                   13548: =item *
                   13549: 
1.748     albertel 13550: newput($namespace,$storehash,$udom,$uname) :
                   13551: 
                   13552: Attempts to store the items in the $storehash, but only if they don't
                   13553: currently exist, if this succeeds you can be certain that you have 
                   13554: successfully created a new key value pair in the $namespace db.
                   13555: 
                   13556: 
                   13557: Args:
                   13558:  $namespace: name of database to store values to
                   13559:  $storehash: hashref to store to the db
                   13560:  $udom: (optional) domain of user containing the db
                   13561:  $uname: (optional) name of user caontaining the db
                   13562: 
                   13563: Returns:
                   13564:  'ok' -> succeeded in storing all keys of $storehash
                   13565:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13566:                         least <key> already existed in the db (other
                   13567:                         requested keys may also already exist)
1.967     bisitz   13568:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13569:  'con_lost' -> unable to contact request server
                   13570:  'refused' -> action was not allowed by remote machine
                   13571: 
                   13572: 
                   13573: =item *
                   13574: 
1.243     albertel 13575: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13576: reference filled in from namesp (encrypts the return communication)
                   13577: ($udom and $uname are optional)
1.191     harris41 13578: 
                   13579: =item *
                   13580: 
1.243     albertel 13581: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13582: critical subroutine
                   13583: 
1.806     raeburn  13584: =item *
                   13585: 
1.860     raeburn  13586: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13587: array reference filled in from namespace found in domain level on either
                   13588: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13589: 
                   13590: =item *
                   13591: 
1.860     raeburn  13592: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13593: domain level either on specified domain server ($uhome) or primary domain 
                   13594: server ($udom and $uhome are optional)
1.806     raeburn  13595: 
1.943     raeburn  13596: =item * 
                   13597: 
1.1240    raeburn  13598: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13599: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13600: the target domain.
                   13601: 
                   13602: May also include additional key => value pairs for the following groups:
                   13603: 
                   13604: =over
                   13605: 
                   13606: =item
                   13607: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13608: 
                   13609: =over
                   13610: 
                   13611: =item defaultquota, authorquota
                   13612: 
                   13613: =back
                   13614: 
                   13615: =item
                   13616: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13617: portfolio for users).
                   13618: 
                   13619: =over
                   13620: 
                   13621: =item
                   13622: aboutme, blog, webdav, portfolio
                   13623: 
                   13624: =back
                   13625: 
                   13626: =item
                   13627: requestcourses: ability to request courses, and how requests are processed.
                   13628: 
                   13629: =over
                   13630: 
                   13631: =item
1.1246    raeburn  13632: official, unofficial, community, textbook
1.1240    raeburn  13633: 
                   13634: =back
                   13635: 
                   13636: =item
                   13637: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13638: 
                   13639: =over
                   13640: 
                   13641: =item
1.1256    raeburn  13642: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  13643: 
                   13644: =back
                   13645: 
                   13646: =item
                   13647: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13648: for course's uploaded content.
                   13649: 
                   13650: =over
                   13651: 
                   13652: =item
1.1246    raeburn  13653: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   13654: communityquota, textbookquota
1.1240    raeburn  13655: 
                   13656: =back
                   13657: 
                   13658: =item
                   13659: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13660: on your servers.
                   13661: 
                   13662: =over
                   13663: 
                   13664: =item 
                   13665: remotesessions, hostedsessions
                   13666: 
                   13667: =back
                   13668: 
                   13669: =back
                   13670: 
                   13671: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13672: utility to create a configuration.db file on a domain's primary library server 
                   13673: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13674: -- corresponding values are authentication type (internal, krb4, krb5,
                   13675: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13676: will be available. Values are retrieved from cache (if current), unless the
                   13677: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13678: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13679: 
                   13680: Typical usage:
1.943     raeburn  13681: 
1.1240    raeburn  13682: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13683: 
1.243     albertel 13684: =back
                   13685: 
                   13686: =head2 Network Status Functions
                   13687: 
                   13688: =over 4
1.191     harris41 13689: 
                   13690: =item *
                   13691: 
1.1137    raeburn  13692: dirlist() : return directory list based on URI (first arg).
                   13693: 
                   13694: Inputs: 1 required, 5 optional.
                   13695: 
                   13696: =over
                   13697: 
                   13698: =item 
                   13699: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13700: 
                   13701: =item
                   13702: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13703: 
                   13704: =item
                   13705: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13706: 
                   13707: =item
                   13708: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13709: 
                   13710: =item
                   13711: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13712: 
                   13713: =item 
                   13714: $alternateRoot - path to prepend in place of path from $uri.
                   13715: 
                   13716: =back
                   13717: 
                   13718: Returns: Array of up to two items.
                   13719: 
                   13720: =over
                   13721: 
                   13722: a reference to an array of files/subdirectories
                   13723: 
                   13724: =over
                   13725: 
                   13726: Each element in the array of files/subdirectories is a & separated list of
                   13727: item name and the result of running stat on the item.  If dirlist was requested
                   13728: for a file instead of a directory, the item name will be ''. For a directory 
                   13729: listing, if the item is a metadata file, the element will end &N&M 
                   13730: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13731: default copyright set (1).  
                   13732: 
                   13733: =back
                   13734: 
                   13735: a scalar containing error condition (if encountered).
                   13736: 
                   13737: =over
                   13738: 
                   13739: =item 
                   13740: no_host (no homeserver identified for $username:$domain).
                   13741: 
                   13742: =item 
                   13743: no_such_host (server contacted for listing not identified as valid host).
                   13744: 
                   13745: =item 
                   13746: con_lost (connection to remote server failed).
                   13747: 
                   13748: =item 
                   13749: refused (invalid $username:$domain received on lond side).
                   13750: 
                   13751: =item 
                   13752: no_such_dir (directory at specified path on lond side does not exist). 
                   13753: 
                   13754: =item 
                   13755: empty (directory at specified path on lond side is empty).
                   13756: 
                   13757: =over
                   13758: 
                   13759: This is currently not encountered because the &ls3, &ls2, 
                   13760: &ls (_handler) routines on the lond side do not filter out
                   13761: . and .. from a directory listing. 
                   13762: 
                   13763: =back
                   13764: 
                   13765: =back
                   13766: 
                   13767: =back
1.191     harris41 13768: 
                   13769: =item *
                   13770: 
1.243     albertel 13771: spareserver() : find server with least workload from spare.tab
                   13772: 
1.986     foxr     13773: 
                   13774: =item *
                   13775: 
                   13776: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13777: if there is no corresponding loncapa host.
                   13778: 
1.243     albertel 13779: =back
                   13780: 
1.986     foxr     13781: 
1.243     albertel 13782: =head2 Apache Request
                   13783: 
                   13784: =over 4
1.191     harris41 13785: 
                   13786: =item *
                   13787: 
1.243     albertel 13788: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13789: localhost, posts hash
                   13790: 
                   13791: =back
                   13792: 
                   13793: =head2 Data to String to Data
                   13794: 
                   13795: =over 4
1.191     harris41 13796: 
                   13797: =item *
                   13798: 
1.243     albertel 13799: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13800: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13801: 
                   13802: =item *
                   13803: 
1.243     albertel 13804: hashref2str($hashref) : convert a hashref into a string complete with
                   13805: escaping and '=' and '&' separators, supports elements that are
                   13806: arrayrefs and hashrefs
1.191     harris41 13807: 
                   13808: =item *
                   13809: 
1.243     albertel 13810: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13811: with escaping and '&' separators, supports elements that are arrayrefs
                   13812: and hashrefs
1.191     harris41 13813: 
                   13814: =item *
                   13815: 
1.243     albertel 13816: str2hash($string) : convert string to hash using unescaping and
                   13817: splitting on '=' and '&', supports elements that are arrayrefs and
                   13818: hashrefs
1.191     harris41 13819: 
                   13820: =item *
                   13821: 
1.243     albertel 13822: str2array($string) : convert string to hash using unescaping and
                   13823: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13824: 
                   13825: =back
                   13826: 
                   13827: =head2 Logging Routines
                   13828: 
                   13829: 
                   13830: These routines allow one to make log messages in the lonnet.log and
                   13831: lonnet.perm logfiles.
1.191     harris41 13832: 
1.1119    foxr     13833: =over 4
                   13834: 
1.191     harris41 13835: =item *
                   13836: 
1.243     albertel 13837: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13838: 
                   13839: =item *
                   13840: 
1.243     albertel 13841: logthis() : append message to the normal lonnet.log file, it gets
                   13842: preiodically rolled over and deleted.
1.191     harris41 13843: 
                   13844: =item *
                   13845: 
1.243     albertel 13846: logperm() : append a permanent message to lonnet.perm.log, this log
                   13847: file never gets deleted by any automated portion of the system, only
                   13848: messages of critical importance should go in here.
                   13849: 
1.1119    foxr     13850: 
1.243     albertel 13851: =back
                   13852: 
                   13853: =head2 General File Helper Routines
                   13854: 
                   13855: =over 4
1.191     harris41 13856: 
                   13857: =item *
                   13858: 
1.481     raeburn  13859: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13860: (a) files in /uploaded
                   13861:   (i) If a local copy of the file exists - 
                   13862:       compares modification date of local copy with last-modified date for 
                   13863:       definitive version stored on home server for course. If local copy is 
                   13864:       stale, requests a new version from the home server and stores it. 
                   13865:       If the original has been removed from the home server, then local copy 
                   13866:       is unlinked.
                   13867:   (ii) If local copy does not exist -
                   13868:       requests the file from the home server and stores it. 
                   13869:   
                   13870:   If $caller is 'uploadrep':  
                   13871:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13872:     for request for files originally uploaded via DOCS. 
                   13873:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13874:   
                   13875:   Otherwise:
                   13876:      This indicates a call from the content generation phase of the request.
                   13877:      -  returns the entire contents of the file or -1.
                   13878:      
                   13879: (b) files in /res
                   13880:    - returns the entire contents of a file or -1; 
                   13881:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13882: 
1.712     albertel 13883: 
                   13884: =item *
                   13885: 
                   13886: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13887:                   reference
                   13888: 
                   13889: returns either a stat() list of data about the file or an empty list
                   13890: if the file doesn't exist or couldn't find out about it (connection
                   13891: problems or user unknown)
                   13892: 
1.191     harris41 13893: =item *
                   13894: 
1.243     albertel 13895: filelocation($dir,$file) : returns file system location of a file
                   13896: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13897: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13898: and a file of ../bob will become /a/bob)
1.191     harris41 13899: 
                   13900: =item *
                   13901: 
                   13902: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13903: filelocation except for hrefs
                   13904: 
                   13905: =item *
                   13906: 
1.1261    raeburn  13907: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   13908: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 13909: 
1.243     albertel 13910: =back
                   13911: 
1.608     albertel 13912: =head2 Usererfile file routines (/uploaded*)
                   13913: 
                   13914: =over 4
                   13915: 
                   13916: =item *
                   13917: 
                   13918: userfileupload(): main rotine for putting a file in a user or course's
                   13919:                   filespace, arguments are,
                   13920: 
1.620     albertel 13921:  formname - required - this is the name of the element in $env where the
1.608     albertel 13922:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13923:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13924:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13925:  context - if coursedoc, store the file in the course of the active role
                   13926:              of the current user; 
                   13927:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13928:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13929:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13930:          if undefined, it will be placed in "unknown"
                   13931: 
                   13932:  (This routine calls clean_filename() to remove any dangerous
                   13933:  characters from the filename, and then calls finuserfileupload() to
                   13934:  complete the transaction)
                   13935: 
                   13936:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13937:  and /adm/notfound.html if unsuccessful
                   13938: 
                   13939: =item *
                   13940: 
                   13941: clean_filename(): routine for cleaing a filename up for storage in
                   13942:                  userfile space, argument is:
                   13943: 
                   13944:  filename - proposed filename
                   13945: 
                   13946: returns: the new clean filename
                   13947: 
                   13948: =item *
                   13949: 
1.1090    raeburn  13950: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13951: userspace, probably shouldn't be called directly
                   13952: 
                   13953:   docuname: username or courseid of destination for the file
                   13954:   docudom: domain of user/course of destination for the file
                   13955:   formname: same as for userfileupload()
1.1090    raeburn  13956:   fname: filename (including subdirectories) for the file
                   13957:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13958:   allfiles: reference to hash used to store objects found by parser
                   13959:   codebase: reference to hash used for codebases of java objects found by parser
                   13960:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13961:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13962:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13963:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13964:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13965:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13966:   mimetype: reference to scalar to accommodate mime type determined
                   13967:             from File::MMagic if $parser = parse.
1.608     albertel 13968: 
                   13969:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13970:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13971:  was 'overwrite').
                   13972:  
1.608     albertel 13973: 
                   13974: =item *
                   13975: 
                   13976: renameuserfile(): renames an existing userfile to a new name
                   13977: 
                   13978:   Args:
                   13979:    docuname: username or courseid of destination for the file
                   13980:    docudom: domain of user/course of destination for the file
                   13981:    old: current file name (including any subdirs under userfiles)
                   13982:    new: desired file name (including any subdirs under userfiles)
                   13983: 
                   13984: =item *
                   13985: 
                   13986: mkdiruserfile(): creates a directory is a userfiles dir
                   13987: 
                   13988:   Args:
                   13989:    docuname: username or courseid of destination for the file
                   13990:    docudom: domain of user/course of destination for the file
                   13991:    dir: dir to create (including any subdirs under userfiles)
                   13992: 
                   13993: =item *
                   13994: 
                   13995: removeuserfile(): removes a file that exists in userfiles
                   13996: 
                   13997:   Args:
                   13998:    docuname: username or courseid of destination for the file
                   13999:    docudom: domain of user/course of destination for the file
                   14000:    fname: filname to delete (including any subdirs under userfiles)
                   14001: 
                   14002: =item *
                   14003: 
                   14004: removeuploadedurl(): convience function for removeuserfile()
                   14005: 
                   14006:   Args:
                   14007:    url:  a full /uploaded/... url to delete
                   14008: 
1.747     albertel 14009: =item * 
                   14010: 
                   14011: get_portfile_permissions():
                   14012:   Args:
                   14013:     domain: domain of user or course contain the portfolio files
                   14014:     user: name of user or num of course contain the portfolio files
                   14015:   Returns:
                   14016:     hashref of a dump of the proper file_permissions.db
                   14017:    
                   14018: 
                   14019: =item * 
                   14020: 
                   14021: get_access_controls():
                   14022: 
                   14023: Args:
                   14024:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14025:   group: (optional) the group you want the files associated with
                   14026:   file: (optional) the file you want access info on
                   14027: 
                   14028: Returns:
1.749     raeburn  14029:     a hash (keys are file names) of hashes containing
                   14030:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14031:         values are XML containing access control settings (see below) 
1.747     albertel 14032: 
                   14033: Internal notes:
                   14034: 
1.749     raeburn  14035:  access controls are stored in file_permissions.db as key=value pairs.
                   14036:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14037:         where scope -> public,guest,course,group,domains or users.
                   14038:               end -> UNIX time for end of access (0 -> no end date)
                   14039:               start -> UNIX time for start of access
                   14040: 
                   14041:     value -> XML description of access control
                   14042:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14043:             <start></start>
                   14044:             <end></end>
                   14045: 
                   14046:             <password></password>  for scope type = guest
                   14047: 
                   14048:             <domain></domain>     for scope type = course or group
                   14049:             <number></number>
                   14050:             <roles id="">
                   14051:              <role></role>
                   14052:              <access></access>
                   14053:              <section></section>
                   14054:              <group></group>
                   14055:             </roles>
                   14056: 
                   14057:             <dom></dom>         for scope type = domains
                   14058: 
                   14059:             <users>             for scope type = users
                   14060:              <user>
                   14061:               <uname></uname>
                   14062:               <udom></udom>
                   14063:              </user>
                   14064:             </users>
                   14065:            </scope> 
                   14066:               
                   14067:  Access data is also aggregated for each file in an additional key=value pair:
                   14068:  key -> path to file/file_name\0accesscontrol 
                   14069:  value -> reference to hash
                   14070:           hash contains key = value pairs
                   14071:           where key = uniqueID:scope_end_start
                   14072:                 value = UNIX time record was last updated
                   14073: 
                   14074:           Used to improve speed of look-ups of access controls for each file.  
                   14075:  
                   14076:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14077: 
1.1198    raeburn  14078: =item *
                   14079: 
1.749     raeburn  14080: modify_access_controls():
                   14081: 
                   14082: Modifies access controls for a portfolio file
                   14083: Args
                   14084: 1. file name
                   14085: 2. reference to hash of required changes,
                   14086: 3. domain
                   14087: 4. username
                   14088:   where domain,username are the domain of the portfolio owner 
                   14089:   (either a user or a course) 
                   14090: 
                   14091: Returns:
                   14092: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14093: 2. result of deletions ('ok' or 'error', with error message).
                   14094: 3. reference to hash of any new or updated access controls.
                   14095: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14096:    key = integer (inbound ID)
1.1198    raeburn  14097:    value = uniqueID
                   14098: 
                   14099: =item *
                   14100: 
                   14101: get_timebased_id():
                   14102: 
                   14103: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14104: course via the Course Editor (e.g., folders, composite pages, 
                   14105: group bulletin boards).
                   14106: 
                   14107: Args: (first three required; six others optional)
                   14108: 
                   14109: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14110:    docssequence, or name of group
                   14111: 
                   14112: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14113:    e.g., num, boardids
                   14114: 
                   14115: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14116:    file will be named nohist_namespace.db
                   14117: 
                   14118: 4. cdom: domain of course; default is current course domain from %env
                   14119: 
                   14120: 5. cnum: course number; default is current course number from %env
                   14121: 
                   14122: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14123:    unix timestamp to form the suffix, if the plain timestamp is already
                   14124:    in use.  Default is to not do this, but simply increment the unix 
                   14125:    timestamp by 1 until a unique key is obtained.
                   14126: 
                   14127: 7. who: holder of locking key; defaults to user:domain for user.
                   14128: 
                   14129: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14130:    retrying); default is 3.
                   14131: 
                   14132: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14133: 
                   14134: Returns:
                   14135: 
                   14136: 1. suffix obtained (numeric)
                   14137: 
                   14138: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14139: 
                   14140: 3. error: contains (localized) error message if an error occurred.
                   14141: 
1.747     albertel 14142: 
1.608     albertel 14143: =back
                   14144: 
1.243     albertel 14145: =head2 HTTP Helper Routines
                   14146: 
                   14147: =over 4
                   14148: 
1.191     harris41 14149: =item *
                   14150: 
                   14151: escape() : unpack non-word characters into CGI-compatible hex codes
                   14152: 
                   14153: =item *
                   14154: 
                   14155: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14156: 
1.243     albertel 14157: =back
                   14158: 
                   14159: =head1 PRIVATE SUBROUTINES
                   14160: 
                   14161: =head2 Underlying communication routines (Shouldn't call)
                   14162: 
                   14163: =over 4
                   14164: 
                   14165: =item *
                   14166: 
                   14167: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14168: 
                   14169: =item *
                   14170: 
                   14171: reply() : uses subreply to send a message to remote machine, logs all failures
                   14172: 
                   14173: =item *
                   14174: 
                   14175: critical() : passes a critical message to another server; if cannot
                   14176: get through then place message in connection buffer directory and
                   14177: returns con_delayed, if incapable of saving message, returns
                   14178: con_failed
                   14179: 
                   14180: =item *
                   14181: 
                   14182: reconlonc() : tries to reconnect lonc client processes.
                   14183: 
                   14184: =back
                   14185: 
                   14186: =head2 Resource Access Logging
                   14187: 
                   14188: =over 4
                   14189: 
                   14190: =item *
                   14191: 
                   14192: flushcourselogs() : flush (save) buffer logs and access logs
                   14193: 
                   14194: =item *
                   14195: 
                   14196: courselog($what) : save message for course in hash
                   14197: 
                   14198: =item *
                   14199: 
                   14200: courseacclog($what) : save message for course using &courselog().  Perform
                   14201: special processing for specific resource types (problems, exams, quizzes, etc).
                   14202: 
1.191     harris41 14203: =item *
                   14204: 
                   14205: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14206: as a PerlChildExitHandler
1.243     albertel 14207: 
                   14208: =back
                   14209: 
                   14210: =head2 Other
                   14211: 
                   14212: =over 4
                   14213: 
                   14214: =item *
                   14215: 
                   14216: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14217: 
                   14218: =back
                   14219: 
                   14220: =cut
1.877     foxr     14221: 

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