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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1191  ! raeburn     4: # $Id: lonnet.pm,v 1.1190 2012/09/04 20:48:05 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.871     albertel   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 {
                    359:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   361:     return $response;
                    362: }
                    363: 
1.1       albertel  364: # -------------------------------------------------- Non-critical communication
                    365: sub subreply {
                    366:     my ($cmd,$server)=@_;
1.838     albertel  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      368:     #
                    369:     #  With loncnew process trimming, there's a timing hole between lonc server
                    370:     #  process exit and the master server picking up the listen on the AF_UNIX
                    371:     #  socket.  In that time interval, a lock file will exist:
                    372: 
                    373:     my $lockfile=$peerfile.".lock";
                    374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    375: 	sleep(1);
                    376:     }
                    377:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      378:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      379:     #
1.550     foxr      380:     #   We'll give the connection a few tries before abandoning it.  If
                    381:     #   connection is not possible, we'll con_lost back to the client.
                    382:     #   
                    383:     my $client;
                    384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    386: 				      Type    => SOCK_STREAM,
                    387: 				      Timeout => 10);
1.869     albertel  388: 	if ($client) {
1.550     foxr      389: 	    last;		# Connected!
1.850     albertel  390: 	} else {
1.853     albertel  391: 	    &create_connection(&hostname($server),$server);
1.550     foxr      392: 	}
1.850     albertel  393:         sleep(1);		# Try again later if failed connection.
1.550     foxr      394:     }
                    395:     my $answer;
                    396:     if ($client) {
1.704     albertel  397: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      398: 	$answer=<$client>;
                    399: 	if (!$answer) { $answer="con_lost"; }
                    400: 	chomp($answer);
                    401:     } else {
                    402: 	$answer = 'con_lost';	# Failed connection.
                    403:     }
1.1       albertel  404:     return $answer;
                    405: }
                    406: 
                    407: sub reply {
                    408:     my ($cmd,$server)=@_;
1.838     albertel  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  410:     my $answer=subreply($cmd,$server);
1.65      www       411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  412:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       413:                 " $cmd to $server returned $answer</font>");
                    414:     }
1.1       albertel  415:     return $answer;
                    416: }
                    417: 
                    418: # ----------------------------------------------------------- Send USR1 to lonc
                    419: 
                    420: sub reconlonc {
1.891     albertel  421:     my ($lonid) = @_;
                    422:     my $hostname = &hostname($lonid);
                    423:     if ($lonid) {
                    424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    425: 	if ($hostname && -e $peerfile) {
                    426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    428: 					     Type    => SOCK_STREAM,
                    429: 					     Timeout => 10);
                    430: 	    if ($client) {
                    431: 		print $client ("reset_retries\n");
                    432: 		my $answer=<$client>;
                    433: 		#reset just this one.
                    434: 	    }
                    435: 	}
                    436: 	return;
                    437:     }
                    438: 
1.836     www       439:     &logthis("Trying to reconnect lonc");
1.1       albertel  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  441:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  442: 	my $loncpid=<$fh>;
                    443:         chomp($loncpid);
                    444:         if (kill 0 => $loncpid) {
                    445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    446:             kill USR1 => $loncpid;
                    447:             sleep 1;
1.836     www       448:          } else {
1.12      www       449: 	    &logthis(
1.672     albertel  450:                "<font color=\"blue\">WARNING:".
1.12      www       451:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  452:         }
                    453:     } else {
1.836     www       454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  455:     }
                    456: }
                    457: 
                    458: # ------------------------------------------------------ Critical communication
1.12      www       459: 
1.1       albertel  460: sub critical {
                    461:     my ($cmd,$server)=@_;
1.838     albertel  462:     unless (&hostname($server)) {
1.672     albertel  463:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       464:                " Critical message to unknown server ($server)</font>");
                    465:         return 'no_such_host';
                    466:     }
1.1       albertel  467:     my $answer=reply($cmd,$server);
                    468:     if ($answer eq 'con_lost') {
                    469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  470: 	my $answer=reply($cmd,$server);
1.1       albertel  471:         if ($answer eq 'con_lost') {
                    472:             my $now=time;
                    473:             my $middlename=$cmd;
1.5       www       474:             $middlename=substr($middlename,0,16);
1.1       albertel  475:             $middlename=~s/\W//g;
                    476:             my $dfilename=
1.305     www       477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    478:             $dumpcount++;
1.1       albertel  479:             {
1.448     albertel  480: 		my $dfh;
                    481: 		if (open($dfh,">$dfilename")) {
                    482: 		    print $dfh "$cmd\n"; 
                    483: 		    close($dfh);
                    484: 		}
1.1       albertel  485:             }
                    486:             sleep 2;
                    487:             my $wcmd='';
                    488:             {
1.448     albertel  489: 		my $dfh;
                    490: 		if (open($dfh,"<$dfilename")) {
                    491: 		    $wcmd=<$dfh>; 
                    492: 		    close($dfh);
                    493: 		}
1.1       albertel  494:             }
                    495:             chomp($wcmd);
1.7       www       496:             if ($wcmd eq $cmd) {
1.672     albertel  497: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       498:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  499:                 &logperm("D:$server:$cmd");
                    500: 	        return 'con_delayed';
                    501:             } else {
1.672     albertel  502:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       503:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  504:                 &logperm("F:$server:$cmd");
                    505:                 return 'con_failed';
                    506:             }
                    507:         }
                    508:     }
                    509:     return $answer;
1.405     albertel  510: }
                    511: 
1.755     albertel  512: # ------------------------------------------- check if return value is an error
                    513: 
                    514: sub error {
                    515:     my ($result) = @_;
1.756     albertel  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  517: 	if ($2 == 2) { return undef; }
                    518: 	return $1;
                    519:     }
                    520:     return undef;
                    521: }
                    522: 
1.783     albertel  523: sub convert_and_load_session_env {
                    524:     my ($lonidsdir,$handle)=@_;
                    525:     my @profile;
                    526:     {
1.917     albertel  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    528: 	if (!$opened) {
1.915     albertel  529: 	    return 0;
                    530: 	}
1.783     albertel  531: 	flock($idf,LOCK_SH);
                    532: 	@profile=<$idf>;
                    533: 	close($idf);
                    534:     }
                    535:     my %temp_env;
                    536:     foreach my $line (@profile) {
1.786     albertel  537: 	if ($line !~ m/=/) {
                    538: 	    return 0;
                    539: 	}
1.783     albertel  540: 	chomp($line);
                    541: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    543:     }
                    544:     unlink("$lonidsdir/$handle.id");
                    545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    546: 	    0640)) {
                    547: 	%disk_env = %temp_env;
                    548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    549: 	untie(%disk_env);
                    550:     }
1.786     albertel  551:     return 1;
1.783     albertel  552: }
                    553: 
1.374     www       554: # ------------------------------------------- Transfer profile into environment
1.780     albertel  555: my $env_loaded;
                    556: sub transfer_profile_to_env {
1.788     albertel  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    558:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       559: 
1.720     albertel  560:     if (!defined($lonidsdir)) {
                    561: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    562:     }
                    563:     if (!defined($handle)) {
                    564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    565:     }
                    566: 
1.786     albertel  567:     my $convert;
                    568:     {
1.917     albertel  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    570: 	if (!$opened) {
1.915     albertel  571: 	    return;
                    572: 	}
1.786     albertel  573: 	flock($idf,LOCK_SH);
                    574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    575: 		&GDBM_READER(),0640)) {
                    576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    577: 	    untie(%disk_env);
                    578: 	} else {
                    579: 	    $convert = 1;
                    580: 	}
                    581:     }
                    582:     if ($convert) {
                    583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    584: 	    &logthis("Failed to load session, or convert session.");
                    585: 	}
1.374     www       586:     }
1.783     albertel  587: 
1.786     albertel  588:     my %remove;
1.783     albertel  589:     while ( my $envname = each(%env) ) {
1.433     matthew   590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    591:             if ($time < time-300) {
1.783     albertel  592:                 $remove{$key}++;
1.433     matthew   593:             }
                    594:         }
                    595:     }
1.783     albertel  596: 
1.619     albertel  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  598:     $env_loaded=1;
1.783     albertel  599:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   600:         &delenv($expired_key);
1.374     www       601:     }
1.1       albertel  602: }
                    603: 
1.916     albertel  604: # ---------------------------------------------------- Check for valid session 
                    605: sub check_for_valid_session {
1.1155    raeburn   606:     my ($r,$name) = @_;
1.916     albertel  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   608:     if ($name eq '') {
                    609:         $name = 'lonID';
                    610:     }
                    611:     my $lonid=$cookies{$name};
1.916     albertel  612:     return undef if (!$lonid);
                    613: 
                    614:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   615:     my $lonidsdir;
                    616:     if ($name eq 'lonDAV') {
                    617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    618:     } else {
                    619:         $lonidsdir=$r->dir_config('lonIDsDir');
                    620:     }
1.916     albertel  621:     return undef if (!-e "$lonidsdir/$handle.id");
                    622: 
1.917     albertel  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    624:     return undef if (!$opened);
1.916     albertel  625: 
                    626:     flock($idf,LOCK_SH);
                    627:     my %disk_env;
                    628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    629: 	    &GDBM_READER(),0640)) {
                    630: 	return undef;	
                    631:     }
                    632: 
                    633:     if (!defined($disk_env{'user.name'})
                    634: 	|| !defined($disk_env{'user.domain'})) {
                    635: 	return undef;
                    636:     }
                    637:     return $handle;
                    638: }
                    639: 
1.830     albertel  640: sub timed_flock {
                    641:     my ($file,$lock_type) = @_;
                    642:     my $failed=0;
                    643:     eval {
                    644: 	local $SIG{__DIE__}='DEFAULT';
                    645: 	local $SIG{ALRM}=sub {
                    646: 	    $failed=1;
                    647: 	    die("failed lock");
                    648: 	};
                    649: 	alarm(13);
                    650: 	flock($file,$lock_type);
                    651: 	alarm(0);
                    652:     };
                    653:     if ($failed) {
                    654: 	return undef;
                    655:     } else {
                    656: 	return 1;
                    657:     }
                    658: }
                    659: 
1.5       www       660: # ---------------------------------------------------------- Append Environment
                    661: 
                    662: sub appenv {
1.949     raeburn   663:     my ($newenv,$roles) = @_;
                    664:     if (ref($newenv) eq 'HASH') {
                    665:         foreach my $key (keys(%{$newenv})) {
                    666:             my $refused = 0;
                    667: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    668:                 $refused = 1;
                    669:                 if (ref($roles) eq 'ARRAY') {
                    670:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    671:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    672:                         $refused = 0;
                    673:                     }
                    674:                 }
                    675:             }
                    676:             if ($refused) {
                    677:                 &logthis("<font color=\"blue\">WARNING: ".
                    678:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    679:                          .'</font>');
                    680: 	        delete($newenv->{$key});
                    681:             } else {
                    682:                 $env{$key}=$newenv->{$key};
                    683:             }
                    684:         }
                    685:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    686:         if ($opened
                    687: 	    && &timed_flock($env_file,LOCK_EX)
                    688: 	    &&
                    689: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    690: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    691: 	    while (my ($key,$value) = each(%{$newenv})) {
                    692: 	        $disk_env{$key} = $value;
                    693: 	    }
                    694: 	    untie(%disk_env);
1.35      www       695:         }
1.191     harris41  696:     }
1.56      www       697:     return 'ok';
                    698: }
                    699: # ----------------------------------------------------- Delete from Environment
                    700: 
                    701: sub delenv {
1.1104    raeburn   702:     my ($delthis,$regexp,$roles) = @_;
                    703:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    704:         my $refused = 1;
                    705:         if (ref($roles) eq 'ARRAY') {
                    706:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    707:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    708:                 $refused = 0;
                    709:             }
                    710:         }
                    711:         if ($refused) {
                    712:             &logthis("<font color=\"blue\">WARNING: ".
                    713:                      "Attempt to delete from environment ".$delthis);
                    714:             return 'error';
                    715:         }
1.56      www       716:     }
1.917     albertel  717:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    718:     if ($opened
1.915     albertel  719: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  720: 	&&
                    721: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    722: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  723: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   724: 	    if ($regexp) {
                    725:                 if ($key=~/^$delthis/) {
                    726:                     delete($env{$key});
                    727:                     delete($disk_env{$key});
                    728:                 } 
                    729:             } else {
                    730:                 if ($key=~/^\Q$delthis\E/) {
                    731: 		    delete($env{$key});
                    732: 		    delete($disk_env{$key});
                    733: 	        }
                    734:             }
1.448     albertel  735: 	}
1.783     albertel  736: 	untie(%disk_env);
1.5       www       737:     }
                    738:     return 'ok';
1.369     albertel  739: }
                    740: 
1.790     albertel  741: sub get_env_multiple {
                    742:     my ($name) = @_;
                    743:     my @values;
                    744:     if (defined($env{$name})) {
                    745:         # exists is it an array
                    746:         if (ref($env{$name})) {
                    747:             @values=@{ $env{$name} };
                    748:         } else {
                    749:             $values[0]=$env{$name};
                    750:         }
                    751:     }
                    752:     return(@values);
                    753: }
                    754: 
1.958     www       755: # ------------------------------------------------------------------- Locking
                    756: 
                    757: sub set_lock {
                    758:     my ($text)=@_;
                    759:     $locknum++;
                    760:     my $id=$$.'-'.$locknum;
                    761:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    762:              'session.lock.'.$id => $text});
                    763:     return $id;
                    764: }
                    765: 
                    766: sub get_locks {
                    767:     my $num=0;
                    768:     my %texts=();
                    769:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    770:        if ($lock=~/\w/) {
                    771:           $num++;
                    772:           $texts{$lock}=$env{'session.lock.'.$lock};
                    773:        }
                    774:    }
                    775:    return ($num,%texts);
                    776: }
                    777: 
                    778: sub remove_lock {
                    779:     my ($id)=@_;
                    780:     my $newlocks='';
                    781:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    782:        if (($lock=~/\w/) && ($lock ne $id)) {
                    783:           $newlocks.=','.$lock;
                    784:        }
                    785:     }
                    786:     &appenv({'session.locks' => $newlocks});
                    787:     &delenv('session.lock.'.$id);
                    788: }
                    789: 
                    790: sub remove_all_locks {
                    791:     my $activelocks=$env{'session.locks'};
                    792:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    793:        if ($lock=~/\w/) {
                    794:           &remove_lock($lock);
                    795:        }
                    796:     }
                    797: }
                    798: 
                    799: 
1.369     albertel  800: # ------------------------------------------ Find out current server userload
                    801: sub userload {
                    802:     my $numusers=0;
                    803:     {
                    804: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    805: 	my $filename;
                    806: 	my $curtime=time;
                    807: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  808: 	    next if ($filename eq '.' || $filename eq '..');
                    809: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  810: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  811: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  812: 	}
                    813: 	closedir(LONIDS);
                    814:     }
                    815:     my $userloadpercent=0;
                    816:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    817:     if ($maxuserload) {
1.371     albertel  818: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  819:     }
1.372     albertel  820:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  821:     return $userloadpercent;
1.283     www       822: }
                    823: 
1.1       albertel  824: # ------------------------------ Find server with least workload from spare.tab
1.11      www       825: 
1.1       albertel  826: sub spareserver {
1.1083    raeburn   827:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  828:     my $spare_server;
1.370     albertel  829:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  830:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    831:                                                      :  $userloadpercent;
1.1083    raeburn   832:     my ($uint_dom,$remotesessions);
                    833:     if (($udom ne '') && (&domain($udom) ne '')) {
                    834:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    835:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    836:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    837:         $remotesessions = $udomdefaults{'remotesessions'};
                    838:     }
1.1123    raeburn   839:     my $spareshash = &this_host_spares($udom);
                    840:     if (ref($spareshash) eq 'HASH') {
                    841:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    842:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    843:                 if ($uint_dom) {
                    844:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    845:                                                  $try_server));
                    846:                 }
                    847: 	        ($spare_server, $lowest_load) =
                    848: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    849:             }
1.1083    raeburn   850:         }
1.784     albertel  851: 
1.1123    raeburn   852:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    853: 
                    854:         if (!$found_server) {
                    855:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    856: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    857:                     if ($uint_dom) {
                    858:                         next unless (&spare_can_host($udom,$uint_dom,
                    859:                                                      $remotesessions,$try_server));
                    860:                     }
                    861: 	            ($spare_server, $lowest_load) =
                    862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:                 }
                    864: 	    }
                    865:         }
1.784     albertel  866:     }
                    867: 
                    868:     if (!$want_server_name) {
1.968     raeburn   869:         my $protocol = 'http';
                    870:         if ($protocol{$spare_server} eq 'https') {
                    871:             $protocol = $protocol{$spare_server};
                    872:         }
1.1001    raeburn   873:         if (defined($spare_server)) {
                    874:             my $hostname = &hostname($spare_server);
1.1083    raeburn   875:             if (defined($hostname)) {
1.1001    raeburn   876: 	        $spare_server = $protocol.'://'.$hostname;
                    877:             }
                    878:         }
1.784     albertel  879:     }
                    880:     return $spare_server;
                    881: }
                    882: 
                    883: sub compare_server_load {
                    884:     my ($try_server, $spare_server, $lowest_load) = @_;
                    885: 
                    886:     my $loadans     = &reply('load',    $try_server);
                    887:     my $userloadans = &reply('userload',$try_server);
                    888: 
                    889:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   890: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  891:     }
                    892: 
                    893:     my $load;
                    894:     if ($loadans =~ /\d/) {
                    895: 	if ($userloadans =~ /\d/) {
                    896: 	    #both are numbers, pick the bigger one
                    897: 	    $load = ($loadans > $userloadans) ? $loadans 
                    898: 		                              : $userloadans;
1.411     albertel  899: 	} else {
1.784     albertel  900: 	    $load = $loadans;
1.411     albertel  901: 	}
1.784     albertel  902:     } else {
                    903: 	$load = $userloadans;
                    904:     }
                    905: 
                    906:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    907: 	$spare_server = $try_server;
                    908: 	$lowest_load  = $load;
1.370     albertel  909:     }
1.784     albertel  910:     return ($spare_server,$lowest_load);
1.202     matthew   911: }
1.914     albertel  912: 
                    913: # --------------------------- ask offload servers if user already has a session
                    914: sub find_existing_session {
                    915:     my ($udom,$uname) = @_;
1.1123    raeburn   916:     my $spareshash = &this_host_spares($udom);
                    917:     if (ref($spareshash) eq 'HASH') {
                    918:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    919:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    920:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    921:             }
                    922:         }
                    923:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    924:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    926:             }
                    927:         }
1.914     albertel  928:     }
                    929:     return;
                    930: }
                    931: 
                    932: # -------------------------------- ask if server already has a session for user
                    933: sub has_user_session {
                    934:     my ($lonid,$udom,$uname) = @_;
                    935:     my $result = &reply(join(':','userhassession',
                    936: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    937:     return 1 if ($result eq 'ok');
                    938: 
                    939:     return 0;
                    940: }
                    941: 
1.1076    raeburn   942: # --------- determine least loaded server in a user's domain which allows login
                    943: 
                    944: sub choose_server {
1.1115    raeburn   945:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   946:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   947:     my %servers = &get_servers($udom);
1.1076    raeburn   948:     my $lowest_load = 30000;
1.1151    raeburn   949:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   950:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   951:         my $loginvia;
                    952:         if ($checkloginvia) {
                    953:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   954:             if ($loginvia) {
                    955:                 my ($server,$path) = split(/:/,$loginvia);
                    956:                 ($login_host, $lowest_load) =
                    957:                     &compare_server_load($server, $login_host, $lowest_load);
                    958:                 if ($login_host eq $server) {
                    959:                     $portal_path = $path;
1.1151    raeburn   960:                     $isredirect = 1;
1.1116    raeburn   961:                 }
                    962:             } else {
                    963:                 ($login_host, $lowest_load) =
                    964:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    965:                 if ($login_host eq $lonhost) {
                    966:                     $portal_path = '';
1.1151    raeburn   967:                     $isredirect = ''; 
1.1116    raeburn   968:                 }
                    969:             }
                    970:         } else {
1.1076    raeburn   971:             ($login_host, $lowest_load) =
1.1116    raeburn   972:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   973:         }
                    974:     }
                    975:     if ($login_host ne '') {
1.1116    raeburn   976:         $hostname = &hostname($login_host);
1.1076    raeburn   977:     }
1.1151    raeburn   978:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   979: }
                    980: 
1.202     matthew   981: # --------------------------------------------- Try to change a user's password
                    982: 
                    983: sub changepass {
1.799     raeburn   984:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   985:     $currentpass = &escape($currentpass);
                    986:     $newpass     = &escape($newpass);
1.1030    raeburn   987:     my $lonhost = $perlvar{'lonHostID'};
                    988:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   989: 		       $server);
                    990:     if (! $answer) {
                    991: 	&logthis("No reply on password change request to $server ".
                    992: 		 "by $uname in domain $udom.");
                    993:     } elsif ($answer =~ "^ok") {
                    994:         &logthis("$uname in $udom successfully changed their password ".
                    995: 		 "on $server.");
                    996:     } elsif ($answer =~ "^pwchange_failure") {
                    997: 	&logthis("$uname in $udom was unable to change their password ".
                    998: 		 "on $server.  The action was blocked by either lcpasswd ".
                    999: 		 "or pwchange");
                   1000:     } elsif ($answer =~ "^non_authorized") {
                   1001:         &logthis("$uname in $udom did not get their password correct when ".
                   1002: 		 "attempting to change it on $server.");
                   1003:     } elsif ($answer =~ "^auth_mode_error") {
                   1004:         &logthis("$uname in $udom attempted to change their password despite ".
                   1005: 		 "not being locally or internally authenticated on $server.");
                   1006:     } elsif ($answer =~ "^unknown_user") {
                   1007:         &logthis("$uname in $udom attempted to change their password ".
                   1008: 		 "on $server but were unable to because $server is not ".
                   1009: 		 "their home server.");
                   1010:     } elsif ($answer =~ "^refused") {
                   1011: 	&logthis("$server refused to change $uname in $udom password because ".
                   1012: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1013:     } elsif ($answer =~ "invalid_client") {
                   1014:         &logthis("$server refused to change $uname in $udom password because ".
                   1015:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1016:     }
                   1017:     return $answer;
1.1       albertel 1018: }
                   1019: 
1.169     harris41 1020: # ----------------------- Try to determine user's current authentication scheme
                   1021: 
                   1022: sub queryauthenticate {
                   1023:     my ($uname,$udom)=@_;
1.456     albertel 1024:     my $uhome=&homeserver($uname,$udom);
                   1025:     if (!$uhome) {
                   1026: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1027: 	return 'no_host';
                   1028:     }
                   1029:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1030:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1031: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1032:     }
1.456     albertel 1033:     return $answer;
1.169     harris41 1034: }
                   1035: 
1.1       albertel 1036: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1037: 
1.1       albertel 1038: sub authenticate {
1.1073    raeburn  1039:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1040:     $upass=&escape($upass);
                   1041:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1042:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1043:     my $newhome;
1.836     www      1044:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1045: # Maybe the machine was offline and only re-appeared again recently?
                   1046:         &reconlonc();
                   1047: # One more
1.952     raeburn  1048: 	$uhome=&homeserver($uname,$udom,1);
                   1049:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1050:             if (defined(&domain($udom,'primary'))) {
                   1051:                 $newhome=&domain($udom,'primary');
                   1052:             }
                   1053:             if ($newhome ne '') {
                   1054:                 $uhome = $newhome;
                   1055:             }
                   1056:         }
1.836     www      1057: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1058: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1059: 	    return 'no_host';
                   1060:         }
1.1       albertel 1061:     }
1.1073    raeburn  1062:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1063:     if ($answer eq 'authorized') {
1.952     raeburn  1064:         if ($newhome) {
                   1065:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1066:             return 'no_account_on_host'; 
                   1067:         } else {
                   1068:             &logthis("User $uname at $udom authorized by $uhome");
                   1069:             return $uhome;
                   1070:         }
1.471     albertel 1071:     }
                   1072:     if ($answer eq 'non_authorized') {
                   1073: 	&logthis("User $uname at $udom rejected by $uhome");
                   1074: 	return 'no_host'; 
1.9       www      1075:     }
1.471     albertel 1076:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1077:     return 'no_host';
                   1078: }
                   1079: 
1.1073    raeburn  1080: sub can_host_session {
1.1074    raeburn  1081:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1082:     my $canhost = 1;
1.1074    raeburn  1083:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1084:     if (ref($remotesessions) eq 'HASH') {
                   1085:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1087:                 $canhost = 0;
                   1088:             } else {
                   1089:                 $canhost = 1;
                   1090:             }
                   1091:         }
                   1092:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1094:                 $canhost = 1;
                   1095:             } else {
                   1096:                 $canhost = 0;
                   1097:             }
                   1098:         }
                   1099:         if ($canhost) {
                   1100:             if ($remotesessions->{'version'} ne '') {
                   1101:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1102:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1103:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1104:                         my $major = $1;
                   1105:                         my $minor = $2;
                   1106:                         if (($major < $reqmajor ) ||
                   1107:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1108:                             $canhost = 0;
                   1109:                         }
                   1110:                     } else {
                   1111:                         $canhost = 0;
                   1112:                     }
                   1113:                 }
                   1114:             }
                   1115:         }
                   1116:     }
                   1117:     if ($canhost) {
                   1118:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1119:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1120:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1121:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1122:                 if (($uint_dom ne '') && 
                   1123:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1124:                     $canhost = 0;
                   1125:                 } else {
                   1126:                     $canhost = 1;
                   1127:                 }
                   1128:             }
                   1129:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1130:                 if (($uint_dom ne '') && 
                   1131:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1132:                     $canhost = 1;
                   1133:                 } else {
                   1134:                     $canhost = 0;
                   1135:                 }
                   1136:             }
                   1137:         }
                   1138:     }
                   1139:     return $canhost;
                   1140: }
                   1141: 
1.1083    raeburn  1142: sub spare_can_host {
                   1143:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1144:     my $canhost=1;
                   1145:     my @intdoms;
                   1146:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1147:     if (ref($internet_names) eq 'ARRAY') {
                   1148:         @intdoms = @{$internet_names};
                   1149:     }
                   1150:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1151:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1152:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1153:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1154:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1155:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1156:                                      $remotesessions,
                   1157:                                      $defdomdefaults{'hostedsessions'});
                   1158:     }
                   1159:     return $canhost;
                   1160: }
                   1161: 
1.1123    raeburn  1162: sub this_host_spares {
                   1163:     my ($dom) = @_;
1.1126    raeburn  1164:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1165:     my @hosts = &current_machine_ids();
                   1166:     foreach my $lonhost (@hosts) {
                   1167:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1168:             $dom_in_use = $dom;
                   1169:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1170:             last;
                   1171:         }
                   1172:     }
1.1126    raeburn  1173:     if ($dom_in_use ne '') {
                   1174:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1175:     }
                   1176:     if (ref($result) ne 'HASH') {
                   1177:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1178:         $dom_in_use = &host_domain($lonhost_in_use);
                   1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1180:         if (ref($result) ne 'HASH') {
                   1181:             $result = \%spareid;
                   1182:         }
                   1183:     }
                   1184:     return $result;
                   1185: }
                   1186: 
                   1187: sub spares_for_offload  {
                   1188:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1189:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1190:     if (defined($cached)) {
                   1191:         return $result;
                   1192:     } else {
1.1126    raeburn  1193:         my $cachetime = 60*60*24;
                   1194:         my %domconfig =
                   1195:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1196:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1197:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1198:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1199:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1200:                 }
                   1201:             }
                   1202:         }
                   1203:     }
1.1126    raeburn  1204:     return;
1.1123    raeburn  1205: }
                   1206: 
1.1129    raeburn  1207: sub get_lonbalancer_config {
                   1208:     my ($servers) = @_;
                   1209:     my ($currbalancer,$currtargets);
                   1210:     if (ref($servers) eq 'HASH') {
                   1211:         foreach my $server (keys(%{$servers})) {
                   1212:             my %what = (
                   1213:                          spareid => 1,
                   1214:                          perlvar => 1,
                   1215:                        );
                   1216:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1217:             if ($result eq 'ok') {
                   1218:                 if (ref($returnhash) eq 'HASH') {
                   1219:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1220:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1221:                             $currbalancer = $server;
                   1222:                             $currtargets = {};
                   1223:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1224:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1225:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1226:                                 }
                   1227:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1228:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1229:                                 }
                   1230:                             }
                   1231:                             last;
                   1232:                         }
                   1233:                     }
                   1234:                 }
                   1235:             }
                   1236:         }
                   1237:     }
                   1238:     return ($currbalancer,$currtargets);
                   1239: }
                   1240: 
                   1241: sub check_loadbalancing {
                   1242:     my ($uname,$udom) = @_;
1.1191  ! raeburn  1243:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
        !          1244:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1245:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1246:     my @hosts = &current_machine_ids();
1.1129    raeburn  1247:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1248:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1249:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1250:     my $serverhomedom = &host_domain($lonhost);
                   1251: 
                   1252:     my $cachetime = 60*60*24;
                   1253: 
                   1254:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1255:         $dom_in_use = $udom;
                   1256:         $homeintdom = 1;
                   1257:     } else {
                   1258:         $dom_in_use = $serverhomedom;
                   1259:     }
                   1260:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1261:     unless (defined($cached)) {
                   1262:         my %domconfig =
                   1263:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1264:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1265:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1266:         }
                   1267:     }
                   1268:     if (ref($result) eq 'HASH') {
1.1191  ! raeburn  1269:         ($is_balancer,$currtargets,$currrules) = 
        !          1270:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1271:         if ($is_balancer) {
                   1272:             if (ref($currrules) eq 'HASH') {
                   1273:                 if ($homeintdom) {
                   1274:                     if ($uname ne '') {
                   1275:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1276:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1277:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1278:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1279:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1280:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1281:                             }
                   1282:                         }
                   1283:                         if ($rule_in_effect eq '') {
                   1284:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1285:                             if ($userenv{'inststatus'} ne '') {
                   1286:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1287:                                 my ($othertitle,$usertypes,$types) =
                   1288:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1289:                                 if (ref($types) eq 'ARRAY') {
                   1290:                                     foreach my $type (@{$types}) {
                   1291:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1292:                                             if (exists($currrules->{$type})) {
                   1293:                                                 $rule_in_effect = $currrules->{$type};
                   1294:                                             }
                   1295:                                         }
                   1296:                                     }
                   1297:                                 }
                   1298:                             } else {
                   1299:                                 if (exists($currrules->{'default'})) {
                   1300:                                     $rule_in_effect = $currrules->{'default'};
                   1301:                                 }
                   1302:                             }
                   1303:                         }
                   1304:                     } else {
                   1305:                         if (exists($currrules->{'default'})) {
                   1306:                             $rule_in_effect = $currrules->{'default'};
                   1307:                         }
                   1308:                     }
                   1309:                 } else {
                   1310:                     if ($currrules->{'_LC_external'} ne '') {
                   1311:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1312:                     }
                   1313:                 }
                   1314:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1315:                                                        $uname,$udom);
                   1316:             }
                   1317:         }
                   1318:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1319:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1320:         unless (defined($cached)) {
                   1321:             my %domconfig =
                   1322:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1323:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1324:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1325:             }
                   1326:         }
                   1327:         if (ref($result) eq 'HASH') {
1.1191  ! raeburn  1328:             ($is_balancer,$currtargets,$currrules) = 
        !          1329:                 &check_balancer_result($result,@hosts);
        !          1330:             if ($is_balancer) {
1.1129    raeburn  1331:                 if (ref($currrules) eq 'HASH') {
                   1332:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1333:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1334:                     }
                   1335:                 }
                   1336:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1337:                                                        $uname,$udom);
                   1338:             }
                   1339:         } else {
                   1340:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1341:                 $is_balancer = 1;
                   1342:                 $offloadto = &this_host_spares($dom_in_use);
                   1343:             }
                   1344:         }
                   1345:     } else {
                   1346:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1347:             $is_balancer = 1;
                   1348:             $offloadto = &this_host_spares($dom_in_use);
                   1349:         }
                   1350:     }
1.1176    raeburn  1351:     if ($is_balancer) {
                   1352:         my $lowest_load = 30000;
                   1353:         if (ref($offloadto) eq 'HASH') {
                   1354:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1355:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1356:                     ($otherserver,$lowest_load) =
                   1357:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1358:                 }
1.1129    raeburn  1359:             }
1.1176    raeburn  1360:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1361: 
1.1176    raeburn  1362:             if (!$found_server) {
                   1363:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1364:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1365:                         ($otherserver,$lowest_load) =
                   1366:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1367:                     }
                   1368:                 }
                   1369:             }
                   1370:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1371:             if (@{$offloadto} == 1) {
                   1372:                 $otherserver = $offloadto->[0];
                   1373:             } elsif (@{$offloadto} > 1) {
                   1374:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1375:                     ($otherserver,$lowest_load) =
                   1376:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1377:                 }
                   1378:             }
                   1379:         }
1.1176    raeburn  1380:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1381:             $is_balancer = 0;
                   1382:             if ($uname ne '' && $udom ne '') {
                   1383:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1384:                     
                   1385:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1386:                              'user.loadbalcheck.time' => time});
                   1387:                 }
1.1129    raeburn  1388:             }
                   1389:         }
                   1390:     }
                   1391:     return ($is_balancer,$otherserver);
                   1392: }
                   1393: 
1.1191  ! raeburn  1394: sub check_balancer_result {
        !          1395:     my ($result,@hosts) = @_;
        !          1396:     my ($is_balancer,$currtargets,$currrules);
        !          1397:     if (ref($result) eq 'HASH') {
        !          1398:         if ($result->{'lonhost'} ne '') {
        !          1399:             my $currbalancer = $result->{'lonhost'};
        !          1400:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
        !          1401:                 $is_balancer = 1;
        !          1402:                 $currtargets = $result->{'targets'};
        !          1403:                 $currrules = $result->{'rules'};
        !          1404:             }
        !          1405:         } else {
        !          1406:             foreach my $key (keys(%{$result})) {
        !          1407:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
        !          1408:                     (ref($result->{$key}) eq 'HASH')) {
        !          1409:                     $is_balancer = 1;
        !          1410:                     $currrules = $result->{$key}{'rules'};
        !          1411:                     $currtargets = $result->{$key}{'targets'};
        !          1412:                     last;
        !          1413:                 }
        !          1414:             }
        !          1415:         }
        !          1416:     }
        !          1417:     return ($is_balancer,$currtargets,$currrules);
        !          1418: }
        !          1419: 
1.1129    raeburn  1420: sub get_loadbalancer_targets {
                   1421:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1422:     my $offloadto;
1.1175    raeburn  1423:     if ($rule_in_effect eq 'none') {
                   1424:         return [$perlvar{'lonHostID'}];
                   1425:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1426:         $offloadto = $currtargets;
                   1427:     } else {
                   1428:         if ($rule_in_effect eq 'homeserver') {
                   1429:             my $homeserver = &homeserver($uname,$udom);
                   1430:             if ($homeserver ne 'no_host') {
                   1431:                 $offloadto = [$homeserver];
                   1432:             }
                   1433:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1434:             my %domconfig =
                   1435:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1436:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1437:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1438:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1439:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1440:                     }
                   1441:                 }
                   1442:             } else {
1.1178    raeburn  1443:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1444:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1445:                 if (&hostname($remotebalancer) ne '') {
                   1446:                     $offloadto = [$remotebalancer];
                   1447:                 }
                   1448:             }
                   1449:         } elsif (&hostname($rule_in_effect) ne '') {
                   1450:             $offloadto = [$rule_in_effect];
                   1451:         }
                   1452:     }
                   1453:     return $offloadto;
                   1454: }
                   1455: 
1.1127    raeburn  1456: sub internet_dom_servers {
                   1457:     my ($dom) = @_;
                   1458:     my (%uniqservers,%servers);
                   1459:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1460:     my @machinedoms = &machine_domains($primaryserver);
                   1461:     foreach my $mdom (@machinedoms) {
                   1462:         my %currservers = %servers;
                   1463:         my %server = &get_servers($mdom);
                   1464:         %servers = (%currservers,%server);
                   1465:     }
                   1466:     my %by_hostname;
                   1467:     foreach my $id (keys(%servers)) {
                   1468:         push(@{$by_hostname{$servers{$id}}},$id);
                   1469:     }
                   1470:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1471:         if (@{$by_hostname{$hostname}} > 1) {
                   1472:             my $match = 0;
                   1473:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1474:                 if (&host_domain($id) eq $dom) {
                   1475:                     $uniqservers{$id} = $hostname;
                   1476:                     $match = 1;
                   1477:                 }
                   1478:             }
                   1479:             unless ($match) {
                   1480:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1481:             }
                   1482:         } else {
                   1483:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1484:         }
                   1485:     }
                   1486:     return %uniqservers;
                   1487: }
                   1488: 
1.1       albertel 1489: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1490: 
1.599     albertel 1491: my %homecache;
1.1       albertel 1492: sub homeserver {
1.230     stredwic 1493:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1494:     my $index="$uname:$udom";
1.426     albertel 1495: 
1.599     albertel 1496:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1497: 
                   1498:     my %servers = &get_servers($udom,'library');
                   1499:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1500:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1501: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1502: 
                   1503: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1504: 	if ($answer eq 'found') {
                   1505: 	    delete($badServerCache{$tryserver}); 
                   1506: 	    return $homecache{$index}=$tryserver;
                   1507: 	} elsif ($answer eq 'no_host') {
                   1508: 	    $badServerCache{$tryserver}=1;
                   1509: 	}
1.1       albertel 1510:     }    
                   1511:     return 'no_host';
1.70      www      1512: }
                   1513: 
                   1514: # ------------------------------------- Find the usernames behind a list of IDs
                   1515: 
                   1516: sub idget {
                   1517:     my ($udom,@ids)=@_;
                   1518:     my %returnhash=();
                   1519:     
1.841     albertel 1520:     my %servers = &get_servers($udom,'library');
                   1521:     foreach my $tryserver (keys(%servers)) {
                   1522: 	my $idlist=join('&',@ids);
                   1523: 	$idlist=~tr/A-Z/a-z/; 
                   1524: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1525: 	my @answer=();
                   1526: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1527: 	    @answer=split(/\&/,$reply);
                   1528: 	}                    ;
                   1529: 	my $i;
                   1530: 	for ($i=0;$i<=$#ids;$i++) {
                   1531: 	    if ($answer[$i]) {
                   1532: 		$returnhash{$ids[$i]}=$answer[$i];
                   1533: 	    } 
                   1534: 	}
                   1535:     } 
1.70      www      1536:     return %returnhash;
                   1537: }
                   1538: 
                   1539: # ------------------------------------- Find the IDs behind a list of usernames
                   1540: 
                   1541: sub idrget {
                   1542:     my ($udom,@unames)=@_;
                   1543:     my %returnhash=();
1.800     albertel 1544:     foreach my $uname (@unames) {
                   1545:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1546:     }
1.70      www      1547:     return %returnhash;
                   1548: }
                   1549: 
                   1550: # ------------------------------- Store away a list of names and associated IDs
                   1551: 
                   1552: sub idput {
                   1553:     my ($udom,%ids)=@_;
                   1554:     my %servers=();
1.800     albertel 1555:     foreach my $uname (keys(%ids)) {
                   1556: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1557:         my $uhom=&homeserver($uname,$udom);
1.70      www      1558:         if ($uhom ne 'no_host') {
1.800     albertel 1559:             my $id=&escape($ids{$uname});
1.70      www      1560:             $id=~tr/A-Z/a-z/;
1.800     albertel 1561:             my $esc_unam=&escape($uname);
1.70      www      1562: 	    if ($servers{$uhom}) {
1.800     albertel 1563: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1564:             } else {
1.800     albertel 1565:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1566:             }
                   1567:         }
1.191     harris41 1568:     }
1.800     albertel 1569:     foreach my $server (keys(%servers)) {
                   1570:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1571:     }
1.344     www      1572: }
                   1573: 
1.1023    raeburn  1574: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1575: sub dump_dom {
1.1165    droeschl 1576:     my ($namespace, $udom, $regexp) = @_;
                   1577: 
                   1578:     $udom ||= $env{'user.domain'};
                   1579: 
                   1580:     return () unless $udom;
                   1581: 
                   1582:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1583: }
                   1584: 
1.1023    raeburn  1585: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1586: 
                   1587: sub get_dom {
1.860     raeburn  1588:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1589:     my $items='';
                   1590:     foreach my $item (@$storearr) {
                   1591:         $items.=&escape($item).'&';
                   1592:     }
                   1593:     $items=~s/\&$//;
1.860     raeburn  1594:     if (!$udom) {
                   1595:         $udom=$env{'user.domain'};
                   1596:         if (defined(&domain($udom,'primary'))) {
                   1597:             $uhome=&domain($udom,'primary');
                   1598:         } else {
1.874     albertel 1599:             undef($uhome);
1.860     raeburn  1600:         }
                   1601:     } else {
                   1602:         if (!$uhome) {
                   1603:             if (defined(&domain($udom,'primary'))) {
                   1604:                 $uhome=&domain($udom,'primary');
                   1605:             }
                   1606:         }
                   1607:     }
                   1608:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1609:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1610:         my %returnhash;
1.875     albertel 1611:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1612:             return %returnhash;
                   1613:         }
1.806     raeburn  1614:         my @pairs=split(/\&/,$rep);
                   1615:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1616:             return @pairs;
                   1617:         }
                   1618:         my $i=0;
                   1619:         foreach my $item (@$storearr) {
                   1620:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1621:             $i++;
                   1622:         }
                   1623:         return %returnhash;
                   1624:     } else {
1.880     banghart 1625:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1626:     }
                   1627: }
                   1628: 
                   1629: # -------------------------------------------- put items in domain db files 
                   1630: 
                   1631: sub put_dom {
1.860     raeburn  1632:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1633:     if (!$udom) {
                   1634:         $udom=$env{'user.domain'};
                   1635:         if (defined(&domain($udom,'primary'))) {
                   1636:             $uhome=&domain($udom,'primary');
                   1637:         } else {
1.874     albertel 1638:             undef($uhome);
1.860     raeburn  1639:         }
                   1640:     } else {
                   1641:         if (!$uhome) {
                   1642:             if (defined(&domain($udom,'primary'))) {
                   1643:                 $uhome=&domain($udom,'primary');
                   1644:             }
                   1645:         }
                   1646:     } 
                   1647:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1648:         my $items='';
                   1649:         foreach my $item (keys(%$storehash)) {
                   1650:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1651:         }
                   1652:         $items=~s/\&$//;
                   1653:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1654:     } else {
1.860     raeburn  1655:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1656:     }
                   1657: }
                   1658: 
1.1023    raeburn  1659: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1660: sub newput_dom {
1.1023    raeburn  1661:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1662:     my $result;
                   1663:     if (!$udom) {
                   1664:         $udom=$env{'user.domain'};
                   1665:     }
1.1023    raeburn  1666:     if ($udom) {
                   1667:         my $uname = &get_domainconfiguser($udom);
                   1668:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1669:     }
                   1670:     return $result;
                   1671: }
                   1672: 
1.1023    raeburn  1673: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1674: sub del_dom {
1.1023    raeburn  1675:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1676:     if (ref($storearr) eq 'ARRAY') {
                   1677:         if (!$udom) {
                   1678:             $udom=$env{'user.domain'};
                   1679:         }
1.1023    raeburn  1680:         if ($udom) {
                   1681:             my $uname = &get_domainconfiguser($udom); 
                   1682:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1683:         }
                   1684:     }
                   1685: }
                   1686: 
1.1023    raeburn  1687: # ----------------------------------construct domainconfig user for a domain 
                   1688: sub get_domainconfiguser {
                   1689:     my ($udom) = @_;
                   1690:     return $udom.'-domainconfig';
                   1691: }
                   1692: 
1.837     raeburn  1693: sub retrieve_inst_usertypes {
                   1694:     my ($udom) = @_;
                   1695:     my (%returnhash,@order);
1.989     raeburn  1696:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1697:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1698:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1699:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1700:         @order = @{$domdefs{'inststatusorder'}};
                   1701:     } else {
                   1702:         if (defined(&domain($udom,'primary'))) {
                   1703:             my $uhome=&domain($udom,'primary');
                   1704:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1705:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1706:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1707:                 return (\%returnhash,\@order);
                   1708:             }
                   1709:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1710:             my @pairs=split(/\&/,$hashitems);
                   1711:             foreach my $item (@pairs) {
                   1712:                 my ($key,$value)=split(/=/,$item,2);
                   1713:                 $key = &unescape($key);
                   1714:                 next if ($key =~ /^error: 2 /);
                   1715:                 $returnhash{$key}=&thaw_unescape($value);
                   1716:             }
                   1717:             my @esc_order = split(/\&/,$orderitems);
                   1718:             foreach my $item (@esc_order) {
                   1719:                 push(@order,&unescape($item));
                   1720:             }
                   1721:         } else {
                   1722:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1723:         }
                   1724:     }
                   1725:     return (\%returnhash,\@order);
                   1726: }
                   1727: 
1.868     raeburn  1728: sub is_domainimage {
                   1729:     my ($url) = @_;
                   1730:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1731:         if (&domain($1) ne '') {
                   1732:             return '1';
                   1733:         }
                   1734:     }
                   1735:     return;
                   1736: }
                   1737: 
1.899     raeburn  1738: sub inst_directory_query {
                   1739:     my ($srch) = @_;
                   1740:     my $udom = $srch->{'srchdomain'};
                   1741:     my %results;
                   1742:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1743:     my $outcome;
1.899     raeburn  1744:     if ($homeserver ne '') {
1.904     albertel 1745: 	my $queryid=&reply("querysend:instdirsearch:".
                   1746: 			   &escape($srch->{'srchby'}).':'.
                   1747: 			   &escape($srch->{'srchterm'}).':'.
                   1748: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1749: 	my $host=&hostname($homeserver);
                   1750: 	if ($queryid !~/^\Q$host\E\_/) {
                   1751: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1752: 	    return;
                   1753: 	}
                   1754: 	my $response = &get_query_reply($queryid);
                   1755: 	my $maxtries = 5;
                   1756: 	my $tries = 1;
                   1757: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1758: 	    $response = &get_query_reply($queryid);
                   1759: 	    $tries ++;
                   1760: 	}
                   1761: 
                   1762:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1763:             if ($response eq 'unavailable') {
                   1764:                 $outcome = $response;
                   1765:             } else {
                   1766:                 $outcome = 'ok';
                   1767:                 my @matches = split(/\n/,$response);
                   1768:                 foreach my $match (@matches) {
                   1769:                     my ($key,$value) = split(/=/,$match);
                   1770:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1771:                 }
1.899     raeburn  1772:             }
                   1773:         }
                   1774:     }
1.909     raeburn  1775:     return ($outcome,%results);
1.899     raeburn  1776: }
                   1777: 
                   1778: sub usersearch {
                   1779:     my ($srch) = @_;
                   1780:     my $dom = $srch->{'srchdomain'};
                   1781:     my %results;
                   1782:     my %libserv = &all_library();
                   1783:     my $query = 'usersearch';
                   1784:     foreach my $tryserver (keys(%libserv)) {
                   1785:         if (&host_domain($tryserver) eq $dom) {
                   1786:             my $host=&hostname($tryserver);
                   1787:             my $queryid=
1.911     raeburn  1788:                 &reply("querysend:".&escape($query).':'.
                   1789:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1790:                        &escape($srch->{'srchtype'}).':'.
                   1791:                        &escape($srch->{'srchterm'}),$tryserver);
                   1792:             if ($queryid !~/^\Q$host\E\_/) {
                   1793:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1794:                 next;
1.899     raeburn  1795:             }
                   1796:             my $reply = &get_query_reply($queryid);
                   1797:             my $maxtries = 1;
                   1798:             my $tries = 1;
                   1799:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1800:                 $reply = &get_query_reply($queryid);
                   1801:                 $tries ++;
                   1802:             }
                   1803:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1804:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1805:             } else {
1.911     raeburn  1806:                 my @matches;
                   1807:                 if ($reply =~ /\n/) {
                   1808:                     @matches = split(/\n/,$reply);
                   1809:                 } else {
                   1810:                     @matches = split(/\&/,$reply);
                   1811:                 }
1.899     raeburn  1812:                 foreach my $match (@matches) {
                   1813:                     my ($uname,$udom,%userhash);
1.911     raeburn  1814:                     foreach my $entry (split(/:/,$match)) {
                   1815:                         my ($key,$value) =
                   1816:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1817:                         $userhash{$key} = $value;
                   1818:                         if ($key eq 'username') {
                   1819:                             $uname = $value;
                   1820:                         } elsif ($key eq 'domain') {
                   1821:                             $udom = $value;
1.911     raeburn  1822:                         }
1.899     raeburn  1823:                     }
                   1824:                     $results{$uname.':'.$udom} = \%userhash;
                   1825:                 }
                   1826:             }
                   1827:         }
                   1828:     }
                   1829:     return %results;
                   1830: }
                   1831: 
1.912     raeburn  1832: sub get_instuser {
                   1833:     my ($udom,$uname,$id) = @_;
                   1834:     my $homeserver = &domain($udom,'primary');
                   1835:     my ($outcome,%results);
                   1836:     if ($homeserver ne '') {
                   1837:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1838:                            &escape($id).':'.&escape($udom),$homeserver);
                   1839:         my $host=&hostname($homeserver);
                   1840:         if ($queryid !~/^\Q$host\E\_/) {
                   1841:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1842:             return;
                   1843:         }
                   1844:         my $response = &get_query_reply($queryid);
                   1845:         my $maxtries = 5;
                   1846:         my $tries = 1;
                   1847:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1848:             $response = &get_query_reply($queryid);
                   1849:             $tries ++;
                   1850:         }
                   1851:         if (!&error($response) && $response ne 'refused') {
                   1852:             if ($response eq 'unavailable') {
                   1853:                 $outcome = $response;
                   1854:             } else {
                   1855:                 $outcome = 'ok';
                   1856:                 my @matches = split(/\n/,$response);
                   1857:                 foreach my $match (@matches) {
                   1858:                     my ($key,$value) = split(/=/,$match);
                   1859:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1860:                 }
                   1861:             }
                   1862:         }
                   1863:     }
                   1864:     my %userinfo;
                   1865:     if (ref($results{$uname}) eq 'HASH') {
                   1866:         %userinfo = %{$results{$uname}};
                   1867:     } 
                   1868:     return ($outcome,%userinfo);
                   1869: }
                   1870: 
                   1871: sub inst_rulecheck {
1.923     raeburn  1872:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1873:     my %returnhash;
                   1874:     if ($udom ne '') {
                   1875:         if (ref($rules) eq 'ARRAY') {
                   1876:             @{$rules} = map {&escape($_);} (@{$rules});
                   1877:             my $rulestr = join(':',@{$rules});
                   1878:             my $homeserver=&domain($udom,'primary');
                   1879:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1880:                 my $response;
                   1881:                 if ($item eq 'username') {                
                   1882:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1883:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1884:                                               $homeserver));
1.923     raeburn  1885:                 } elsif ($item eq 'id') {
                   1886:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1887:                                               ':'.&escape($id).':'.$rulestr,
                   1888:                                               $homeserver));
1.945     raeburn  1889:                 } elsif ($item eq 'selfcreate') {
                   1890:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1891:                                                &escape($udom).':'.&escape($uname).
                   1892:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1893:                 }
1.912     raeburn  1894:                 if ($response ne 'refused') {
                   1895:                     my @pairs=split(/\&/,$response);
                   1896:                     foreach my $item (@pairs) {
                   1897:                         my ($key,$value)=split(/=/,$item,2);
                   1898:                         $key = &unescape($key);
                   1899:                         next if ($key =~ /^error: 2 /);
                   1900:                         $returnhash{$key}=&thaw_unescape($value);
                   1901:                     }
                   1902:                 }
                   1903:             }
                   1904:         }
                   1905:     }
                   1906:     return %returnhash;
                   1907: }
                   1908: 
                   1909: sub inst_userrules {
1.923     raeburn  1910:     my ($udom,$check) = @_;
1.912     raeburn  1911:     my (%ruleshash,@ruleorder);
                   1912:     if ($udom ne '') {
                   1913:         my $homeserver=&domain($udom,'primary');
                   1914:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1915:             my $response;
                   1916:             if ($check eq 'id') {
                   1917:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1918:                                  $homeserver);
1.943     raeburn  1919:             } elsif ($check eq 'email') {
                   1920:                 $response=&reply('instemailrules:'.&escape($udom),
                   1921:                                  $homeserver);
1.923     raeburn  1922:             } else {
                   1923:                 $response=&reply('instuserrules:'.&escape($udom),
                   1924:                                  $homeserver);
                   1925:             }
1.912     raeburn  1926:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1927:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1928:                 ($response ne 'no_such_host')) {
                   1929:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1930:                 my @pairs=split(/\&/,$hashitems);
                   1931:                 foreach my $item (@pairs) {
                   1932:                     my ($key,$value)=split(/=/,$item,2);
                   1933:                     $key = &unescape($key);
                   1934:                     next if ($key =~ /^error: 2 /);
                   1935:                     $ruleshash{$key}=&thaw_unescape($value);
                   1936:                 }
                   1937:                 my @esc_order = split(/\&/,$orderitems);
                   1938:                 foreach my $item (@esc_order) {
                   1939:                     push(@ruleorder,&unescape($item));
                   1940:                 }
                   1941:             }
                   1942:         }
                   1943:     }
                   1944:     return (\%ruleshash,\@ruleorder);
                   1945: }
                   1946: 
1.976     raeburn  1947: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1948: 
                   1949: sub get_domain_defaults {
                   1950:     my ($domain) = @_;
                   1951:     my $cachetime = 60*60*24;
                   1952:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1953:     if (defined($cached)) {
                   1954:         if (ref($result) eq 'HASH') {
                   1955:             return %{$result};
                   1956:         }
                   1957:     }
                   1958:     my %domdefaults;
                   1959:     my %domconfig =
1.989     raeburn  1960:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1961:                                   'requestcourses','inststatus',
1.1183    raeburn  1962:                                   'coursedefaults','usersessions',
                   1963:                                   'requestauthor'],$domain);
1.943     raeburn  1964:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1965:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1966:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1967:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1968:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1969:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1970:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1971:     } else {
                   1972:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1973:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1974:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1975:     }
1.976     raeburn  1976:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1977:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1978:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1979:         } else {
                   1980:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1981:         } 
1.1177    raeburn  1982:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1983:         foreach my $item (@usertools) {
                   1984:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1985:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1986:             }
                   1987:         }
                   1988:     }
1.985     raeburn  1989:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1990:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1991:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1992:         }
                   1993:     }
1.1183    raeburn  1994:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   1995:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   1996:     }
1.989     raeburn  1997:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1998:         foreach my $item ('inststatustypes','inststatusorder') {
                   1999:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2000:         }
                   2001:     }
1.1047    raeburn  2002:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   2003:         foreach my $item ('canuse_pdfforms') {
                   2004:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   2005:         }
                   2006:     }
1.1073    raeburn  2007:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2008:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2009:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2010:         }
                   2011:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2012:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2013:         }
                   2014:     }
1.943     raeburn  2015:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   2016:                                   $cachetime);
                   2017:     return %domdefaults;
                   2018: }
                   2019: 
1.344     www      2020: # --------------------------------------------------- Assign a key to a student
                   2021: 
                   2022: sub assign_access_key {
1.364     www      2023: #
                   2024: # a valid key looks like uname:udom#comments
                   2025: # comments are being appended
                   2026: #
1.498     www      2027:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2028:     $kdom=
1.620     albertel 2029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2030:     $knum=
1.620     albertel 2031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2032:     $cdom=
1.620     albertel 2033:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2034:     $cnum=
1.620     albertel 2035:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2036:     $udom=$env{'user.name'} unless (defined($udom));
                   2037:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2038:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2039:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2040:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2041:                                                   # assigned to this person
                   2042:                                                   # - this should not happen,
1.345     www      2043:                                                   # unless something went wrong
                   2044:                                                   # the first time around
                   2045: # ready to assign
1.364     www      2046:         $logentry=$1.'; '.$logentry;
1.496     www      2047:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2048:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2049: # key now belongs to user
1.346     www      2050: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2051:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2052:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2053:                 return 'ok';
                   2054:             } else {
                   2055:                 return 
                   2056:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2057: 	    }
                   2058:         } else {
                   2059:             return 'error: Could not assign key, try again later.';
                   2060:         }
1.364     www      2061:     } elsif (!$existing{$ckey}) {
1.345     www      2062: # the key does not exist
                   2063: 	return 'error: The key does not exist';
                   2064:     } else {
                   2065: # the key is somebody else's
                   2066: 	return 'error: The key is already in use';
                   2067:     }
1.344     www      2068: }
                   2069: 
1.364     www      2070: # ------------------------------------------ put an additional comment on a key
                   2071: 
                   2072: sub comment_access_key {
                   2073: #
                   2074: # a valid key looks like uname:udom#comments
                   2075: # comments are being appended
                   2076: #
                   2077:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2078:     $cdom=
1.620     albertel 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2080:     $cnum=
1.620     albertel 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2082:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2083:     if ($existing{$ckey}) {
                   2084:         $existing{$ckey}.='; '.$logentry;
                   2085: # ready to assign
1.367     www      2086:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2087:                                                  $cdom,$cnum) eq 'ok') {
                   2088: 	    return 'ok';
                   2089:         } else {
                   2090: 	    return 'error: Count not store comment.';
                   2091:         }
                   2092:     } else {
                   2093: # the key does not exist
                   2094: 	return 'error: The key does not exist';
                   2095:     }
                   2096: }
                   2097: 
1.344     www      2098: # ------------------------------------------------------ Generate a set of keys
                   2099: 
                   2100: sub generate_access_keys {
1.364     www      2101:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2102:     $cdom=
1.620     albertel 2103:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2104:     $cnum=
1.620     albertel 2105:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2106:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2107:     unless (($cdom) && ($cnum)) { return 0; }
                   2108:     if ($number>10000) { return 0; }
                   2109:     sleep(2); # make sure don't get same seed twice
                   2110:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2111:     my $total=0;
                   2112:     for (my $i=1;$i<=$number;$i++) {
                   2113:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2114:                   sprintf("%lx",int(100000*rand)).'-'.
                   2115:                   sprintf("%lx",int(100000*rand));
                   2116:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2117:        $newkey=~s/0/h/g; # and also 0 and O
                   2118:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2119:        if ($existing{$newkey}) {
                   2120:            $i--;
                   2121:        } else {
1.364     www      2122: 	  if (&put('accesskeys',
                   2123:               { $newkey => '# generated '.localtime().
1.620     albertel 2124:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2125:                            '; '.$logentry },
                   2126: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2127:               $total++;
                   2128: 	  }
                   2129:        }
                   2130:     }
1.620     albertel 2131:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2132:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2133:     return $total;
                   2134: }
                   2135: 
                   2136: # ------------------------------------------------------- Validate an accesskey
                   2137: 
                   2138: sub validate_access_key {
                   2139:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2140:     $cdom=
1.620     albertel 2141:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2142:     $cnum=
1.620     albertel 2143:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2144:     $udom=$env{'user.domain'} unless (defined($udom));
                   2145:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2146:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2147:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2148: }
                   2149: 
                   2150: # ------------------------------------- Find the section of student in a course
1.652     albertel 2151: sub devalidate_getsection_cache {
                   2152:     my ($udom,$unam,$courseid)=@_;
                   2153:     my $hashid="$udom:$unam:$courseid";
                   2154:     &devalidate_cache_new('getsection',$hashid);
                   2155: }
1.298     matthew  2156: 
1.815     albertel 2157: sub courseid_to_courseurl {
                   2158:     my ($courseid) = @_;
                   2159:     #already url style courseid
                   2160:     return $courseid if ($courseid =~ m{^/});
                   2161: 
                   2162:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2163: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2164: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2165: 	return "/$cdom/$cnum";
                   2166:     }
                   2167: 
                   2168:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2169:     if (exists($courseinfo{'num'})) {
                   2170: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2171:     }
                   2172: 
                   2173:     return undef;
                   2174: }
                   2175: 
1.298     matthew  2176: sub getsection {
                   2177:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2178:     my $cachetime=1800;
1.551     albertel 2179: 
                   2180:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2181:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2182:     if (defined($cached)) { return $result; }
                   2183: 
1.298     matthew  2184:     my %Pending; 
                   2185:     my %Expired;
                   2186:     #
                   2187:     # Each role can either have not started yet (pending), be active, 
                   2188:     #    or have expired.
                   2189:     #
                   2190:     # If there is an active role, we are done.
                   2191:     #
                   2192:     # If there is more than one role which has not started yet, 
                   2193:     #     choose the one which will start sooner
                   2194:     # If there is one role which has not started yet, return it.
                   2195:     #
                   2196:     # If there is more than one expired role, choose the one which ended last.
                   2197:     # If there is a role which has expired, return it.
                   2198:     #
1.815     albertel 2199:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2200:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2201:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2202:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2203:         my $section=$1;
                   2204:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2205:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2206:         my $now=time;
1.548     albertel 2207:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2208:             $Expired{$end}=$section;
                   2209:             next;
                   2210:         }
1.548     albertel 2211:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2212:             $Pending{$start}=$section;
                   2213:             next;
                   2214:         }
1.599     albertel 2215:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2216:     }
                   2217:     #
                   2218:     # Presumedly there will be few matching roles from the above
                   2219:     # loop and the sorting time will be negligible.
                   2220:     if (scalar(keys(%Pending))) {
                   2221:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2222:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2223:     } 
                   2224:     if (scalar(keys(%Expired))) {
                   2225:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2226:         my $time = pop(@sorted);
1.599     albertel 2227:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2228:     }
1.599     albertel 2229:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2230: }
1.70      www      2231: 
1.599     albertel 2232: sub save_cache {
                   2233:     &purge_remembered();
1.722     albertel 2234:     #&Apache::loncommon::validate_page();
1.620     albertel 2235:     undef(%env);
1.780     albertel 2236:     undef($env_loaded);
1.599     albertel 2237: }
1.452     albertel 2238: 
1.599     albertel 2239: my $to_remember=-1;
                   2240: my %remembered;
                   2241: my %accessed;
                   2242: my $kicks=0;
                   2243: my $hits=0;
1.849     albertel 2244: sub make_key {
                   2245:     my ($name,$id) = @_;
1.872     albertel 2246:     if (length($id) > 65 
                   2247: 	&& length(&escape($id)) > 200) {
                   2248: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2249:     }
1.849     albertel 2250:     return &escape($name.':'.$id);
                   2251: }
                   2252: 
1.599     albertel 2253: sub devalidate_cache_new {
                   2254:     my ($name,$id,$debug) = @_;
                   2255:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2256:     $id=&make_key($name,$id);
1.599     albertel 2257:     $memcache->delete($id);
                   2258:     delete($remembered{$id});
                   2259:     delete($accessed{$id});
                   2260: }
                   2261: 
                   2262: sub is_cached_new {
                   2263:     my ($name,$id,$debug) = @_;
1.849     albertel 2264:     $id=&make_key($name,$id);
1.599     albertel 2265:     if (exists($remembered{$id})) {
1.1133    foxr     2266: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2267: 	$accessed{$id}=[&gettimeofday()];
                   2268: 	$hits++;
                   2269: 	return ($remembered{$id},1);
                   2270:     }
                   2271:     my $value = $memcache->get($id);
                   2272:     if (!(defined($value))) {
                   2273: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2274: 	return (undef,undef);
1.416     albertel 2275:     }
1.599     albertel 2276:     if ($value eq '__undef__') {
                   2277: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2278: 	$value=undef;
                   2279:     }
                   2280:     &make_room($id,$value,$debug);
                   2281:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2282:     return ($value,1);
                   2283: }
                   2284: 
                   2285: sub do_cache_new {
                   2286:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2287:     $id=&make_key($name,$id);
1.599     albertel 2288:     my $setvalue=$value;
                   2289:     if (!defined($setvalue)) {
                   2290: 	$setvalue='__undef__';
                   2291:     }
1.623     albertel 2292:     if (!defined($time) ) {
                   2293: 	$time=600;
                   2294:     }
1.599     albertel 2295:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2296:     my $result = $memcache->set($id,$setvalue,$time);
                   2297:     if (! $result) {
1.872     albertel 2298: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2299: 	$memcache->disconnect_all();
1.872     albertel 2300:     }
1.600     albertel 2301:     # need to make a copy of $value
1.919     albertel 2302:     &make_room($id,$value,$debug);
1.599     albertel 2303:     return $value;
                   2304: }
                   2305: 
                   2306: sub make_room {
                   2307:     my ($id,$value,$debug)=@_;
1.919     albertel 2308: 
                   2309:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2310:                                     : $value;
1.599     albertel 2311:     if ($to_remember<0) { return; }
                   2312:     $accessed{$id}=[&gettimeofday()];
                   2313:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2314:     my $to_kick;
                   2315:     my $max_time=0;
                   2316:     foreach my $other (keys(%accessed)) {
                   2317: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2318: 	    $to_kick=$other;
                   2319: 	    $max_time=&tv_interval($accessed{$other});
                   2320: 	}
                   2321:     }
                   2322:     delete($remembered{$to_kick});
                   2323:     delete($accessed{$to_kick});
                   2324:     $kicks++;
                   2325:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2326:     return;
                   2327: }
                   2328: 
1.599     albertel 2329: sub purge_remembered {
1.604     albertel 2330:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2331:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2332:     undef(%remembered);
                   2333:     undef(%accessed);
1.428     albertel 2334: }
1.70      www      2335: # ------------------------------------- Read an entry from a user's environment
                   2336: 
                   2337: sub userenvironment {
                   2338:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2339:     my $items;
                   2340:     foreach my $item (@what) {
                   2341:         $items.=&escape($item).'&';
                   2342:     }
                   2343:     $items=~s/\&$//;
1.70      www      2344:     my %returnhash=();
1.1009    raeburn  2345:     my $uhome = &homeserver($unam,$udom);
                   2346:     unless ($uhome eq 'no_host') {
                   2347:         my @answer=split(/\&/, 
                   2348:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2349:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2350:             return %returnhash;
                   2351:         }
1.1009    raeburn  2352:         my $i;
                   2353:         for ($i=0;$i<=$#what;$i++) {
                   2354: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2355:         }
1.70      www      2356:     }
                   2357:     return %returnhash;
1.1       albertel 2358: }
                   2359: 
1.617     albertel 2360: # ---------------------------------------------------------- Get a studentphoto
                   2361: sub studentphoto {
                   2362:     my ($udom,$unam,$ext) = @_;
                   2363:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2364:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2365:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2366:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2367:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2368:             } else {
                   2369:                 my ($result,$perm_reqd)=
1.707     albertel 2370: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2371:                 if ($result eq 'ok') {
                   2372:                     if (!($perm_reqd eq 'yes')) {
                   2373:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2374:                     }
                   2375:                 }
                   2376:             }
                   2377:         }
                   2378:     } else {
                   2379:         my ($result,$perm_reqd) = 
1.707     albertel 2380: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2381:         if ($result eq 'ok') {
                   2382:             if (!($perm_reqd eq 'yes')) {
                   2383:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2384:             }
                   2385:         }
                   2386:     }
                   2387:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2388: }
                   2389: 
                   2390: sub retrievestudentphoto {
                   2391:     my ($udom,$unam,$ext,$type) = @_;
                   2392:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2393:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2394:     if ($ret eq 'ok') {
                   2395:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2396:         if ($type eq 'thumbnail') {
                   2397:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2398:         }
                   2399:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2400:         return $tokenurl;
                   2401:     } else {
                   2402:         if ($type eq 'thumbnail') {
                   2403:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2404:         } else { 
                   2405:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2406:         }
1.617     albertel 2407:     }
                   2408: }
                   2409: 
1.263     www      2410: # -------------------------------------------------------------------- New chat
                   2411: 
                   2412: sub chatsend {
1.724     raeburn  2413:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2414:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2415:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2416:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2417:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2418: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2419: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2420: }
                   2421: 
                   2422: # ------------------------------------------ Find current version of a resource
                   2423: 
                   2424: sub getversion {
                   2425:     my $fname=&clutter(shift);
1.1189    raeburn  2426:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2427:     return &currentversion(&filelocation('',$fname));
                   2428: }
                   2429: 
                   2430: sub currentversion {
                   2431:     my $fname=shift;
                   2432:     my $author=$fname;
                   2433:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2434:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2435:     my $home=&homeserver($uname,$udom);
1.292     www      2436:     if ($home eq 'no_host') { 
                   2437:         return -1; 
                   2438:     }
1.1112    www      2439:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2440:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2441: 	return -1;
                   2442:     }
1.1112    www      2443:     return $answer;
1.263     www      2444: }
                   2445: 
1.1111    www      2446: #
                   2447: # Return special version number of resource if set by override, empty otherwise
                   2448: #
                   2449: sub usedversion {
                   2450:     my $fname=shift;
                   2451:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2452:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2453:     if ($urlversion) { return $urlversion; }
                   2454:     return '';
                   2455: }
                   2456: 
1.1       albertel 2457: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2458: 
1.1       albertel 2459: sub subscribe {
                   2460:     my $fname=shift;
1.761     raeburn  2461:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2462:     $fname=~s/[\n\r]//g;
1.1       albertel 2463:     my $author=$fname;
                   2464:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2465:     my ($udom,$uname)=split(/\//,$author);
                   2466:     my $home=homeserver($uname,$udom);
1.335     albertel 2467:     if ($home eq 'no_host') {
                   2468:         return 'not_found';
1.1       albertel 2469:     }
                   2470:     my $answer=reply("sub:$fname",$home);
1.64      www      2471:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2472: 	$answer.=' by '.$home;
                   2473:     }
1.1       albertel 2474:     return $answer;
                   2475: }
                   2476:     
1.8       www      2477: # -------------------------------------------------------------- Replicate file
                   2478: 
                   2479: sub repcopy {
                   2480:     my $filename=shift;
1.23      www      2481:     $filename=~s/\/+/\//g;
1.1142    raeburn  2482:     my $londocroot = $perlvar{'lonDocRoot'};
                   2483:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2484:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2485:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2486: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2487: 	return &repcopy_userfile($filename);
                   2488:     }
1.532     albertel 2489:     $filename=~s/[\n\r]//g;
1.8       www      2490:     my $transname="$filename.in.transfer";
1.828     www      2491: # FIXME: this should flock
1.607     raeburn  2492:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2493:     my $remoteurl=subscribe($filename);
1.64      www      2494:     if ($remoteurl =~ /^con_lost by/) {
                   2495: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2496:            return 'unavailable';
1.8       www      2497:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2498: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2499: 	   return 'not_found';
1.64      www      2500:     } elsif ($remoteurl =~ /^rejected by/) {
                   2501: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2502:            return 'forbidden';
1.20      www      2503:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2504:            return 'ok';
1.8       www      2505:     } else {
1.290     www      2506:         my $author=$filename;
                   2507:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2508:         my ($udom,$uname)=split(/\//,$author);
                   2509:         my $home=homeserver($uname,$udom);
                   2510:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2511:            my @parts=split(/\//,$filename);
                   2512:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2513:            if ($path ne "$londocroot/res") {
1.8       www      2514:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2515: 	       return 'bad_request';
1.8       www      2516:            }
                   2517:            my $count;
                   2518:            for ($count=5;$count<$#parts;$count++) {
                   2519:                $path.="/$parts[$count]";
                   2520:                if ((-e $path)!=1) {
                   2521: 		   mkdir($path,0777);
                   2522:                }
                   2523:            }
                   2524:            my $ua=new LWP::UserAgent;
                   2525:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2526:            my $response=$ua->request($request,$transname);
                   2527:            if ($response->is_error()) {
                   2528: 	       unlink($transname);
                   2529:                my $message=$response->status_line;
1.672     albertel 2530:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2531:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2532:                return 'unavailable';
1.8       www      2533:            } else {
1.16      www      2534: 	       if ($remoteurl!~/\.meta$/) {
                   2535:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2536:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2537:                   if ($mresponse->is_error()) {
                   2538: 		      unlink($filename.'.meta');
                   2539:                       &logthis(
1.672     albertel 2540:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2541:                   }
                   2542: 	       }
1.8       www      2543:                rename($transname,$filename);
1.607     raeburn  2544:                return 'ok';
1.8       www      2545:            }
1.290     www      2546:        }
1.8       www      2547:     }
1.330     www      2548: }
                   2549: 
                   2550: # ------------------------------------------------ Get server side include body
                   2551: sub ssi_body {
1.381     albertel 2552:     my ($filelink,%form)=@_;
1.606     matthew  2553:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2554:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2555:     }
1.953     www      2556:     my $output='';
                   2557:     my $response;
1.980     raeburn  2558:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2559:        ($output,$response)=&externalssi($filelink);
1.953     www      2560:     } else {
1.1004    droeschl 2561:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2562:        $filelink .= 'inhibitmenu=yes';
1.953     www      2563:        ($output,$response)=&ssi($filelink,%form);
                   2564:     }
1.778     albertel 2565:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2566:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2567:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2568:     if (wantarray) {
                   2569:         return ($output, $response);
                   2570:     } else {
                   2571:         return $output;
                   2572:     }
1.8       www      2573: }
                   2574: 
1.15      www      2575: # --------------------------------------------------------- Server Side Include
                   2576: 
1.782     albertel 2577: sub absolute_url {
                   2578:     my ($host_name) = @_;
                   2579:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2580:     if ($host_name eq '') {
                   2581: 	$host_name = $ENV{'SERVER_NAME'};
                   2582:     }
                   2583:     return $protocol.$host_name;
                   2584: }
                   2585: 
1.942     foxr     2586: #
                   2587: #   Server side include.
                   2588: # Parameters:
                   2589: #  fn     Possibly encrypted resource name/id.
                   2590: #  form   Hash that describes how the rendering should be done
                   2591: #         and other things.
1.944     foxr     2592: # Returns:
1.950     raeburn  2593: #   Scalar context: The content of the response.
                   2594: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2595: #     
1.15      www      2596: sub ssi {
                   2597: 
1.944     foxr     2598:     my ($fn,%form)=@_;
1.15      www      2599:     my $ua=new LWP::UserAgent;
1.23      www      2600:     my $request;
1.711     albertel 2601: 
                   2602:     $form{'no_update_last_known'}=1;
1.895     albertel 2603:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2604:     if (%form) {
1.782     albertel 2605:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2606:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2607:     } else {
1.782     albertel 2608:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2609:     }
                   2610: 
1.15      www      2611:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2612:     my $response= $ua->request($request);
1.1182    foxr     2613:     my $content = $response->content;
                   2614: 
                   2615: 
1.944     foxr     2616:     if (wantarray) {
1.1173    foxr     2617: 	return ($content, $response);
1.944     foxr     2618:     } else {
1.1173    foxr     2619: 	return $content;
1.942     foxr     2620:     }
1.324     www      2621: }
                   2622: 
                   2623: sub externalssi {
                   2624:     my ($url)=@_;
                   2625:     my $ua=new LWP::UserAgent;
                   2626:     my $request=new HTTP::Request('GET',$url);
                   2627:     my $response=$ua->request($request);
1.954     raeburn  2628:     if (wantarray) {
                   2629:         return ($response->content, $response);
                   2630:     } else {
                   2631:         return $response->content;
                   2632:     }
1.15      www      2633: }
1.254     www      2634: 
1.492     albertel 2635: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2636: 
                   2637: sub allowuploaded {
                   2638:     my ($srcurl,$url)=@_;
                   2639:     $url=&clutter(&declutter($url));
                   2640:     my $dir=$url;
                   2641:     $dir=~s/\/[^\/]+$//;
                   2642:     my %httpref=();
                   2643:     my $httpurl=&hreflocation('',$url);
                   2644:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2645:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2646: }
1.477     raeburn  2647: 
1.478     albertel 2648: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2649: # input: action, courseID, current domain, intended
1.637     raeburn  2650: #        path to file, source of file, instruction to parse file for objects,
                   2651: #        ref to hash for embedded objects,
                   2652: #        ref to hash for codebase of java objects.
1.1095    raeburn  2653: #        reference to scalar to accommodate mime type determined
                   2654: #          from File::MMagic if $parser = parse.
1.637     raeburn  2655: #
1.485     raeburn  2656: # output: url to file (if action was uploaddoc), 
                   2657: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2658: #
1.478     albertel 2659: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2660: # course.
1.477     raeburn  2661: #
1.478     albertel 2662: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2663: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2664: #          course's home server.
1.477     raeburn  2665: #
1.478     albertel 2666: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2667: #          be copied from $source (current location) to 
                   2668: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2669: #         and will then be copied to
                   2670: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2671: #         course's home server.
1.485     raeburn  2672: #
1.481     raeburn  2673: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2674: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2675: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2676: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2677: #         in course's home server.
1.637     raeburn  2678: #
1.477     raeburn  2679: 
                   2680: sub process_coursefile {
1.1095    raeburn  2681:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2682:         $mimetype)=@_;
1.477     raeburn  2683:     my $fetchresult;
1.638     albertel 2684:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2685:     if ($action eq 'propagate') {
1.638     albertel 2686:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2687: 			     $home);
1.481     raeburn  2688:     } else {
1.477     raeburn  2689:         my $fpath = '';
                   2690:         my $fname = $file;
1.478     albertel 2691:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2692:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2693:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2694:         if ($action eq 'copy') {
                   2695:             if ($source eq '') {
                   2696:                 $fetchresult = 'no source file';
                   2697:                 return $fetchresult;
                   2698:             } else {
                   2699:                 my $destination = $filepath.'/'.$fname;
                   2700:                 rename($source,$destination);
                   2701:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2702:                                  $home);
1.481     raeburn  2703:             }
                   2704:         } elsif ($action eq 'uploaddoc') {
                   2705:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2706:             print $fh $env{'form.'.$source};
1.481     raeburn  2707:             close($fh);
1.637     raeburn  2708:             if ($parser eq 'parse') {
1.1024    raeburn  2709:                 my $mm = new File::MMagic;
1.1095    raeburn  2710:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2711:                 if ($type eq 'text/html') {
1.1024    raeburn  2712:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2713:                     unless ($parse_result eq 'ok') {
                   2714:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2715:                     }
1.637     raeburn  2716:                 }
1.1095    raeburn  2717:                 if (ref($mimetype)) {
                   2718:                     $$mimetype = $type;
                   2719:                 } 
1.637     raeburn  2720:             }
1.477     raeburn  2721:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2722:                                  $home);
1.481     raeburn  2723:             if ($fetchresult eq 'ok') {
                   2724:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2725:             } else {
                   2726:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2727:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2728:                 return '/adm/notfound.html';
                   2729:             }
1.477     raeburn  2730:         }
                   2731:     }
1.485     raeburn  2732:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2733:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2734:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2735:     }
                   2736:     return $fetchresult;
                   2737: }
                   2738: 
1.637     raeburn  2739: sub build_filepath {
                   2740:     my ($fpath) = @_;
                   2741:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2742:     unless ($fpath eq '') {
                   2743:         my @parts=split('/',$fpath);
                   2744:         foreach my $part (@parts) {
                   2745:             $filepath.= '/'.$part;
                   2746:             if ((-e $filepath)!=1) {
                   2747:                 mkdir($filepath,0777);
                   2748:             }
                   2749:         }
                   2750:     }
                   2751:     return $filepath;
                   2752: }
                   2753: 
                   2754: sub store_edited_file {
1.638     albertel 2755:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2756:     my $file = $primary_url;
                   2757:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2758:     my $fpath = '';
                   2759:     my $fname = $file;
                   2760:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2761:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2762:     my $filepath = &build_filepath($fpath);
                   2763:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2764:     print $fh $content;
                   2765:     close($fh);
1.638     albertel 2766:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2767:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2768: 			  $home);
1.637     raeburn  2769:     if ($$fetchresult eq 'ok') {
                   2770:         return '/uploaded/'.$fpath.'/'.$fname;
                   2771:     } else {
1.638     albertel 2772:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2773: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2774:         return '/adm/notfound.html';
                   2775:     }
                   2776: }
                   2777: 
1.531     albertel 2778: sub clean_filename {
1.831     albertel 2779:     my ($fname,$args)=@_;
1.315     www      2780: # Replace Windows backslashes by forward slashes
1.257     www      2781:     $fname=~s/\\/\//g;
1.831     albertel 2782:     if (!$args->{'keep_path'}) {
                   2783:         # Get rid of everything but the actual filename
                   2784: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2785:     }
1.315     www      2786: # Replace spaces by underscores
                   2787:     $fname=~s/\s+/\_/g;
                   2788: # Replace all other weird characters by nothing
1.831     albertel 2789:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2790: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2791: # numbers
                   2792:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2793:     return $fname;
                   2794: }
1.1051    raeburn  2795: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2796: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2797: # image with the same aspect ratio as the original, but with dimensions which do 
                   2798: # not exceed $resizewidth and $resizeheight.
                   2799:  
1.984     neumanie 2800: sub resizeImage {
1.1051    raeburn  2801:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2802:     my $ima = Image::Magick->new;
                   2803:     my $resized;
                   2804:     if (-e $img_path) {
                   2805:         $ima->Read($img_path);
                   2806:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2807:             my $width = $ima->Get('width');
                   2808:             my $height = $ima->Get('height');
                   2809:             if ($width > $resizewidth) {
                   2810: 	        my $factor = $width/$resizewidth;
                   2811:                 my $newheight = $height/$factor;
                   2812:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2813:                 $resized = 1;
                   2814:             }
                   2815:         }
                   2816:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2817:             my $width = $ima->Get('width');
                   2818:             my $height = $ima->Get('height');
                   2819:             if ($height > $resizeheight) {
                   2820:                 my $factor = $height/$resizeheight;
                   2821:                 my $newwidth = $width/$factor;
                   2822:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2823:                 $resized = 1;
                   2824:             }
                   2825:         }
                   2826:         if ($resized) {
                   2827:             $ima->Write($img_path);
                   2828:         }
                   2829:     }
                   2830:     return;
1.977     amueller 2831: }
                   2832: 
1.608     albertel 2833: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2834: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2835: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2836: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2837: #                                    canceloverwrite, or ''. 
                   2838: #                   if 'coursedoc': upload to the current course
                   2839: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2840: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2841: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2842: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2843: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2844: #        $allfiles - reference to hash for embedded objects
                   2845: #        $codebase - reference to hash for codebase of java objects
                   2846: #        $desuname - username for permanent storage of uploaded file
                   2847: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2848: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2849: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2850: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2851: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2852: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2853: #                    from File::MMagic.
1.858     raeburn  2854: # 
1.686     albertel 2855: # output: url of file in userspace, or error: <message> 
                   2856: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2857: 
1.531     albertel 2858: sub userfileupload {
1.1090    raeburn  2859:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2860:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2861:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2862:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2863:     $fname=&clean_filename($fname);
1.1090    raeburn  2864:     # See if there is anything left
1.257     www      2865:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2866:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2867:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2868:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2869:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2870:         my $now = time;
1.1090    raeburn  2871:         my $filepath;
1.1095    raeburn  2872:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2873:              $filepath = 'tmp/helprequests/'.$now;
                   2874:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2875:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2876:                          '_'.$env{'user.domain'}.'/pending';
                   2877:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2878:             my ($docuname,$docudom);
                   2879:             if ($destudom) {
                   2880:                 $docudom = $destudom;
                   2881:             } else {
                   2882:                 $docudom = $env{'user.domain'};
                   2883:             }
                   2884:             if ($destuname) {
                   2885:                 $docuname = $destuname;
                   2886:             } else {
                   2887:                 $docuname = $env{'user.name'};
                   2888:             }
                   2889:             if (exists($env{'form.group'})) {
                   2890:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2891:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2892:             }
                   2893:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2894:             if ($context eq 'canceloverwrite') {
                   2895:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2896:                 if (-e  $tempfile) {
                   2897:                     my @info = stat($tempfile);
                   2898:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2899:                         unlink($tempfile);
                   2900:                     }
                   2901:                 }
                   2902:                 return;
1.523     raeburn  2903:             }
                   2904:         }
1.1090    raeburn  2905:         # Create the directory if not present
1.741     raeburn  2906:         my @parts=split(/\//,$filepath);
                   2907:         my $fullpath = $perlvar{'lonDaemons'};
                   2908:         for (my $i=0;$i<@parts;$i++) {
                   2909:             $fullpath .= '/'.$parts[$i];
                   2910:             if ((-e $fullpath)!=1) {
                   2911:                 mkdir($fullpath,0777);
                   2912:             }
                   2913:         }
                   2914:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2915:         print $fh $env{'form.'.$formname};
                   2916:         close($fh);
1.1090    raeburn  2917:         if ($context eq 'existingfile') {
                   2918:             my @info = stat($fullpath.'/'.$fname);
                   2919:             return ($fullpath.'/'.$fname,$info[9]);
                   2920:         } else {
                   2921:             return $fullpath.'/'.$fname;
                   2922:         }
1.523     raeburn  2923:     }
1.995     raeburn  2924:     if ($subdir eq 'scantron') {
                   2925:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2926:     } else {
1.995     raeburn  2927:         $fname="$subdir/$fname";
                   2928:     }
1.1090    raeburn  2929:     if ($context eq 'coursedoc') {
1.638     albertel 2930: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2931: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2932:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2933:             return &finishuserfileupload($docuname,$docudom,
                   2934: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2935: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2936:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2937:         } else {
1.620     albertel 2938:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2939:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2940: 				       $fname,$formname,$parser,
1.1095    raeburn  2941: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2942:         }
1.719     banghart 2943:     } elsif (defined($destuname)) {
                   2944:         my $docuname=$destuname;
                   2945:         my $docudom=$destudom;
1.860     raeburn  2946: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2947: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2948:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2949:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2950:     } else {
1.638     albertel 2951:         my $docuname=$env{'user.name'};
                   2952:         my $docudom=$env{'user.domain'};
1.714     raeburn  2953:         if (exists($env{'form.group'})) {
                   2954:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2955:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2956:         }
1.860     raeburn  2957: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2958: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2959:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2960:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2961:     }
1.271     www      2962: }
                   2963: 
                   2964: sub finishuserfileupload {
1.860     raeburn  2965:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2966:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2967:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2968:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2969:   
1.860     raeburn  2970:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2971:     $file=$fname;
                   2972:     if ($fname=~m|/|) {
                   2973:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2974: 	$path.=$fnamepath.'/';
                   2975:     }
1.259     www      2976:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2977:     my $count;
                   2978:     for ($count=4;$count<=$#parts;$count++) {
                   2979:         $filepath.="/$parts[$count]";
                   2980:         if ((-e $filepath)!=1) {
                   2981: 	    mkdir($filepath,0777);
                   2982:         }
                   2983:     }
1.984     neumanie 2984: 
1.258     www      2985: # Save the file
                   2986:     {
1.701     albertel 2987: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2988: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2989: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2990: 	    return '/adm/notfound.html';
                   2991: 	}
1.1090    raeburn  2992:         if ($context eq 'overwrite') {
1.1117    foxr     2993:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2994:             my $target = $filepath.'/'.$file;
                   2995:             if (-e $source) {
                   2996:                 my @info = stat($source);
                   2997:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2998:                     unless (&File::Copy::move($source,$target)) {
                   2999:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3000:                         return "Moving from $source failed";
                   3001:                     }
                   3002:                 } else {
                   3003:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3004:                 }
                   3005:             } else {
                   3006:                 return "Temporary file: $source missing";
                   3007:             }
                   3008:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3009: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3010: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3011: 	    return '/adm/notfound.html';
                   3012: 	}
1.570     albertel 3013: 	close(FH);
1.1051    raeburn  3014:         if ($resizewidth && $resizeheight) {
                   3015:             my $mm = new File::MMagic;
                   3016:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3017:             if ($mime_type =~ m{^image/}) {
                   3018: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3019:             }  
1.977     amueller 3020: 	}
1.258     www      3021:     }
1.1152    raeburn  3022:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3023:         if (ref($mimetype)) {
                   3024:             if ($$mimetype eq '') {
                   3025:                 my $mm = new File::MMagic;
                   3026:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3027:                 $$mimetype = $type;
                   3028:             }
                   3029:         }
                   3030:     }
1.637     raeburn  3031:     if ($parser eq 'parse') {
1.1152    raeburn  3032:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3033:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3034:                                                        $allfiles,$codebase);
                   3035:             unless ($parse_result eq 'ok') {
                   3036:                 &logthis('Failed to parse '.$filepath.$file.
                   3037: 	   	         ' for embedded media: '.$parse_result); 
                   3038:             }
1.637     raeburn  3039:         }
                   3040:     }
1.860     raeburn  3041:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3042:         my $input = $filepath.'/'.$file;
                   3043:         my $output = $filepath.'/'.'tn-'.$file;
                   3044:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3045:         system("convert -sample $thumbsize $input $output");
                   3046:         if (-e $filepath.'/'.'tn-'.$file) {
                   3047:             $fetchthumb  = 1; 
                   3048:         }
                   3049:     }
1.858     raeburn  3050:  
1.259     www      3051: # Notify homeserver to grep it
                   3052: #
1.984     neumanie 3053:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3054:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3055:     if ($fetchresult eq 'ok') {
1.860     raeburn  3056:         if ($fetchthumb) {
                   3057:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3058:             if ($thumbresult ne 'ok') {
                   3059:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3060:                          $docuhome.': '.$thumbresult);
                   3061:             }
                   3062:         }
1.259     www      3063: #
1.258     www      3064: # Return the URL to it
1.494     albertel 3065:         return '/uploaded/'.$path.$file;
1.263     www      3066:     } else {
1.494     albertel 3067:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3068: 		 ': '.$fetchresult);
1.263     www      3069:         return '/adm/notfound.html';
1.858     raeburn  3070:     }
1.493     albertel 3071: }
                   3072: 
1.637     raeburn  3073: sub extract_embedded_items {
1.961     raeburn  3074:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3075:     my @state = ();
1.1164    raeburn  3076:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3077:     my %javafiles = (
                   3078:                       codebase => '',
                   3079:                       code => '',
                   3080:                       archive => ''
                   3081:                     );
                   3082:     my %mediafiles = (
                   3083:                       src => '',
                   3084:                       movie => '',
                   3085:                      );
1.648     raeburn  3086:     my $p;
                   3087:     if ($content) {
                   3088:         $p = HTML::LCParser->new($content);
                   3089:     } else {
1.961     raeburn  3090:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3091:     }
1.641     albertel 3092:     while (my $t=$p->get_token()) {
1.640     albertel 3093: 	if ($t->[0] eq 'S') {
                   3094: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3095: 	    push(@state, $tagname);
1.648     raeburn  3096:             if (lc($tagname) eq 'allow') {
                   3097:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3098:             }
1.640     albertel 3099: 	    if (lc($tagname) eq 'img') {
                   3100: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3101: 	    }
1.886     albertel 3102: 	    if (lc($tagname) eq 'a') {
                   3103: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3104: 	    }
1.645     raeburn  3105:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3106:                 my $src;
1.645     raeburn  3107:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3108:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3109:                 } else {
1.1164    raeburn  3110:                     if ($attr->{'src'} ne '') {
                   3111:                         $src = $attr->{'src'};
                   3112:                         &add_filetype($allfiles,$src,'src');
                   3113:                     }
                   3114:                 }
                   3115:                 my $text = $p->get_trimmed_text();
                   3116:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3117:                     my @swfargs = split(/,/,$1);
                   3118:                     foreach my $item (@swfargs) {
                   3119:                         $item =~ s/["']//g;
                   3120:                         $item =~ s/^\s+//;
                   3121:                         $item =~ s/\s+$//;
                   3122:                     }
                   3123:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3124:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3125:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3126:                         } else {
                   3127:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3128:                         }
                   3129:                     }
1.645     raeburn  3130:                 }
                   3131:             }
                   3132:             if (lc($tagname) eq 'link') {
                   3133:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3134:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3135:                 }
                   3136:             }
1.640     albertel 3137: 	    if (lc($tagname) eq 'object' ||
                   3138: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3139: 		foreach my $item (keys(%javafiles)) {
                   3140: 		    $javafiles{$item} = '';
                   3141: 		}
1.1164    raeburn  3142:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3143:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3144:                 }
1.640     albertel 3145: 	    }
                   3146: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3147: 		my $name = lc($attr->{'name'});
                   3148: 		foreach my $item (keys(%javafiles)) {
                   3149: 		    if ($name eq $item) {
                   3150: 			$javafiles{$item} = $attr->{'value'};
                   3151: 			last;
                   3152: 		    }
                   3153: 		}
1.1164    raeburn  3154:                 my $pathfrom;
1.640     albertel 3155: 		foreach my $item (keys(%mediafiles)) {
                   3156: 		    if ($name eq $item) {
1.1164    raeburn  3157:                         $pathfrom = $attr->{'value'};
                   3158:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3159: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3160: 			last;
                   3161: 		    }
                   3162: 		}
1.1164    raeburn  3163:                 if ($name eq 'flashvars') {
                   3164:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3165:                 }
                   3166:                 if ($pathfrom ne '') {
                   3167:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3168:                                          $pathfrom);
                   3169:                 }
1.640     albertel 3170: 	    }
                   3171: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3172: 		foreach my $item (keys(%javafiles)) {
                   3173: 		    if ($attr->{$item}) {
                   3174: 			$javafiles{$item} = $attr->{$item};
                   3175: 			last;
                   3176: 		    }
                   3177: 		}
                   3178: 		foreach my $item (keys(%mediafiles)) {
                   3179: 		    if ($attr->{$item}) {
                   3180: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3181: 			last;
                   3182: 		    }
                   3183: 		}
1.1164    raeburn  3184:                 if (lc($tagname) eq 'embed') {
                   3185:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3186:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3187:                                              $attr->{'src'});
                   3188:                     }
                   3189:                 }
1.640     albertel 3190: 	    }
1.1164    raeburn  3191:             if ($t->[4] =~ m{/>$}) {
                   3192:                 pop(@state);  
                   3193:             }
1.640     albertel 3194: 	} elsif ($t->[0] eq 'E') {
                   3195: 	    my ($tagname) = ($t->[1]);
                   3196: 	    if ($javafiles{'codebase'} ne '') {
                   3197: 		$javafiles{'codebase'} .= '/';
                   3198: 	    }  
                   3199: 	    if (lc($tagname) eq 'applet' ||
                   3200: 		lc($tagname) eq 'object' ||
                   3201: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3202: 		) {
                   3203: 		foreach my $item (keys(%javafiles)) {
                   3204: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3205: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3206: 			&add_filetype($allfiles,$file,$item);
                   3207: 		    }
                   3208: 		}
                   3209: 	    } 
                   3210: 	    pop @state;
                   3211: 	}
                   3212:     }
1.1164    raeburn  3213:     foreach my $id (sort(keys(%flashvars))) {
                   3214:         if ($shockwave{$id} ne '') {
                   3215:             my @pairs = split(/\&/,$flashvars{$id});
                   3216:             foreach my $pair (@pairs) {
                   3217:                 my ($key,$value) = split(/\=/,$pair);
                   3218:                 if ($key eq 'thumb') {
                   3219:                     &add_filetype($allfiles,$value,$key);
                   3220:                 } elsif ($key eq 'content') {
                   3221:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3222:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3223:                     if ($ext ne '') {
                   3224:                         &add_filetype($allfiles,$path.$value,$ext);
                   3225:                     }
                   3226:                 }
                   3227:             }
                   3228:         }
                   3229:     }
1.637     raeburn  3230:     return 'ok';
                   3231: }
                   3232: 
1.639     albertel 3233: sub add_filetype {
                   3234:     my ($allfiles,$file,$type)=@_;
                   3235:     if (exists($allfiles->{$file})) {
                   3236: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3237: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3238: 	}
                   3239:     } else {
                   3240: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3241:     }
                   3242: }
                   3243: 
1.1164    raeburn  3244: sub embedded_dependency {
                   3245:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3246:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3247:         if (($identifier ne '') &&
                   3248:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3249:             ($pathfrom ne '')) {
                   3250:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3251:             foreach my $dep (@{$related->{$identifier}}) {
                   3252:                 &add_filetype($allfiles,$path.$dep,'object');
                   3253:             }
                   3254:         }
                   3255:     }
                   3256:     return;
                   3257: }
                   3258: 
1.493     albertel 3259: sub removeuploadedurl {
1.984     neumanie 3260:     my ($url)=@_;	
                   3261:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3262:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3263: }
                   3264: 
                   3265: sub removeuserfile {
                   3266:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3267:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3268:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3269:     if ($result eq 'ok') {	
1.798     raeburn  3270:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3271:             my $metafile = $fname.'.meta';
                   3272:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3273: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3274:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3275:             my $sqlresult = 
1.823     albertel 3276:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3277:                                         'portfolio_metadata',$group,
                   3278:                                         'delete');
1.798     raeburn  3279:         }
                   3280:     }
                   3281:     return $result;
1.257     www      3282: }
1.15      www      3283: 
1.530     albertel 3284: sub mkdiruserfile {
                   3285:     my ($docuname,$docudom,$dir)=@_;
                   3286:     my $home=&homeserver($docuname,$docudom);
                   3287:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3288: }
                   3289: 
1.531     albertel 3290: sub renameuserfile {
                   3291:     my ($docuname,$docudom,$old,$new)=@_;
                   3292:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3293:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3294:                         &escape("$old").':'.&escape("$new"),$home);
                   3295:     if ($result eq 'ok') {
                   3296:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3297:             my $oldmeta = $old.'.meta';
                   3298:             my $newmeta = $new.'.meta';
                   3299:             my $metaresult = 
                   3300:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3301: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3302:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3303:             my $sqlresult = 
1.823     albertel 3304:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3305:                                         'portfolio_metadata',$group,
                   3306:                                         'delete');
1.798     raeburn  3307:         }
                   3308:     }
                   3309:     return $result;
1.531     albertel 3310: }
                   3311: 
1.14      www      3312: # ------------------------------------------------------------------------- Log
                   3313: 
                   3314: sub log {
                   3315:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3316:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3317: }
                   3318: 
                   3319: # ------------------------------------------------------------------ Course Log
1.352     www      3320: #
                   3321: # This routine flushes several buffers of non-mission-critical nature
                   3322: #
1.157     www      3323: 
                   3324: sub flushcourselogs {
1.352     www      3325:     &logthis('Flushing log buffers');
                   3326: #
                   3327: # course logs
                   3328: # This is a log of all transactions in a course, which can be used
                   3329: # for data mining purposes
                   3330: #
                   3331: # It also collects the courseid database, which lists last transaction
                   3332: # times and course titles for all courseids
                   3333: #
                   3334:     my %courseidbuffer=();
1.921     raeburn  3335:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3336:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3337: 		          &escape($courselogs{$crsid}),
                   3338: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3339: 	    delete $courselogs{$crsid};
                   3340:         } else {
                   3341:             &logthis('Failed to flush log buffer for '.$crsid);
                   3342:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3343:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3344:                         " exceeded maximum size, deleting.</font>");
                   3345:                delete $courselogs{$crsid};
                   3346:             }
1.352     www      3347:         }
1.920     raeburn  3348:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3349:             'description' => $coursedescrbuf{$crsid},
                   3350:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3351:             'type'        => $coursetypebuf{$crsid},
                   3352:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3353:         };
1.191     harris41 3354:     }
1.352     www      3355: #
                   3356: # Write course id database (reverse lookup) to homeserver of courses 
                   3357: # Is used in pickcourse
                   3358: #
1.840     albertel 3359:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3360:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3361:                                     $courseidbuffer{$crs_home},
                   3362:                                     $crs_home,'timeonly');
1.352     www      3363:     }
                   3364: #
                   3365: # File accesses
                   3366: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3367: #
1.449     matthew  3368:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3369:         if ($entry =~ /___count$/) {
                   3370:             my ($dom,$name);
1.807     albertel 3371:             ($dom,$name,undef)=
1.811     albertel 3372: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3373:             if (! defined($dom) || $dom eq '' || 
                   3374:                 ! defined($name) || $name eq '') {
1.620     albertel 3375:                 my $cid = $env{'request.course.id'};
                   3376:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3377:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3378:             }
1.450     matthew  3379:             my $value = $accesshash{$entry};
                   3380:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3381:             my %temphash=($url => $value);
1.449     matthew  3382:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3383:             if ($result eq 'ok') {
                   3384:                 delete $accesshash{$entry};
                   3385:             }
                   3386:         } else {
1.811     albertel 3387:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3388:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3389:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3390:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3391:                 delete $accesshash{$entry};
                   3392:             }
1.185     www      3393:         }
1.191     harris41 3394:     }
1.352     www      3395: #
                   3396: # Roles
                   3397: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3398: #
1.800     albertel 3399:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3400:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3401: 	    split(/\:/,$entry);
                   3402:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3403:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3404:                 $rudom,$runame) eq 'ok') {
                   3405: 	    delete $userrolehash{$entry};
                   3406:         }
                   3407:     }
1.662     raeburn  3408: #
                   3409: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3410: #
                   3411:     my %domrolebuffer = ();
1.1000    raeburn  3412:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3413:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3414:         if ($domrolebuffer{$rudom}) {
                   3415:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3416:                       '='.&escape($domainrolehash{$entry});
                   3417:         } else {
                   3418:             $domrolebuffer{$rudom}.=&escape($entry).
                   3419:                       '='.&escape($domainrolehash{$entry});
                   3420:         }
                   3421:         delete $domainrolehash{$entry};
                   3422:     }
                   3423:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3424: 	my %servers = &get_servers($dom,'library');
                   3425: 	foreach my $tryserver (keys(%servers)) {
                   3426: 	    unless (&reply('domroleput:'.$dom.':'.
                   3427: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3428: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3429: 	    }
1.662     raeburn  3430:         }
                   3431:     }
1.186     www      3432:     $dumpcount++;
1.157     www      3433: }
                   3434: 
                   3435: sub courselog {
                   3436:     my $what=shift;
1.158     www      3437:     $what=time.':'.$what;
1.620     albertel 3438:     unless ($env{'request.course.id'}) { return ''; }
                   3439:     $coursedombuf{$env{'request.course.id'}}=
                   3440:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3441:     $coursenumbuf{$env{'request.course.id'}}=
                   3442:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3443:     $coursehombuf{$env{'request.course.id'}}=
                   3444:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3445:     $coursedescrbuf{$env{'request.course.id'}}=
                   3446:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3447:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3448:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3449:     $courseownerbuf{$env{'request.course.id'}}=
                   3450:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3451:     $coursetypebuf{$env{'request.course.id'}}=
                   3452:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3453:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3454: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3455:     } else {
1.620     albertel 3456: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3457:     }
1.620     albertel 3458:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3459: 	&flushcourselogs();
                   3460:     }
1.158     www      3461: }
                   3462: 
                   3463: sub courseacclog {
                   3464:     my $fnsymb=shift;
1.620     albertel 3465:     unless ($env{'request.course.id'}) { return ''; }
                   3466:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3467:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3468:         $what.=':POST';
1.583     matthew  3469:         # FIXME: Probably ought to escape things....
1.800     albertel 3470: 	foreach my $key (keys(%env)) {
                   3471:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3472:                 my $formitem = $1;
                   3473:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3474:                     $what.=':'.$formitem.'='.$env{$key};
                   3475:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3476:                     $what.=':'.$formitem.'='.$env{$key};
                   3477:                 }
1.158     www      3478:             }
1.191     harris41 3479:         }
1.583     matthew  3480:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3481:         # FIXME: We should not be depending on a form parameter that someone
                   3482:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3483:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3484:             $what.= ':POST';
                   3485:             # FIXME: Probably ought to escape things....
                   3486:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3487:                                  'crsdiscuss') {
1.620     albertel 3488:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3489:             }
                   3490:         }
1.158     www      3491:     }
                   3492:     &courselog($what);
1.149     www      3493: }
                   3494: 
1.185     www      3495: sub countacc {
                   3496:     my $url=&declutter(shift);
1.458     matthew  3497:     return if (! defined($url) || $url eq '');
1.620     albertel 3498:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3499: #
                   3500: # Mark that this url was used in this course
                   3501: #
1.620     albertel 3502:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3503: #
                   3504: # Increase the access count for this resource in this child process
                   3505: #
1.281     www      3506:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3507:     $accesshash{$key}++;
1.185     www      3508: }
1.349     www      3509: 
1.361     www      3510: sub linklog {
                   3511:     my ($from,$to)=@_;
                   3512:     $from=&declutter($from);
                   3513:     $to=&declutter($to);
                   3514:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3515:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3516: }
1.1160    www      3517: 
                   3518: sub statslog {
                   3519:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3520:     if ($users<2) { return; }
                   3521:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3522:             'course'       => $env{'request.course.id'},
                   3523:             'sections'     => '"all"',
                   3524:             'num_students' => $users,
                   3525:             'part'         => $part,
                   3526:             'symb'         => $symb,
                   3527:             'mean_tries'   => $av_attempts,
                   3528:             'deg_of_diff'  => $degdiff});
                   3529:     foreach my $key (keys(%dynstore)) {
                   3530:         $accesshash{$key}=$dynstore{$key};
                   3531:     }
                   3532: }
1.361     www      3533:   
1.349     www      3534: sub userrolelog {
                   3535:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3536:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3537:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3538:        $userrolehash
                   3539:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3540:                     =$tend.':'.$tstart;
1.662     raeburn  3541:     }
1.1169    droeschl 3542:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3543:        $userrolehash
                   3544:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3545:                     =$tend.':'.$tstart;
                   3546:     }
1.1169    droeschl 3547:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3548:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3549:        $domainrolehash
                   3550:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3551:                     = $tend.':'.$tstart;
                   3552:     }
1.351     www      3553: }
                   3554: 
1.957     raeburn  3555: sub courserolelog {
                   3556:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3557:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3558:         my $cdom = $1;
                   3559:         my $cnum = $2;
                   3560:         my $sec = $3;
                   3561:         my $namespace = 'rolelog';
                   3562:         my %storehash = (
                   3563:                            role    => $trole,
                   3564:                            start   => $tstart,
                   3565:                            end     => $tend,
                   3566:                            selfenroll => $selfenroll,
                   3567:                            context    => $context,
                   3568:                         );
                   3569:         if ($trole eq 'gr') {
                   3570:             $namespace = 'groupslog';
                   3571:             $storehash{'group'} = $sec;
                   3572:         } else {
                   3573:             $storehash{'section'} = $sec;
                   3574:         }
1.1188    raeburn  3575:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3576:                    $domain,$cnum,$cdom);
1.1184    raeburn  3577:         if (($trole ne 'st') || ($sec ne '')) {
                   3578:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3579:         }
                   3580:     }
                   3581:     return;
                   3582: }
                   3583: 
1.1184    raeburn  3584: sub domainrolelog {
                   3585:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3586:     if ($area =~ m{^/($match_domain)/$}) {
                   3587:         my $cdom = $1;
                   3588:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3589:         my $namespace = 'rolelog';
                   3590:         my %storehash = (
                   3591:                            role    => $trole,
                   3592:                            start   => $tstart,
                   3593:                            end     => $tend,
                   3594:                            context => $context,
                   3595:                         );
1.1188    raeburn  3596:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3597:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3598:     }
                   3599:     return;
                   3600: 
                   3601: }
                   3602: 
                   3603: sub coauthorrolelog {
                   3604:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3605:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3606:         my $audom = $1;
                   3607:         my $auname = $2;
                   3608:         my $namespace = 'rolelog';
                   3609:         my %storehash = (
                   3610:                            role    => $trole,
                   3611:                            start   => $tstart,
                   3612:                            end     => $tend,
                   3613:                            context => $context,
                   3614:                         );
1.1188    raeburn  3615:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3616:                    $domain,$auname,$audom);
1.1184    raeburn  3617:     }
                   3618:     return;
                   3619: }
                   3620: 
1.351     www      3621: sub get_course_adv_roles {
1.948     raeburn  3622:     my ($cid,$codes) = @_;
1.620     albertel 3623:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3624:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3625:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3626:     my %nothide=();
1.800     albertel 3627:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3628:         if ($user !~ /:/) {
                   3629: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3630:         } else {
                   3631:             $nothide{$user}=1;
                   3632:         }
1.470     www      3633:     }
1.351     www      3634:     my %returnhash=();
                   3635:     my %dumphash=
                   3636:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3637:     my $now=time;
1.997     raeburn  3638:     my %privileged;
1.1000    raeburn  3639:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3640: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3641:         if (($tstart) && ($tstart<0)) { next; }
                   3642:         if (($tend) && ($tend<$now)) { next; }
                   3643:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3644:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3645: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3646:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3647:             my %dompersonnel =
1.998     raeburn  3648:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3649:             $privileged{$domain} = {};
                   3650:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3651:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3652:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3653:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3654:                         $privileged{$udom}{$uname} = 1;
                   3655:                     }
                   3656:                 }
                   3657:             }
                   3658:         }
                   3659:         if ((exists($privileged{$domain}{$username})) && 
                   3660:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3661: 	if ($role eq 'cr') { next; }
1.948     raeburn  3662:         if ($codes) {
                   3663:             if ($section) { $role .= ':'.$section; }
                   3664:             if ($returnhash{$role}) {
                   3665:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3666:             } else {
                   3667:                 $returnhash{$role}=$username.':'.$domain;
                   3668:             }
1.351     www      3669:         } else {
1.988     raeburn  3670:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3671:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3672:             if ($returnhash{$key}) {
                   3673: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3674:             } else {
                   3675:                 $returnhash{$key}=$username.':'.$domain;
                   3676:             }
1.351     www      3677:         }
1.948     raeburn  3678:     }
1.400     www      3679:     return %returnhash;
                   3680: }
                   3681: 
                   3682: sub get_my_roles {
1.937     raeburn  3683:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3684:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3685:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3686:     my (%dumphash,%nothide);
1.1086    raeburn  3687:     if ($context eq 'userroles') {
1.1166    raeburn  3688:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3689:     } else {
                   3690:         %dumphash=
1.400     www      3691:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3692:         if ($hidepriv) {
                   3693:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3694:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3695:                 if ($user !~ /:/) {
                   3696:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3697:                 } else {
                   3698:                     $nothide{$user} = 1;
                   3699:                 }
                   3700:             }
                   3701:         }
1.858     raeburn  3702:     }
1.400     www      3703:     my %returnhash=();
                   3704:     my $now=time;
1.999     raeburn  3705:     my %privileged;
1.800     albertel 3706:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3707:         my ($role,$tend,$tstart);
                   3708:         if ($context eq 'userroles') {
1.1149    raeburn  3709:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3710: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3711:         } else {
                   3712:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3713:         }
1.400     www      3714:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3715:         my $status = 'active';
1.939     raeburn  3716:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3717:             $status = 'previous';
                   3718:         } 
                   3719:         if (($tstart) && ($now<$tstart)) {
                   3720:             $status = 'future';
                   3721:         }
                   3722:         if (ref($types) eq 'ARRAY') {
                   3723:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3724:                 next;
                   3725:             } 
                   3726:         } else {
                   3727:             if ($status ne 'active') {
                   3728:                 next;
                   3729:             }
                   3730:         }
1.867     raeburn  3731:         my ($rolecode,$username,$domain,$section,$area);
                   3732:         if ($context eq 'userroles') {
1.1186    raeburn  3733:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3734:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3735:         } else {
                   3736:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3737:         }
1.832     raeburn  3738:         if (ref($roledoms) eq 'ARRAY') {
                   3739:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3740:                 next;
                   3741:             }
                   3742:         }
                   3743:         if (ref($roles) eq 'ARRAY') {
                   3744:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3745:                 if ($role =~ /^cr\//) {
                   3746:                     if (!grep(/^cr$/,@{$roles})) {
                   3747:                         next;
                   3748:                     }
1.1104    raeburn  3749:                 } elsif ($role =~ /^gr\//) {
                   3750:                     if (!grep(/^gr$/,@{$roles})) {
                   3751:                         next;
                   3752:                     }
1.922     raeburn  3753:                 } else {
                   3754:                     next;
                   3755:                 }
1.832     raeburn  3756:             }
1.867     raeburn  3757:         }
1.937     raeburn  3758:         if ($hidepriv) {
1.999     raeburn  3759:             if ($context eq 'userroles') {
                   3760:                 if ((&privileged($username,$domain)) &&
                   3761:                     (!$nothide{$username.':'.$domain})) {
                   3762:                     next;
                   3763:                 }
                   3764:             } else {
                   3765:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3766:                     my %dompersonnel =
                   3767:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3768:                     $privileged{$domain} = {};
                   3769:                     if (keys(%dompersonnel)) {
                   3770:                         foreach my $server (keys(%dompersonnel)) {
                   3771:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3772:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3773:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3774:                                     $privileged{$udom}{$uname} = $trole;
                   3775:                                 }
                   3776:                             }
                   3777:                         }
                   3778:                     }
                   3779:                 }
                   3780:                 if (exists($privileged{$domain}{$username})) {
                   3781:                     if (!$nothide{$username.':'.$domain}) {
                   3782:                         next;
                   3783:                     }
                   3784:                 }
1.937     raeburn  3785:             }
                   3786:         }
1.933     raeburn  3787:         if ($withsec) {
                   3788:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3789:                 $tstart.':'.$tend;
                   3790:         } else {
                   3791:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3792:         }
1.832     raeburn  3793:     }
1.373     www      3794:     return %returnhash;
1.399     www      3795: }
                   3796: 
                   3797: # ----------------------------------------------------- Frontpage Announcements
                   3798: #
                   3799: #
                   3800: 
                   3801: sub postannounce {
                   3802:     my ($server,$text)=@_;
1.844     albertel 3803:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3804:     unless ($text=~/\w/) { $text=''; }
                   3805:     return &reply('setannounce:'.&escape($text),$server);
                   3806: }
                   3807: 
                   3808: sub getannounce {
1.448     albertel 3809: 
                   3810:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3811: 	my $announcement='';
1.800     albertel 3812: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3813: 	close($fh);
1.399     www      3814: 	if ($announcement=~/\w/) { 
                   3815: 	    return 
                   3816:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3817:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3818: 	} else {
                   3819: 	    return '';
                   3820: 	}
                   3821:     } else {
                   3822: 	return '';
                   3823:     }
1.351     www      3824: }
1.353     www      3825: 
                   3826: # ---------------------------------------------------------- Course ID routines
                   3827: # Deal with domain's nohist_courseid.db files
                   3828: #
                   3829: 
                   3830: sub courseidput {
1.921     raeburn  3831:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3832:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3833:     my $outcome;
                   3834:     if ($caller eq 'timeonly') {
                   3835:         my $cids = '';
                   3836:         foreach my $item (keys(%$storehash)) {
                   3837:             $cids.=&escape($item).'&';
                   3838:         }
                   3839:         $cids=~s/\&$//;
                   3840:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3841:                           $coursehome);       
                   3842:     } else {
                   3843:         my $items = '';
                   3844:         foreach my $item (keys(%$storehash)) {
                   3845:             $items.= &escape($item).'='.
                   3846:                      &freeze_escape($$storehash{$item}).'&';
                   3847:         }
                   3848:         $items=~s/\&$//;
                   3849:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3850:                           $coursehome);
1.918     raeburn  3851:     }
                   3852:     if ($outcome eq 'unknown_cmd') {
                   3853:         my $what;
                   3854:         foreach my $cid (keys(%$storehash)) {
                   3855:             $what .= &escape($cid).'=';
1.921     raeburn  3856:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3857:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3858:             }
                   3859:             $what =~ s/\:$/&/;
                   3860:         }
                   3861:         $what =~ s/\&$//;  
                   3862:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3863:     } else {
                   3864:         return $outcome;
                   3865:     }
1.353     www      3866: }
                   3867: 
                   3868: sub courseiddump {
1.921     raeburn  3869:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3870:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3871:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3872:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3873:     my $as_hash = 1;
                   3874:     my %returnhash;
                   3875:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3876:     my %libserv = &all_library();
                   3877:     foreach my $tryserver (keys(%libserv)) {
                   3878:         if ( (  $hostidflag == 1 
                   3879: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3880: 	     || (!defined($hostidflag)) ) {
                   3881: 
1.918     raeburn  3882: 	    if (($domfilter eq '') ||
                   3883: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 3884:                 my $rep;
                   3885:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   3886:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   3887:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   3888:                                 &escape($descfilter), &escape($instcodefilter), 
                   3889:                                 &escape($ownerfilter), &escape($coursefilter),
                   3890:                                 &escape($typefilter), &escape($regexp_ok), 
                   3891:                                 $as_hash, &escape($selfenrollonly), 
                   3892:                                 &escape($catfilter), $showhidden, $caller, 
                   3893:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   3894:                                 &escape($createdbefore), &escape($createdafter), 
                   3895:                                 &escape($creationcontext), $domcloner)));
                   3896:                 } else {
                   3897:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3898:                              $sincefilter.':'.&escape($descfilter).':'.
                   3899:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   3900:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   3901:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   3902:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   3903:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   3904:                              &escape($cc_clone).':'.$cloneonly.':'.
                   3905:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   3906:                              &escape($creationcontext).':'.$domcloner,
                   3907:                              $tryserver);
                   3908:                 }
                   3909:                      
1.918     raeburn  3910:                 my @pairs=split(/\&/,$rep);
                   3911:                 foreach my $item (@pairs) {
                   3912:                     my ($key,$value)=split(/\=/,$item,2);
                   3913:                     $key = &unescape($key);
                   3914:                     next if ($key =~ /^error: 2 /);
                   3915:                     my $result = &thaw_unescape($value);
                   3916:                     if (ref($result) eq 'HASH') {
                   3917:                         $returnhash{$key}=$result;
                   3918:                     } else {
1.921     raeburn  3919:                         my @responses = split(/:/,$value);
                   3920:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3921:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3922:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3923:                         }
1.1008    raeburn  3924:                     }
1.353     www      3925:                 }
                   3926:             }
                   3927:         }
                   3928:     }
                   3929:     return %returnhash;
                   3930: }
                   3931: 
1.1055    raeburn  3932: sub courselastaccess {
                   3933:     my ($cdom,$cnum,$hostidref) = @_;
                   3934:     my %returnhash;
                   3935:     if ($cdom && $cnum) {
                   3936:         my $chome = &homeserver($cnum,$cdom);
                   3937:         if ($chome ne 'no_host') {
                   3938:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3939:             &extract_lastaccess(\%returnhash,$rep);
                   3940:         }
                   3941:     } else {
                   3942:         if (!$cdom) { $cdom=''; }
                   3943:         my %libserv = &all_library();
                   3944:         foreach my $tryserver (keys(%libserv)) {
                   3945:             if (ref($hostidref) eq 'ARRAY') {
                   3946:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3947:             } 
                   3948:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3949:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3950:                 &extract_lastaccess(\%returnhash,$rep);
                   3951:             }
                   3952:         }
                   3953:     }
                   3954:     return %returnhash;
                   3955: }
                   3956: 
                   3957: sub extract_lastaccess {
                   3958:     my ($returnhash,$rep) = @_;
                   3959:     if (ref($returnhash) eq 'HASH') {
                   3960:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3961:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3962:                  $rep eq '') {
                   3963:             my @pairs=split(/\&/,$rep);
                   3964:             foreach my $item (@pairs) {
                   3965:                 my ($key,$value)=split(/\=/,$item,2);
                   3966:                 $key = &unescape($key);
                   3967:                 next if ($key =~ /^error: 2 /);
                   3968:                 $returnhash->{$key} = &thaw_unescape($value);
                   3969:             }
                   3970:         }
                   3971:     }
                   3972:     return;
                   3973: }
                   3974: 
1.658     raeburn  3975: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3976: 
                   3977: sub dcmailput {
1.685     raeburn  3978:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3979:     my $status = &Apache::lonnet::critical(
1.740     www      3980:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3981:        &escape($message),$server);
1.662     raeburn  3982:     return $status;
                   3983: }
                   3984: 
1.658     raeburn  3985: sub dcmaildump {
                   3986:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3987:     my %returnhash=();
1.846     albertel 3988: 
                   3989:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3990:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3991:                                                          &escape($enddate).':';
                   3992: 	my @esc_senders=map { &escape($_)} @$senders;
                   3993: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3994: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3995:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3996:             if (($key) && ($value)) {
                   3997:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3998:             }
                   3999:         }
                   4000:     }
                   4001:     return %returnhash;
                   4002: }
1.662     raeburn  4003: # ---------------------------------------------------------- Domain roles
                   4004: 
                   4005: sub get_domain_roles {
                   4006:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4007:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4008:         $startdate = '.';
                   4009:     }
1.1018    raeburn  4010:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4011:         $enddate = '.';
                   4012:     }
1.922     raeburn  4013:     my $rolelist;
                   4014:     if (ref($roles) eq 'ARRAY') {
                   4015:         $rolelist = join(':',@{$roles});
                   4016:     }
1.662     raeburn  4017:     my %personnel = ();
1.841     albertel 4018: 
                   4019:     my %servers = &get_servers($dom,'library');
                   4020:     foreach my $tryserver (keys(%servers)) {
                   4021: 	%{$personnel{$tryserver}}=();
                   4022: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4023: 					    &escape($startdate).':'.
                   4024: 					    &escape($enddate).':'.
                   4025: 					    &escape($rolelist), $tryserver))) {
                   4026: 	    my ($key,$value) = split(/\=/,$line,2);
                   4027: 	    if (($key) && ($value)) {
                   4028: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4029: 	    }
                   4030: 	}
1.662     raeburn  4031:     }
                   4032:     return %personnel;
                   4033: }
1.658     raeburn  4034: 
1.1057    www      4035: # ----------------------------------------------------------- Interval timing 
1.149     www      4036: 
1.1153    www      4037: {
                   4038: # Caches needed for speedup of navmaps
                   4039: # We don't want to cache this for very long at all (5 seconds at most)
                   4040: # 
                   4041: # The user for whom we cache
                   4042: my $cachedkey='';
                   4043: # The cached times for this user
                   4044: my %cachedtimes=();
                   4045: # When this was last done
                   4046: my $cachedtime=();
                   4047: 
                   4048: sub load_all_first_access {
1.1154    raeburn  4049:     my ($uname,$udom)=@_;
1.1156    www      4050:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4051:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4052:         return;
                   4053:     }
                   4054:     $cachedtime=time;
                   4055:     $cachedkey=$uname.':'.$udom;
                   4056:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4057: }
                   4058: 
1.504     albertel 4059: sub get_first_access {
1.1162    raeburn  4060:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4061:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4062:     if ($argsymb) { $symb=$argsymb; }
                   4063:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4064:     if ($argmap) { $map = $argmap; }
1.926     albertel 4065:     if ($type eq 'course') {
                   4066: 	$res='course';
                   4067:     } elsif ($type eq 'map') {
1.588     albertel 4068: 	$res=&symbread($map);
                   4069:     } else {
                   4070: 	$res=$symb;
                   4071:     }
1.1153    www      4072:     &load_all_first_access($uname,$udom);
                   4073:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4074: }
                   4075: 
                   4076: sub set_first_access {
1.1162    raeburn  4077:     my ($type,$interval)=@_;
1.790     albertel 4078:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4079:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4080:     if ($type eq 'course') {
                   4081: 	$res='course';
                   4082:     } elsif ($type eq 'map') {
1.588     albertel 4083: 	$res=&symbread($map);
                   4084:     } else {
                   4085: 	$res=$symb;
                   4086:     }
1.1153    www      4087:     $cachedkey='';
1.1162    raeburn  4088:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4089:     if (!$firstaccess) {
1.1162    raeburn  4090:         my $start = time;
                   4091: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4092:                           $udom,$uname);
                   4093:         if ($putres eq 'ok') {
                   4094:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4095:                  $udom,$uname); 
                   4096:             &appenv(
                   4097:                      {
                   4098:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4099:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4100:                      }
                   4101:                   );
                   4102:         }
                   4103:         return $putres;
1.505     albertel 4104:     }
                   4105:     return 'already_set';
1.504     albertel 4106: }
1.1153    www      4107: }
1.110     www      4108: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4109: 
                   4110: sub expirespread {
                   4111:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4112:     my $cid=$env{'request.course.id'}; 
1.110     www      4113:     if ($cid) {
                   4114:        my $now=time;
                   4115:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4116:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4117:                             $env{'course.'.$cid.'.num'}.
1.110     www      4118: 	        	    ':nohist_expirationdates:'.
                   4119:                             &escape($key).'='.$now,
1.620     albertel 4120:                             $env{'course.'.$cid.'.home'})
1.110     www      4121:     }
                   4122:     return 'ok';
1.14      www      4123: }
                   4124: 
1.109     www      4125: # ----------------------------------------------------- Devalidate Spreadsheets
                   4126: 
                   4127: sub devalidate {
1.325     www      4128:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4129:     my $cid=$env{'request.course.id'}; 
1.109     www      4130:     if ($cid) {
1.391     matthew  4131:         # delete the stored spreadsheets for
                   4132:         # - the student level sheet of this user in course's homespace
                   4133:         # - the assessment level sheet for this resource 
                   4134:         #   for this user in user's homespace
1.553     albertel 4135: 	# - current conditional state info
1.325     www      4136: 	my $key=$uname.':'.$udom.':';
1.109     www      4137:         my $status=
1.299     matthew  4138: 	    &del('nohist_calculatedsheets',
1.391     matthew  4139: 		 [$key.'studentcalc:'],
1.620     albertel 4140: 		 $env{'course.'.$cid.'.domain'},
                   4141: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4142: 		.' '.
                   4143: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4144: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4145:         unless ($status eq 'ok ok') {
                   4146:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4147:                     $uname.' at '.$udom.' for '.
1.109     www      4148: 		    $symb.': '.$status);
1.133     albertel 4149:         }
1.553     albertel 4150: 	&delenv('user.state.'.$cid);
1.109     www      4151:     }
                   4152: }
                   4153: 
1.265     albertel 4154: sub get_scalar {
                   4155:     my ($string,$end) = @_;
                   4156:     my $value;
                   4157:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4158: 	$value = $1;
                   4159:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4160: 	$value = $1;
                   4161:     }
                   4162:     return &unescape($value);
                   4163: }
                   4164: 
                   4165: sub array2str {
                   4166:   my (@array) = @_;
                   4167:   my $result=&arrayref2str(\@array);
                   4168:   $result=~s/^__ARRAY_REF__//;
                   4169:   $result=~s/__END_ARRAY_REF__$//;
                   4170:   return $result;
                   4171: }
                   4172: 
1.204     albertel 4173: sub arrayref2str {
                   4174:   my ($arrayref) = @_;
1.265     albertel 4175:   my $result='__ARRAY_REF__';
1.204     albertel 4176:   foreach my $elem (@$arrayref) {
1.265     albertel 4177:     if(ref($elem) eq 'ARRAY') {
                   4178:       $result.=&arrayref2str($elem).'&';
                   4179:     } elsif(ref($elem) eq 'HASH') {
                   4180:       $result.=&hashref2str($elem).'&';
                   4181:     } elsif(ref($elem)) {
                   4182:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4183:     } else {
                   4184:       $result.=&escape($elem).'&';
                   4185:     }
                   4186:   }
                   4187:   $result=~s/\&$//;
1.265     albertel 4188:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4189:   return $result;
                   4190: }
                   4191: 
1.168     albertel 4192: sub hash2str {
1.204     albertel 4193:   my (%hash) = @_;
                   4194:   my $result=&hashref2str(\%hash);
1.265     albertel 4195:   $result=~s/^__HASH_REF__//;
                   4196:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4197:   return $result;
                   4198: }
                   4199: 
                   4200: sub hashref2str {
                   4201:   my ($hashref)=@_;
1.265     albertel 4202:   my $result='__HASH_REF__';
1.800     albertel 4203:   foreach my $key (sort(keys(%$hashref))) {
                   4204:     if (ref($key) eq 'ARRAY') {
                   4205:       $result.=&arrayref2str($key).'=';
                   4206:     } elsif (ref($key) eq 'HASH') {
                   4207:       $result.=&hashref2str($key).'=';
                   4208:     } elsif (ref($key)) {
1.265     albertel 4209:       $result.='=';
1.800     albertel 4210:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4211:     } else {
1.1132    raeburn  4212: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4213:     }
                   4214: 
1.800     albertel 4215:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4216:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4217:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4218:       $result.=&hashref2str($hashref->{$key}).'&';
                   4219:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4220:        $result.='&';
1.800     albertel 4221:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4222:     } else {
1.800     albertel 4223:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4224:     }
                   4225:   }
1.168     albertel 4226:   $result=~s/\&$//;
1.265     albertel 4227:   $result .= '__END_HASH_REF__';
1.168     albertel 4228:   return $result;
                   4229: }
                   4230: 
                   4231: sub str2hash {
1.265     albertel 4232:     my ($string)=@_;
                   4233:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4234:     return %$hash;
                   4235: }
                   4236: 
                   4237: sub str2hashref {
1.168     albertel 4238:   my ($string) = @_;
1.265     albertel 4239: 
                   4240:   my %hash;
                   4241: 
                   4242:   if($string !~ /^__HASH_REF__/) {
                   4243:       if (! ($string eq '' || !defined($string))) {
                   4244: 	  $hash{'error'}='Not hash reference';
                   4245:       }
                   4246:       return (\%hash, $string);
                   4247:   }
                   4248: 
                   4249:   $string =~ s/^__HASH_REF__//;
                   4250: 
                   4251:   while($string !~ /^__END_HASH_REF__/) {
                   4252:       #key
                   4253:       my $key='';
                   4254:       if($string =~ /^__HASH_REF__/) {
                   4255:           ($key, $string)=&str2hashref($string);
                   4256:           if(defined($key->{'error'})) {
                   4257:               $hash{'error'}='Bad data';
                   4258:               return (\%hash, $string);
                   4259:           }
                   4260:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4261:           ($key, $string)=&str2arrayref($string);
                   4262:           if($key->[0] eq 'Array reference error') {
                   4263:               $hash{'error'}='Bad data';
                   4264:               return (\%hash, $string);
                   4265:           }
                   4266:       } else {
                   4267:           $string =~ s/^(.*?)=//;
1.267     albertel 4268: 	  $key=&unescape($1);
1.265     albertel 4269:       }
                   4270:       $string =~ s/^=//;
                   4271: 
                   4272:       #value
                   4273:       my $value='';
                   4274:       if($string =~ /^__HASH_REF__/) {
                   4275:           ($value, $string)=&str2hashref($string);
                   4276:           if(defined($value->{'error'})) {
                   4277:               $hash{'error'}='Bad data';
                   4278:               return (\%hash, $string);
                   4279:           }
                   4280:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4281:           ($value, $string)=&str2arrayref($string);
                   4282:           if($value->[0] eq 'Array reference error') {
                   4283:               $hash{'error'}='Bad data';
                   4284:               return (\%hash, $string);
                   4285:           }
                   4286:       } else {
                   4287: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4288:       }
                   4289:       $string =~ s/^&//;
                   4290: 
                   4291:       $hash{$key}=$value;
1.204     albertel 4292:   }
1.265     albertel 4293: 
                   4294:   $string =~ s/^__END_HASH_REF__//;
                   4295: 
                   4296:   return (\%hash, $string);
1.204     albertel 4297: }
                   4298: 
                   4299: sub str2array {
1.265     albertel 4300:     my ($string)=@_;
                   4301:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4302:     return @$array;
                   4303: }
                   4304: 
                   4305: sub str2arrayref {
1.204     albertel 4306:   my ($string) = @_;
1.265     albertel 4307:   my @array;
                   4308: 
                   4309:   if($string !~ /^__ARRAY_REF__/) {
                   4310:       if (! ($string eq '' || !defined($string))) {
                   4311: 	  $array[0]='Array reference error';
                   4312:       }
                   4313:       return (\@array, $string);
                   4314:   }
                   4315: 
                   4316:   $string =~ s/^__ARRAY_REF__//;
                   4317: 
                   4318:   while($string !~ /^__END_ARRAY_REF__/) {
                   4319:       my $value='';
                   4320:       if($string =~ /^__HASH_REF__/) {
                   4321:           ($value, $string)=&str2hashref($string);
                   4322:           if(defined($value->{'error'})) {
                   4323:               $array[0] ='Array reference error';
                   4324:               return (\@array, $string);
                   4325:           }
                   4326:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4327:           ($value, $string)=&str2arrayref($string);
                   4328:           if($value->[0] eq 'Array reference error') {
                   4329:               $array[0] ='Array reference error';
                   4330:               return (\@array, $string);
                   4331:           }
                   4332:       } else {
                   4333: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4334:       }
                   4335:       $string =~ s/^&//;
                   4336: 
                   4337:       push(@array, $value);
1.191     harris41 4338:   }
1.265     albertel 4339: 
                   4340:   $string =~ s/^__END_ARRAY_REF__//;
                   4341: 
                   4342:   return (\@array, $string);
1.168     albertel 4343: }
                   4344: 
1.167     albertel 4345: # -------------------------------------------------------------------Temp Store
                   4346: 
1.168     albertel 4347: sub tmpreset {
                   4348:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4349:   if (!$symb) {
                   4350:     $symb=&symbread();
1.620     albertel 4351:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4352:   }
                   4353:   $symb=escape($symb);
                   4354: 
1.620     albertel 4355:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4356:   $namespace=~s/\//\_/g;
                   4357:   $namespace=~s/\W//g;
                   4358: 
1.620     albertel 4359:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4360:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4361:   if ($domain eq 'public' && $stuname eq 'public') {
                   4362:       $stuname=$ENV{'REMOTE_ADDR'};
                   4363:   }
1.1117    foxr     4364:   my $path=LONCAPA::tempdir();
1.168     albertel 4365:   my %hash;
                   4366:   if (tie(%hash,'GDBM_File',
                   4367: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4368: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4369:     foreach my $key (keys(%hash)) {
1.180     albertel 4370:       if ($key=~ /:$symb/) {
1.168     albertel 4371: 	delete($hash{$key});
                   4372:       }
                   4373:     }
                   4374:   }
                   4375: }
                   4376: 
1.167     albertel 4377: sub tmpstore {
1.168     albertel 4378:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4379: 
                   4380:   if (!$symb) {
                   4381:     $symb=&symbread();
1.620     albertel 4382:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4383:   }
                   4384:   $symb=escape($symb);
                   4385: 
                   4386:   if (!$namespace) {
                   4387:     # I don't think we would ever want to store this for a course.
                   4388:     # it seems this will only be used if we don't have a course.
1.620     albertel 4389:     #$namespace=$env{'request.course.id'};
1.168     albertel 4390:     #if (!$namespace) {
1.620     albertel 4391:       $namespace=$env{'request.state'};
1.168     albertel 4392:     #}
                   4393:   }
                   4394:   $namespace=~s/\//\_/g;
                   4395:   $namespace=~s/\W//g;
1.620     albertel 4396:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4397:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4398:   if ($domain eq 'public' && $stuname eq 'public') {
                   4399:       $stuname=$ENV{'REMOTE_ADDR'};
                   4400:   }
1.168     albertel 4401:   my $now=time;
                   4402:   my %hash;
1.1117    foxr     4403:   my $path=LONCAPA::tempdir();
1.168     albertel 4404:   if (tie(%hash,'GDBM_File',
                   4405: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4406: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4407:     $hash{"version:$symb"}++;
                   4408:     my $version=$hash{"version:$symb"};
                   4409:     my $allkeys=''; 
                   4410:     foreach my $key (keys(%$storehash)) {
                   4411:       $allkeys.=$key.':';
1.591     albertel 4412:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4413:     }
                   4414:     $hash{"$version:$symb:timestamp"}=$now;
                   4415:     $allkeys.='timestamp';
                   4416:     $hash{"$version:keys:$symb"}=$allkeys;
                   4417:     if (untie(%hash)) {
                   4418:       return 'ok';
                   4419:     } else {
                   4420:       return "error:$!";
                   4421:     }
                   4422:   } else {
                   4423:     return "error:$!";
                   4424:   }
                   4425: }
1.167     albertel 4426: 
1.168     albertel 4427: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4428: 
1.168     albertel 4429: sub tmprestore {
                   4430:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4431: 
1.168     albertel 4432:   if (!$symb) {
                   4433:     $symb=&symbread();
1.620     albertel 4434:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4435:   }
                   4436:   $symb=escape($symb);
                   4437: 
1.620     albertel 4438:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4439: 
1.620     albertel 4440:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4441:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4442:   if ($domain eq 'public' && $stuname eq 'public') {
                   4443:       $stuname=$ENV{'REMOTE_ADDR'};
                   4444:   }
1.168     albertel 4445:   my %returnhash;
                   4446:   $namespace=~s/\//\_/g;
                   4447:   $namespace=~s/\W//g;
                   4448:   my %hash;
1.1117    foxr     4449:   my $path=LONCAPA::tempdir();
1.168     albertel 4450:   if (tie(%hash,'GDBM_File',
                   4451: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4452: 	  &GDBM_READER(),0640)) {
1.168     albertel 4453:     my $version=$hash{"version:$symb"};
                   4454:     $returnhash{'version'}=$version;
                   4455:     my $scope;
                   4456:     for ($scope=1;$scope<=$version;$scope++) {
                   4457:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4458:       my @keys=split(/:/,$vkeys);
                   4459:       my $key;
                   4460:       $returnhash{"$scope:keys"}=$vkeys;
                   4461:       foreach $key (@keys) {
1.591     albertel 4462: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4463: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4464:       }
                   4465:     }
1.168     albertel 4466:     if (!(untie(%hash))) {
                   4467:       return "error:$!";
                   4468:     }
                   4469:   } else {
                   4470:     return "error:$!";
                   4471:   }
                   4472:   return %returnhash;
1.167     albertel 4473: }
                   4474: 
1.9       www      4475: # ----------------------------------------------------------------------- Store
                   4476: 
                   4477: sub store {
1.124     www      4478:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4479:     my $home='';
                   4480: 
1.168     albertel 4481:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4482: 
1.213     www      4483:     $symb=&symbclean($symb);
1.122     albertel 4484:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4485: 
1.620     albertel 4486:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4487:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4488: 
                   4489:     &devalidate($symb,$stuname,$domain);
1.109     www      4490: 
                   4491:     $symb=escape($symb);
1.187     www      4492:     if (!$namespace) { 
1.620     albertel 4493:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4494:           return ''; 
                   4495:        } 
                   4496:     }
1.620     albertel 4497:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4498: 
                   4499:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4500:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4501: 
1.12      www      4502:     my $namevalue='';
1.800     albertel 4503:     foreach my $key (keys(%$storehash)) {
                   4504:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4505:     }
1.12      www      4506:     $namevalue=~s/\&$//;
1.187     www      4507:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4508:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4509: }
                   4510: 
1.47      www      4511: # -------------------------------------------------------------- Critical Store
                   4512: 
                   4513: sub cstore {
1.124     www      4514:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4515:     my $home='';
                   4516: 
1.168     albertel 4517:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4518: 
1.213     www      4519:     $symb=&symbclean($symb);
1.122     albertel 4520:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4521: 
1.620     albertel 4522:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4523:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4524: 
                   4525:     &devalidate($symb,$stuname,$domain);
1.109     www      4526: 
                   4527:     $symb=escape($symb);
1.187     www      4528:     if (!$namespace) { 
1.620     albertel 4529:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4530:           return ''; 
                   4531:        } 
                   4532:     }
1.620     albertel 4533:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4534: 
                   4535:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4536:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4537: 
1.47      www      4538:     my $namevalue='';
1.800     albertel 4539:     foreach my $key (keys(%$storehash)) {
                   4540:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4541:     }
1.47      www      4542:     $namevalue=~s/\&$//;
1.187     www      4543:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4544:     return critical
                   4545:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4546: }
                   4547: 
1.9       www      4548: # --------------------------------------------------------------------- Restore
                   4549: 
                   4550: sub restore {
1.124     www      4551:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4552:     my $home='';
                   4553: 
1.168     albertel 4554:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4555: 
1.122     albertel 4556:     if (!$symb) {
                   4557:       unless ($symb=escape(&symbread())) { return ''; }
                   4558:     } else {
1.213     www      4559:       $symb=&escape(&symbclean($symb));
1.122     albertel 4560:     }
1.188     www      4561:     if (!$namespace) { 
1.620     albertel 4562:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4563:           return ''; 
                   4564:        } 
                   4565:     }
1.620     albertel 4566:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4567:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4568:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4569:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4570: 
1.12      www      4571:     my %returnhash=();
1.800     albertel 4572:     foreach my $line (split(/\&/,$answer)) {
                   4573: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4574:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4575:     }
1.75      www      4576:     my $version;
                   4577:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4578:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4579:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4580:        }
1.75      www      4581:     }
1.13      www      4582:     return %returnhash;
1.34      www      4583: }
                   4584: 
                   4585: # ---------------------------------------------------------- Course Description
1.1118    foxr     4586: #
                   4587: #  
1.34      www      4588: 
                   4589: sub coursedescription {
1.731     albertel 4590:     my ($courseid,$args)=@_;
1.34      www      4591:     $courseid=~s/^\///;
1.49      www      4592:     $courseid=~s/\_/\//g;
1.34      www      4593:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4594:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4595:     my $normalid=$cdomain.'_'.$cnum;
                   4596:     # need to always cache even if we get errors otherwise we keep 
                   4597:     # trying and trying and trying to get the course description.
                   4598:     my %envhash=();
                   4599:     my %returnhash=();
1.731     albertel 4600:     
                   4601:     my $expiretime=600;
                   4602:     if ($env{'request.course.id'} eq $normalid) {
                   4603: 	$expiretime=120;
                   4604:     }
                   4605: 
                   4606:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4607:     if (!$args->{'freshen_cache'}
                   4608: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4609: 	foreach my $key (keys(%env)) {
                   4610: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4611: 	    my ($setting) = $1;
                   4612: 	    $returnhash{$setting} = $env{$key};
                   4613: 	}
                   4614: 	return %returnhash;
                   4615:     }
                   4616: 
1.1118    foxr     4617:     # get the data again
                   4618: 
1.731     albertel 4619:     if (!$args->{'one_time'}) {
                   4620: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4621:     }
1.811     albertel 4622: 
1.34      www      4623:     if ($chome ne 'no_host') {
1.302     albertel 4624:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4625:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4626: 	   my $username = $env{'user.name'}; # Defult username
                   4627: 	   if(defined $args->{'user'}) {
                   4628: 	       $username = $args->{'user'};
                   4629: 	   }
1.129     albertel 4630:            $returnhash{'home'}= $chome;
                   4631: 	   $returnhash{'domain'} = $cdomain;
                   4632: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4633:            if (!defined($returnhash{'type'})) {
                   4634:                $returnhash{'type'} = 'Course';
                   4635:            }
1.130     albertel 4636:            while (my ($name,$value) = each %returnhash) {
1.53      www      4637:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4638:            }
1.270     www      4639:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4640:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4641: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4642:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4643:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4644:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4645:        }
                   4646:     }
1.731     albertel 4647:     if (!$args->{'one_time'}) {
1.949     raeburn  4648: 	&appenv(\%envhash);
1.731     albertel 4649:     }
1.302     albertel 4650:     return %returnhash;
1.461     www      4651: }
                   4652: 
1.1080    raeburn  4653: sub update_released_required {
                   4654:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4655:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4656:         $cid = $env{'request.course.id'};
                   4657:         $cdom = $env{'course.'.$cid.'.domain'};
                   4658:         $cnum = $env{'course.'.$cid.'.num'};
                   4659:         $chome = $env{'course.'.$cid.'.home'};
                   4660:     }
                   4661:     if ($needsrelease) {
                   4662:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4663:         my $needsupdate;
                   4664:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4665:             $needsupdate = 1;
                   4666:         } else {
                   4667:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4668:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4669:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4670:                 $needsupdate = 1;
                   4671:             }
                   4672:         }
                   4673:         if ($needsupdate) {
                   4674:             my %needshash = (
                   4675:                              'internal.releaserequired' => $needsrelease,
                   4676:                             );
                   4677:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4678:             if ($putresult eq 'ok') {
                   4679:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4680:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4681:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4682:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4683:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4684:                 }
                   4685:             }
                   4686:         }
                   4687:     }
                   4688:     return;
                   4689: }
                   4690: 
1.461     www      4691: # -------------------------------------------------See if a user is privileged
                   4692: 
                   4693: sub privileged {
                   4694:     my ($username,$domain)=@_;
1.1170    droeschl 4695: 
                   4696:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4697:     my $now = time;
                   4698: 
                   4699:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4700:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4701:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4702:                 return 1 unless ($tend && $tend < $now) 
                   4703:                     or ($tstart && $tstart > $now);
                   4704:             }
1.461     www      4705: 	}
1.1170    droeschl 4706: 
1.461     www      4707:     return 0;
1.9       www      4708: }
1.1       albertel 4709: 
1.103     harris41 4710: # -------------------------------------------------------- Get user privileges
1.11      www      4711: 
                   4712: sub rolesinit {
1.1169    droeschl 4713:     my ($domain, $username) = @_;
                   4714:     my %userroles = ('user.login.time' => time);
                   4715:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4716: 
                   4717:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4718:     # also, blocking can be triggered by an activating timer
                   4719:     # it's saved in the user's %env.
                   4720:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4721:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4722:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4723:         %timerintchk, %timerintenv);
                   4724: 
1.1162    raeburn  4725:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4726:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4727:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4728:     }
1.1169    droeschl 4729: 
1.1162    raeburn  4730:     foreach my $key (keys(%timerinterval)) {
                   4731:         my ($cid,$rest) = split(/\0/,$key);
                   4732:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4733:     }
1.1169    droeschl 4734: 
1.11      www      4735:     my %allroles=();
1.1162    raeburn  4736:     my %allgroups=();
1.11      www      4737: 
1.1169    droeschl 4738:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4739:         my $role = $rolesdump{$area};
                   4740:         $area =~ s/\_\w\w$//;
                   4741: 
                   4742:         my ($trole, $tend, $tstart, $group_privs);
                   4743: 
                   4744:         if ($role =~ /^cr/) {
                   4745:         # Custom role, defined by a user 
                   4746:         # e.g., user.role.cr/msu/smith/mynewrole
                   4747:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4748:                 $trole = $1;
                   4749:                 ($tend, $tstart) = split('_', $2);
                   4750:             } else {
                   4751:                 $trole = $role;
                   4752:             }
                   4753:         } elsif ($role =~ m|^gr/|) {
                   4754:         # Role of member in a group, defined within a course/community
                   4755:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4756:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4757:             next if $tstart eq '-1';
                   4758:             ($trole, $group_privs) = split(/\//, $trole);
                   4759:             $group_privs = &unescape($group_privs);
                   4760:         } else {
                   4761:         # Just a normal role, defined in roles.tab
                   4762:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4763:         }
                   4764: 
                   4765:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4766:                  $username);
                   4767:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4768: 
                   4769:         # role expired or not available yet?
                   4770:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4771:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4772: 
                   4773:         next if $area eq '' or $trole eq '';
                   4774: 
                   4775:         my $spec = "$trole.$area";
                   4776:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4777: 
                   4778:         if ($trole =~ /^cr\//) {
                   4779:         # Custom role, defined by a user
                   4780:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4781:         } elsif ($trole eq 'gr') {
                   4782:         # Role of a member in a group, defined within a course/community
                   4783:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4784:             next;
                   4785:         } else {
                   4786:         # Normal role, defined in roles.tab
                   4787:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4788:         }
                   4789: 
                   4790:         my $cid = $tdomain.'_'.$trest;
                   4791:         unless ($firstaccchk{$cid}) {
                   4792:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4793:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4794:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4795:                         $coursetimerstarts{$cid}{$item}; 
                   4796:                 }
                   4797:             }
                   4798:             $firstaccchk{$cid} = 1;
                   4799:         }
                   4800:         unless ($timerintchk{$cid}) {
                   4801:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4802:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4803:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4804:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4805:                 }
1.12      www      4806:             }
1.1169    droeschl 4807:             $timerintchk{$cid} = 1;
1.191     harris41 4808:         }
1.11      www      4809:     }
1.1169    droeschl 4810: 
                   4811:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4812:         \%allroles, \%allgroups);
                   4813:     $env{'user.adv'} = $userroles{'user.adv'};
                   4814: 
1.1162    raeburn  4815:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4816: }
                   4817: 
1.567     raeburn  4818: sub set_arearole {
                   4819:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4820: # log the associated role with the area
                   4821:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4822:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4823: }
                   4824: 
                   4825: sub custom_roleprivs {
                   4826:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4827:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4828:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4829:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4830:         my ($rdummy,$roledef)=
                   4831:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4832:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4833:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4834:             if (defined($syspriv)) {
1.1043    raeburn  4835:                 if ($trest =~ /^$match_community$/) {
                   4836:                     $syspriv =~ s/bre\&S//; 
                   4837:                 }
1.567     raeburn  4838:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4839:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4840:             }
                   4841:             if ($tdomain ne '') {
                   4842:                 if (defined($dompriv)) {
                   4843:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4844:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4845:                 }
                   4846:                 if (($trest ne '') && (defined($coursepriv))) {
                   4847:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4848:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4849:                 }
                   4850:             }
                   4851:         }
                   4852:     }
                   4853: }
                   4854: 
1.678     raeburn  4855: sub group_roleprivs {
                   4856:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4857:     my $access = 1;
                   4858:     my $now = time;
                   4859:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4860:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4861:     if ($access) {
1.811     albertel 4862:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4863:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4864:     }
                   4865: }
1.567     raeburn  4866: 
                   4867: sub standard_roleprivs {
                   4868:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4869:     if (defined($pr{$trole.':s'})) {
                   4870:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4871:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4872:     }
                   4873:     if ($tdomain ne '') {
                   4874:         if (defined($pr{$trole.':d'})) {
                   4875:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4876:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4877:         }
                   4878:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4879:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4880:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4881:         }
                   4882:     }
                   4883: }
                   4884: 
                   4885: sub set_userprivs {
1.1064    raeburn  4886:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4887:     my $author=0;
                   4888:     my $adv=0;
1.678     raeburn  4889:     my %grouproles = ();
                   4890:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4891:         my @groupkeys; 
1.1000    raeburn  4892:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4893:             push(@groupkeys,$role);
                   4894:         }
                   4895:         if (ref($groups_roles) eq 'HASH') {
                   4896:             foreach my $key (keys(%{$groups_roles})) {
                   4897:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4898:                     push(@groupkeys,$key);
                   4899:                 }
                   4900:             }
                   4901:         }
                   4902:         if (@groupkeys > 0) {
                   4903:             foreach my $role (@groupkeys) {
                   4904:                 my ($trole,$area,$sec,$extendedarea);
                   4905:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4906:                     $trole = $1;
                   4907:                     $area = $2;
                   4908:                     $sec = $3;
                   4909:                     $extendedarea = $area.$sec;
                   4910:                     if (exists($$allgroups{$area})) {
                   4911:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4912:                             my $spec = $trole.'.'.$extendedarea;
                   4913:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4914:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4915:                         }
1.678     raeburn  4916:                     }
                   4917:                 }
                   4918:             }
                   4919:         }
                   4920:     }
1.800     albertel 4921:     foreach my $group (keys(%grouproles)) {
                   4922:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4923:     }
1.800     albertel 4924:     foreach my $role (keys(%{$allroles})) {
                   4925:         my %thesepriv;
1.941     raeburn  4926:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4927:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4928:             if ($item ne '') {
                   4929:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4930:                 if ($restrictions eq '') {
                   4931:                     $thesepriv{$privilege}='F';
                   4932:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4933:                     $thesepriv{$privilege}.=$restrictions;
                   4934:                 }
                   4935:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4936:             }
                   4937:         }
                   4938:         my $thesestr='';
1.1104    raeburn  4939:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4940: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4941: 	}
                   4942:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4943:     }
                   4944:     return ($author,$adv);
                   4945: }
                   4946: 
1.994     raeburn  4947: sub role_status {
1.1104    raeburn  4948:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4949:     my @pwhere = ();
                   4950:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4951:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4952:         unless (!defined($$role) || $$role eq '') {
                   4953:             $$where=join('.',@pwhere);
                   4954:             $$trolecode=$$role.'.'.$$where;
                   4955:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4956:             $$tstatus='is';
1.1104    raeburn  4957:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4958:                 $$tstatus='future';
1.1034    raeburn  4959:                 if ($$tstart<$now) {
                   4960:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4961:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4962:                             my (%allroles,%allgroups,$group_privs,
                   4963:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4964:                             my %userroles = (
                   4965:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4966:                             );
1.1064    raeburn  4967:                             @rolecodes = ('cm'); 
1.1002    raeburn  4968:                             my $spec=$$role.'.'.$$where;
                   4969:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4970:                             if ($$role =~ /^cr\//) {
                   4971:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4972:                                 push(@rolecodes,'cr');
1.1002    raeburn  4973:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4974:                                 push(@rolecodes,$$role);
1.1002    raeburn  4975:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4976:                                                     $env{'user.name'});
1.1064    raeburn  4977:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4978:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4979:                                 $group_privs = &unescape($group_privs);
                   4980:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4981:                                 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  4982:                                 &get_groups_roles($tdomain,$trest,
                   4983:                                                   \%course_roles,\@rolecodes,
                   4984:                                                   \%groups_roles);
1.1002    raeburn  4985:                             } else {
1.1064    raeburn  4986:                                 push(@rolecodes,$$role);
1.1002    raeburn  4987:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4988:                             }
1.1064    raeburn  4989:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4990:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4991:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4992:                         }
                   4993:                     }
1.1034    raeburn  4994:                     $$tstatus = 'is';
1.1002    raeburn  4995:                 }
1.994     raeburn  4996:             }
                   4997:             if ($$tend) {
1.1104    raeburn  4998:                 if ($$tend<$update) {
1.994     raeburn  4999:                     $$tstatus='expired';
                   5000:                 } elsif ($$tend<$now) {
                   5001:                     $$tstatus='will_not';
                   5002:                 }
                   5003:             }
                   5004:         }
                   5005:     }
                   5006: }
                   5007: 
1.1104    raeburn  5008: sub get_groups_roles {
                   5009:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5010:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5011:                   (ref($rolecodes) eq 'ARRAY') && 
                   5012:                   (ref($groups_roles) eq 'HASH')); 
                   5013:     if (keys(%{$cdom_courseroles}) > 0) {
                   5014:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5015:         if ($cdom ne '' && $cnum ne '') {
                   5016:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5017:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5018:                     my $crsrole = $1;
                   5019:                     my $crssec = $2;
                   5020:                     if ($crsrole =~ /^cr/) {
                   5021:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5022:                             push(@{$rolecodes},'cr');
                   5023:                         }
                   5024:                     } else {
                   5025:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5026:                             push(@{$rolecodes},$crsrole);
                   5027:                         }
                   5028:                     }
                   5029:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5030:                     if ($crssec ne '') {
                   5031:                         $rolekey .= "/$crssec";
                   5032:                     }
                   5033:                     $rolekey .= './';
                   5034:                     $groups_roles->{$rolekey} = $rolecodes;
                   5035:                 }
                   5036:             }
                   5037:         }
                   5038:     }
                   5039:     return;
                   5040: }
                   5041: 
                   5042: sub delete_env_groupprivs {
                   5043:     my ($where,$courseroles,$possroles) = @_;
                   5044:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5045:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5046:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5047:         %{$courseroles->{$udom}} =
                   5048:             &get_my_roles('','','userroles',['active'],
                   5049:                           $possroles,[$udom],1);
                   5050:     }
                   5051:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5052:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5053:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5054:             my $area = '/'.$cdom.'/'.$cnum;
                   5055:             my $privkey = "user.priv.$crsrole.$area";
                   5056:             if ($crssec ne '') {
                   5057:                 $privkey .= '/'.$crssec;
                   5058:             }
                   5059:             $privkey .= ".$area/$group";
                   5060:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5061:         }
                   5062:     }
                   5063:     return;
                   5064: }
                   5065: 
1.994     raeburn  5066: sub check_adhoc_privs {
1.1104    raeburn  5067:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5068:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5069:     my $setprivs;
1.994     raeburn  5070:     if ($env{$cckey}) {
                   5071:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5072:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5073:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5074:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5075:             $setprivs = 1;
1.994     raeburn  5076:         }
                   5077:     } else {
1.1088    raeburn  5078:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5079:         $setprivs = 1;
1.994     raeburn  5080:     }
1.1185    raeburn  5081:     return $setprivs;
1.994     raeburn  5082: }
                   5083: 
                   5084: sub set_adhoc_privileges {
                   5085: # role can be cc or ca
1.1088    raeburn  5086:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5087:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5088:     my $spec = $role.'.'.$area;
                   5089:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5090:                                   $env{'user.name'});
                   5091:     my %ccrole = ();
                   5092:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5093:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5094:     &appenv(\%userroles,[$role,'cm']);
                   5095:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5096:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5097:         &appenv( {'request.role'        => $spec,
                   5098:                   'request.role.domain' => $dcdom,
                   5099:                   'request.course.sec'  => ''
                   5100:                  }
                   5101:                );
                   5102:         my $tadv=0;
                   5103:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5104:         &appenv({'request.role.adv'    => $tadv});
                   5105:     }
1.994     raeburn  5106: }
                   5107: 
1.12      www      5108: # --------------------------------------------------------------- get interface
                   5109: 
                   5110: sub get {
1.131     albertel 5111:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5112:    my $items='';
1.800     albertel 5113:    foreach my $item (@$storearr) {
                   5114:        $items.=&escape($item).'&';
1.191     harris41 5115:    }
1.12      www      5116:    $items=~s/\&$//;
1.620     albertel 5117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5118:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5119:    my $uhome=&homeserver($uname,$udomain);
                   5120: 
1.133     albertel 5121:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5122:    my @pairs=split(/\&/,$rep);
1.273     albertel 5123:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5124:      return @pairs;
                   5125:    }
1.15      www      5126:    my %returnhash=();
1.42      www      5127:    my $i=0;
1.800     albertel 5128:    foreach my $item (@$storearr) {
                   5129:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5130:       $i++;
1.191     harris41 5131:    }
1.15      www      5132:    return %returnhash;
1.27      www      5133: }
                   5134: 
                   5135: # --------------------------------------------------------------- del interface
                   5136: 
                   5137: sub del {
1.133     albertel 5138:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5139:    my $items='';
1.800     albertel 5140:    foreach my $item (@$storearr) {
                   5141:        $items.=&escape($item).'&';
1.191     harris41 5142:    }
1.984     neumanie 5143: 
1.27      www      5144:    $items=~s/\&$//;
1.620     albertel 5145:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5146:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5147:    my $uhome=&homeserver($uname,$udomain);
                   5148:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5149: }
                   5150: 
                   5151: # -------------------------------------------------------------- dump interface
                   5152: 
1.1180    droeschl 5153: sub unserialize {
                   5154:     my ($rep, $escapedkeys) = @_;
                   5155: 
                   5156:     return {} if $rep =~ /^error/;
                   5157: 
                   5158:     my %returnhash=();
                   5159: 	foreach my $item (split /\&/, $rep) {
                   5160: 	    my ($key, $value) = split(/=/, $item, 2);
                   5161: 	    $key = unescape($key) unless $escapedkeys;
                   5162: 	    next if $key =~ /^error: 2 /;
                   5163: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5164: 	}
                   5165:     #return %returnhash;
                   5166:     return \%returnhash;
                   5167: }        
                   5168: 
                   5169: # see Lond::dump_with_regexp
                   5170: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5171: sub dump {
1.1180    droeschl 5172:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5173:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5174:     if (!$uname) { $uname=$env{'user.name'}; }
                   5175:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5176: 
1.1180    droeschl 5177:     my $reply;
                   5178:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5179:         # user is hosted on this machine
                   5180:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
                   5181:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5182:         return %{unserialize($reply, $escapedkeys)};
                   5183:     }
1.755     albertel 5184:     if ($regexp) {
                   5185: 	$regexp=&escape($regexp);
                   5186:     } else {
                   5187: 	$regexp='.';
                   5188:     }
1.1166    raeburn  5189:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5190:     my @pairs=split(/\&/,$rep);
                   5191:     my %returnhash=();
1.1098    foxr     5192:     if (!($rep =~ /^error/ )) {
                   5193: 	foreach my $item (@pairs) {
                   5194: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5195:         $key = unescape($key) unless $escapedkeys;
                   5196:         #$key = &unescape($key);
1.1098    foxr     5197: 	    next if ($key =~ /^error: 2 /);
                   5198: 	    $returnhash{$key}=&thaw_unescape($value);
                   5199: 	}
1.755     albertel 5200:     }
                   5201:     return %returnhash;
1.407     www      5202: }
                   5203: 
1.1098    foxr     5204: 
1.717     albertel 5205: # --------------------------------------------------------- dumpstore interface
                   5206: 
                   5207: sub dumpstore {
                   5208:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5209:    # same as dump but keys must be escaped. They may contain colon separated
                   5210:    # lists of values that may themself contain colons (e.g. symbs).
                   5211:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5212: }
                   5213: 
1.407     www      5214: # -------------------------------------------------------------- keys interface
                   5215: 
                   5216: sub getkeys {
                   5217:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5218:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5219:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5220:    my $uhome=&homeserver($uname,$udomain);
                   5221:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5222:    my @keyarray=();
1.800     albertel 5223:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5224:       next if ($key =~ /^error: 2 /);
1.800     albertel 5225:       push(@keyarray,&unescape($key));
1.407     www      5226:    }
                   5227:    return @keyarray;
1.318     matthew  5228: }
                   5229: 
1.319     matthew  5230: # --------------------------------------------------------------- currentdump
                   5231: sub currentdump {
1.328     matthew  5232:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5233:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5234:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5235:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5236:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5237:    my $rep;
                   5238: 
                   5239:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5240:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5241:                    $courseid)));
                   5242:    } else {
                   5243:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5244:    }
                   5245: 
1.318     matthew  5246:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5247:    #
1.318     matthew  5248:    my %returnhash=();
1.319     matthew  5249:    #
                   5250:    if ($rep eq "unknown_cmd") { 
                   5251:        # an old lond will not know currentdump
                   5252:        # Do a dump and make it look like a currentdump
1.822     albertel 5253:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5254:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5255:        my %hash = @tmp;
                   5256:        @tmp=();
1.424     matthew  5257:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5258:    } else {
                   5259:        my @pairs=split(/\&/,$rep);
1.800     albertel 5260:        foreach my $pair (@pairs) {
                   5261:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5262:            my ($symb,$param) = split(/:/,$key);
                   5263:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5264:                                                         &thaw_unescape($value);
1.319     matthew  5265:        }
1.191     harris41 5266:    }
1.12      www      5267:    return %returnhash;
1.424     matthew  5268: }
                   5269: 
                   5270: sub convert_dump_to_currentdump{
                   5271:     my %hash = %{shift()};
                   5272:     my %returnhash;
                   5273:     # Code ripped from lond, essentially.  The only difference
                   5274:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5275:     # we might run in to problems with parameter names =~ /^v\./
                   5276:     while (my ($key,$value) = each(%hash)) {
                   5277:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5278: 	$symb  = &unescape($symb);
                   5279: 	$param = &unescape($param);
1.424     matthew  5280:         next if ($v eq 'version' || $symb eq 'keys');
                   5281:         next if (exists($returnhash{$symb}) &&
                   5282:                  exists($returnhash{$symb}->{$param}) &&
                   5283:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5284:         $returnhash{$symb}->{$param}=$value;
                   5285:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5286:     }
                   5287:     #
                   5288:     # Remove all of the keys in the hashes which keep track of
                   5289:     # the version of the parameter.
                   5290:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5291:         # use a foreach because we are going to delete from the hash.
                   5292:         foreach my $key (keys(%$param_hash)) {
                   5293:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5294:         }
                   5295:     }
                   5296:     return \%returnhash;
1.12      www      5297: }
                   5298: 
1.627     albertel 5299: # ------------------------------------------------------ critical inc interface
                   5300: 
                   5301: sub cinc {
                   5302:     return &inc(@_,'critical');
                   5303: }
                   5304: 
1.449     matthew  5305: # --------------------------------------------------------------- inc interface
                   5306: 
                   5307: sub inc {
1.627     albertel 5308:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5309:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5310:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5311:     my $uhome=&homeserver($uname,$udomain);
                   5312:     my $items='';
                   5313:     if (! ref($store)) {
                   5314:         # got a single value, so use that instead
                   5315:         $items = &escape($store).'=&';
                   5316:     } elsif (ref($store) eq 'SCALAR') {
                   5317:         $items = &escape($$store).'=&';        
                   5318:     } elsif (ref($store) eq 'ARRAY') {
                   5319:         $items = join('=&',map {&escape($_);} @{$store});
                   5320:     } elsif (ref($store) eq 'HASH') {
                   5321:         while (my($key,$value) = each(%{$store})) {
                   5322:             $items.= &escape($key).'='.&escape($value).'&';
                   5323:         }
                   5324:     }
                   5325:     $items=~s/\&$//;
1.627     albertel 5326:     if ($critical) {
                   5327: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5328:     } else {
                   5329: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5330:     }
1.449     matthew  5331: }
                   5332: 
1.12      www      5333: # --------------------------------------------------------------- put interface
                   5334: 
                   5335: sub put {
1.134     albertel 5336:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5337:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5338:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5339:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5340:    my $items='';
1.800     albertel 5341:    foreach my $item (keys(%$storehash)) {
                   5342:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5343:    }
1.12      www      5344:    $items=~s/\&$//;
1.134     albertel 5345:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5346: }
                   5347: 
1.631     albertel 5348: # ------------------------------------------------------------ newput interface
                   5349: 
                   5350: sub newput {
                   5351:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5352:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5353:    if (!$uname) { $uname=$env{'user.name'}; }
                   5354:    my $uhome=&homeserver($uname,$udomain);
                   5355:    my $items='';
                   5356:    foreach my $key (keys(%$storehash)) {
                   5357:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5358:    }
                   5359:    $items=~s/\&$//;
                   5360:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5361: }
                   5362: 
                   5363: # ---------------------------------------------------------  putstore interface
                   5364: 
1.524     raeburn  5365: sub putstore {
1.715     albertel 5366:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5367:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5368:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5369:    my $uhome=&homeserver($uname,$udomain);
                   5370:    my $items='';
1.715     albertel 5371:    foreach my $key (keys(%$storehash)) {
                   5372:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5373:    }
1.715     albertel 5374:    $items=~s/\&$//;
1.716     albertel 5375:    my $esc_symb=&escape($symb);
                   5376:    my $esc_v=&escape($version);
1.715     albertel 5377:    my $reply =
1.716     albertel 5378:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5379: 	      $uhome);
                   5380:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5381:        # gfall back to way things use to be done
1.715     albertel 5382:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5383: 			    $uname);
1.524     raeburn  5384:    }
1.715     albertel 5385:    return $reply;
                   5386: }
                   5387: 
                   5388: sub old_putstore {
1.716     albertel 5389:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5390:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5391:     if (!$uname) { $uname=$env{'user.name'}; }
                   5392:     my $uhome=&homeserver($uname,$udomain);
                   5393:     my %newstorehash;
1.800     albertel 5394:     foreach my $item (keys(%$storehash)) {
                   5395: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5396: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5397:     }
                   5398:     my $items='';
                   5399:     my %allitems = ();
1.800     albertel 5400:     foreach my $item (keys(%newstorehash)) {
                   5401: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5402: 	    my $key = $1.':keys:'.$2;
                   5403: 	    $allitems{$key} .= $3.':';
                   5404: 	}
1.800     albertel 5405: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5406:     }
1.800     albertel 5407:     foreach my $item (keys(%allitems)) {
                   5408: 	$allitems{$item} =~ s/\:$//;
                   5409: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5410:     }
                   5411:     $items=~s/\&$//;
                   5412:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5413: }
                   5414: 
1.47      www      5415: # ------------------------------------------------------ critical put interface
                   5416: 
                   5417: sub cput {
1.134     albertel 5418:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5419:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5420:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5421:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5422:    my $items='';
1.800     albertel 5423:    foreach my $item (keys(%$storehash)) {
                   5424:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5425:    }
1.47      www      5426:    $items=~s/\&$//;
1.134     albertel 5427:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5428: }
                   5429: 
                   5430: # -------------------------------------------------------------- eget interface
                   5431: 
                   5432: sub eget {
1.133     albertel 5433:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5434:    my $items='';
1.800     albertel 5435:    foreach my $item (@$storearr) {
                   5436:        $items.=&escape($item).'&';
1.191     harris41 5437:    }
1.12      www      5438:    $items=~s/\&$//;
1.620     albertel 5439:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5440:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5441:    my $uhome=&homeserver($uname,$udomain);
                   5442:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5443:    my @pairs=split(/\&/,$rep);
                   5444:    my %returnhash=();
1.42      www      5445:    my $i=0;
1.800     albertel 5446:    foreach my $item (@$storearr) {
                   5447:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5448:       $i++;
1.191     harris41 5449:    }
1.12      www      5450:    return %returnhash;
                   5451: }
                   5452: 
1.667     albertel 5453: # ------------------------------------------------------------ tmpput interface
                   5454: sub tmpput {
1.802     raeburn  5455:     my ($storehash,$server,$context)=@_;
1.667     albertel 5456:     my $items='';
1.800     albertel 5457:     foreach my $item (keys(%$storehash)) {
                   5458: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5459:     }
                   5460:     $items=~s/\&$//;
1.802     raeburn  5461:     if (defined($context)) {
                   5462:         $items .= ':'.&escape($context);
                   5463:     }
1.667     albertel 5464:     return &reply("tmpput:$items",$server);
                   5465: }
                   5466: 
                   5467: # ------------------------------------------------------------ tmpget interface
                   5468: sub tmpget {
1.688     albertel 5469:     my ($token,$server)=@_;
                   5470:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5471:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5472:     my %returnhash;
                   5473:     foreach my $item (split(/\&/,$rep)) {
                   5474: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5475:         next if ($key =~ /^error: 2 /);
1.667     albertel 5476: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5477:     }
                   5478:     return %returnhash;
                   5479: }
                   5480: 
1.1113    raeburn  5481: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5482: sub tmpdel {
                   5483:     my ($token,$server)=@_;
                   5484:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5485:     return &reply("tmpdel:$token",$server);
                   5486: }
                   5487: 
1.765     albertel 5488: # -------------------------------------------------- portfolio access checking
                   5489: 
                   5490: sub portfolio_access {
1.766     albertel 5491:     my ($requrl) = @_;
1.765     albertel 5492:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5493:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5494:     if ($result) {
                   5495:         my %setters;
                   5496:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5497:             my ($startblock,$endblock) =
                   5498:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5499:             if ($startblock && $endblock) {
                   5500:                 return 'B';
                   5501:             }
                   5502:         } else {
                   5503:             my ($startblock,$endblock) =
                   5504:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5505:             if ($startblock && $endblock) {
                   5506:                 return 'B';
                   5507:             }
                   5508:         }
                   5509:     }
1.765     albertel 5510:     if ($result eq 'ok') {
1.766     albertel 5511:        return 'F';
1.765     albertel 5512:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5513:        return 'A';
1.765     albertel 5514:     }
1.766     albertel 5515:     return '';
1.765     albertel 5516: }
                   5517: 
                   5518: sub get_portfolio_access {
1.767     albertel 5519:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5520: 
                   5521:     if (!ref($access_hash)) {
                   5522: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5523: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5524: 						   $file_name);
                   5525: 	$access_hash = $access_controls{$file_name};
                   5526:     }
                   5527: 
1.765     albertel 5528:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5529:     my $now = time;
                   5530:     if (ref($access_hash) eq 'HASH') {
                   5531:         foreach my $key (keys(%{$access_hash})) {
                   5532:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5533:             if ($start > $now) {
                   5534:                 next;
                   5535:             }
                   5536:             if ($end && $end<$now) {
                   5537:                 next;
                   5538:             }
                   5539:             if ($scope eq 'public') {
                   5540:                 $public = $key;
                   5541:                 last;
                   5542:             } elsif ($scope eq 'guest') {
                   5543:                 $guest = $key;
                   5544:             } elsif ($scope eq 'domains') {
                   5545:                 push(@domains,$key);
                   5546:             } elsif ($scope eq 'users') {
                   5547:                 push(@users,$key);
                   5548:             } elsif ($scope eq 'course') {
                   5549:                 push(@courses,$key);
                   5550:             } elsif ($scope eq 'group') {
                   5551:                 push(@groups,$key);
                   5552:             }
                   5553:         }
                   5554:         if ($public) {
                   5555:             return 'ok';
                   5556:         }
                   5557:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5558:             if ($guest) {
                   5559:                 return $guest;
                   5560:             }
                   5561:         } else {
                   5562:             if (@domains > 0) {
                   5563:                 foreach my $domkey (@domains) {
                   5564:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5565:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5566:                             return 'ok';
                   5567:                         }
                   5568:                     }
                   5569:                 }
                   5570:             }
                   5571:             if (@users > 0) {
                   5572:                 foreach my $userkey (@users) {
1.865     raeburn  5573:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5574:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5575:                             if (ref($item) eq 'HASH') {
                   5576:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5577:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5578:                                     return 'ok';
                   5579:                                 }
                   5580:                             }
                   5581:                         }
                   5582:                     } 
1.765     albertel 5583:                 }
                   5584:             }
                   5585:             my %roleshash;
                   5586:             my @courses_and_groups = @courses;
                   5587:             push(@courses_and_groups,@groups); 
                   5588:             if (@courses_and_groups > 0) {
                   5589:                 my (%allgroups,%allroles); 
                   5590:                 my ($start,$end,$role,$sec,$group);
                   5591:                 foreach my $envkey (%env) {
1.1060    raeburn  5592:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5593:                         my $cid = $2.'_'.$3; 
                   5594:                         if ($1 eq 'gr') {
                   5595:                             $group = $4;
                   5596:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5597:                         } else {
                   5598:                             if ($4 eq '') {
                   5599:                                 $sec = 'none';
                   5600:                             } else {
                   5601:                                 $sec = $4;
                   5602:                             }
                   5603:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5604:                         }
1.811     albertel 5605:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5606:                         my $cid = $2.'_'.$3;
                   5607:                         if ($4 eq '') {
                   5608:                             $sec = 'none';
                   5609:                         } else {
                   5610:                             $sec = $4;
                   5611:                         }
                   5612:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5613:                     }
                   5614:                 }
                   5615:                 if (keys(%allroles) == 0) {
                   5616:                     return;
                   5617:                 }
                   5618:                 foreach my $key (@courses_and_groups) {
                   5619:                     my %content = %{$$access_hash{$key}};
                   5620:                     my $cnum = $content{'number'};
                   5621:                     my $cdom = $content{'domain'};
                   5622:                     my $cid = $cdom.'_'.$cnum;
                   5623:                     if (!exists($allroles{$cid})) {
                   5624:                         next;
                   5625:                     }    
                   5626:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5627:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5628:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5629:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5630:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5631:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5632:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5633:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5634:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5635:                                         if (grep/^all$/,@sections) {
                   5636:                                             return 'ok';
                   5637:                                         } else {
                   5638:                                             if (grep/^$sec$/,@sections) {
                   5639:                                                 return 'ok';
                   5640:                                             }
                   5641:                                         }
                   5642:                                     }
                   5643:                                 }
                   5644:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5645:                                     if (grep/^none$/,@groups) {
                   5646:                                         return 'ok';
                   5647:                                     }
                   5648:                                 } else {
                   5649:                                     if (grep/^all$/,@groups) {
                   5650:                                         return 'ok';
                   5651:                                     } 
                   5652:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5653:                                         if (grep/^$group$/,@groups) {
                   5654:                                             return 'ok';
                   5655:                                         }
                   5656:                                     }
                   5657:                                 } 
                   5658:                             }
                   5659:                         }
                   5660:                     }
                   5661:                 }
                   5662:             }
                   5663:             if ($guest) {
                   5664:                 return $guest;
                   5665:             }
                   5666:         }
                   5667:     }
                   5668:     return;
                   5669: }
                   5670: 
                   5671: sub course_group_datechecker {
                   5672:     my ($dates,$now,$status) = @_;
                   5673:     my ($start,$end) = split(/\./,$dates);
                   5674:     if (!$start && !$end) {
                   5675:         return 'ok';
                   5676:     }
                   5677:     if (grep/^active$/,@{$status}) {
                   5678:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5679:             return 'ok';
                   5680:         }
                   5681:     }
                   5682:     if (grep/^previous$/,@{$status}) {
                   5683:         if ($end > $now ) {
                   5684:             return 'ok';
                   5685:         }
                   5686:     }
                   5687:     if (grep/^future$/,@{$status}) {
                   5688:         if ($start > $now) {
                   5689:             return 'ok';
                   5690:         }
                   5691:     }
                   5692:     return; 
                   5693: }
                   5694: 
                   5695: sub parse_portfolio_url {
                   5696:     my ($url) = @_;
                   5697: 
                   5698:     my ($type,$udom,$unum,$group,$file_name);
                   5699:     
1.823     albertel 5700:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5701: 	$type = 1;
                   5702:         $udom = $1;
                   5703:         $unum = $2;
                   5704:         $file_name = $3;
1.823     albertel 5705:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5706: 	$type = 2;
                   5707:         $udom = $1;
                   5708:         $unum = $2;
                   5709:         $group = $3;
                   5710:         $file_name = $3.'/'.$4;
                   5711:     }
                   5712:     if (wantarray) {
                   5713: 	return ($type,$udom,$unum,$file_name,$group);
                   5714:     }
                   5715:     return $type;
                   5716: }
                   5717: 
                   5718: sub is_portfolio_url {
                   5719:     my ($url) = @_;
                   5720:     return scalar(&parse_portfolio_url($url));
                   5721: }
                   5722: 
1.798     raeburn  5723: sub is_portfolio_file {
                   5724:     my ($file) = @_;
1.820     raeburn  5725:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5726:         return 1;
                   5727:     }
                   5728:     return;
                   5729: }
                   5730: 
1.976     raeburn  5731: sub usertools_access {
1.1084    raeburn  5732:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5733:     my ($access,%tools);
                   5734:     if ($context eq '') {
                   5735:         $context = 'tools';
                   5736:     }
                   5737:     if ($context eq 'requestcourses') {
                   5738:         %tools = (
                   5739:                       official   => 1,
                   5740:                       unofficial => 1,
1.1006    raeburn  5741:                       community  => 1,
1.985     raeburn  5742:                  );
1.1183    raeburn  5743:     } elsif ($context eq 'requestauthor') {
                   5744:         %tools = (
                   5745:                       requestauthor => 1,
                   5746:                  );
1.985     raeburn  5747:     } else {
                   5748:         %tools = (
                   5749:                       aboutme   => 1,
                   5750:                       blog      => 1,
1.1177    raeburn  5751:                       webdav    => 1,
1.985     raeburn  5752:                       portfolio => 1,
                   5753:                  );
                   5754:     }
1.976     raeburn  5755:     return if (!defined($tools{$tool}));
                   5756: 
                   5757:     if ((!defined($udom)) || (!defined($uname))) {
                   5758:         $udom = $env{'user.domain'};
                   5759:         $uname = $env{'user.name'};
                   5760:     }
                   5761: 
1.978     raeburn  5762:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5763:         if ($action ne 'reload') {
1.985     raeburn  5764:             if ($context eq 'requestcourses') {
                   5765:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  5766:             } elsif ($context eq 'requestauthor') {
                   5767:                 return $env{'environment.canrequest.author'};
1.985     raeburn  5768:             } else {
                   5769:                 return $env{'environment.availabletools.'.$tool};
                   5770:             }
                   5771:         }
1.976     raeburn  5772:     }
                   5773: 
1.1183    raeburn  5774:     my ($toolstatus,$inststatus,$envkey);
                   5775:     if ($context eq 'requestauthor') {
                   5776:         $envkey = $context; 
                   5777:     } else {
                   5778:         $envkey = $context.'.'.$tool;
                   5779:     }
1.976     raeburn  5780: 
1.985     raeburn  5781:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5782:          ($action ne 'reload')) {
1.1183    raeburn  5783:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  5784:         $inststatus = $env{'environment.inststatus'};
                   5785:     } else {
1.1084    raeburn  5786:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  5787:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  5788:             $inststatus = $userenvref->{'inststatus'};
                   5789:         } else {
1.1183    raeburn  5790:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   5791:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  5792:             $inststatus = $userenv{'inststatus'};
                   5793:         }
1.976     raeburn  5794:     }
                   5795: 
                   5796:     if ($toolstatus ne '') {
                   5797:         if ($toolstatus) {
                   5798:             $access = 1;
                   5799:         } else {
                   5800:             $access = 0;
                   5801:         }
                   5802:         return $access;
                   5803:     }
                   5804: 
1.1084    raeburn  5805:     my ($is_adv,%domdef);
                   5806:     if (ref($is_advref) eq 'HASH') {
                   5807:         $is_adv = $is_advref->{'is_adv'};
                   5808:     } else {
                   5809:         $is_adv = &is_advanced_user($udom,$uname);
                   5810:     }
                   5811:     if (ref($domdefref) eq 'HASH') {
                   5812:         %domdef = %{$domdefref};
                   5813:     } else {
                   5814:         %domdef = &get_domain_defaults($udom);
                   5815:     }
1.976     raeburn  5816:     if (ref($domdef{$tool}) eq 'HASH') {
                   5817:         if ($is_adv) {
                   5818:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5819:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5820:                     $access = 1;
                   5821:                 } else {
                   5822:                     $access = 0;
                   5823:                 }
                   5824:                 return $access;
                   5825:             }
                   5826:         }
                   5827:         if ($inststatus ne '') {
                   5828:             my ($hasaccess,$hasnoaccess);
                   5829:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5830:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5831:                     if ($domdef{$tool}{$affiliation}) {
                   5832:                         $hasaccess = 1;
                   5833:                     } else {
                   5834:                         $hasnoaccess = 1;
                   5835:                     }
                   5836:                 }
                   5837:             }
                   5838:             if ($hasaccess || $hasnoaccess) {
                   5839:                 if ($hasaccess) {
                   5840:                     $access = 1;
                   5841:                 } elsif ($hasnoaccess) {
                   5842:                     $access = 0; 
                   5843:                 }
                   5844:                 return $access;
                   5845:             }
                   5846:         } else {
                   5847:             if ($domdef{$tool}{'default'} ne '') {
                   5848:                 if ($domdef{$tool}{'default'}) {
                   5849:                     $access = 1;
                   5850:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5851:                     $access = 0;
                   5852:                 }
                   5853:                 return $access;
                   5854:             }
                   5855:         }
                   5856:     } else {
1.1177    raeburn  5857:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  5858:             $access = 1;
                   5859:         } else {
                   5860:             $access = 0;
                   5861:         }
1.976     raeburn  5862:         return $access;
                   5863:     }
                   5864: }
                   5865: 
1.1050    raeburn  5866: sub is_course_owner {
                   5867:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5868:     if (($udom eq '') || ($uname eq '')) {
                   5869:         $udom = $env{'user.domain'};
                   5870:         $uname = $env{'user.name'};
                   5871:     }
                   5872:     unless (($udom eq '') || ($uname eq '')) {
                   5873:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5874:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5875:                 return 1;
                   5876:             } else {
                   5877:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5878:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5879:                     return 1;
                   5880:                 }
                   5881:             }
                   5882:         }
                   5883:     }
                   5884:     return;
                   5885: }
                   5886: 
1.976     raeburn  5887: sub is_advanced_user {
                   5888:     my ($udom,$uname) = @_;
1.1085    raeburn  5889:     if ($udom ne '' && $uname ne '') {
                   5890:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5891:             if (wantarray) {
                   5892:                 return ($env{'user.adv'},$env{'user.author'});
                   5893:             } else {
                   5894:                 return $env{'user.adv'};
                   5895:             }
1.1085    raeburn  5896:         }
                   5897:     }
1.976     raeburn  5898:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5899:     my %allroles;
1.1128    raeburn  5900:     my ($is_adv,$is_author);
1.976     raeburn  5901:     foreach my $role (keys(%roleshash)) {
                   5902:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5903:         my $area = '/'.$tdomain.'/'.$trest;
                   5904:         if ($sec ne '') {
                   5905:             $area .= '/'.$sec;
                   5906:         }
                   5907:         if (($area ne '') && ($trole ne '')) {
                   5908:             my $spec=$trole.'.'.$area;
                   5909:             if ($trole =~ /^cr\//) {
                   5910:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5911:             } elsif ($trole ne 'gr') {
                   5912:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5913:             }
1.1128    raeburn  5914:             if ($trole eq 'au') {
                   5915:                 $is_author = 1;
                   5916:             }
1.976     raeburn  5917:         }
                   5918:     }
                   5919:     foreach my $role (keys(%allroles)) {
                   5920:         last if ($is_adv);
                   5921:         foreach my $item (split(/:/,$allroles{$role})) {
                   5922:             if ($item ne '') {
                   5923:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5924:                 if ($privilege eq 'adv') {
                   5925:                     $is_adv = 1;
                   5926:                     last;
                   5927:                 }
                   5928:             }
                   5929:         }
                   5930:     }
1.1128    raeburn  5931:     if (wantarray) {
                   5932:         return ($is_adv,$is_author);
                   5933:     }
1.976     raeburn  5934:     return $is_adv;
                   5935: }
1.798     raeburn  5936: 
1.1035    raeburn  5937: sub check_can_request {
1.1036    raeburn  5938:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5939:     my $canreq = 0;
                   5940:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5941:     my @options = ('approval','validate','autolimit');
                   5942:     my $optregex = join('|',@options);
                   5943:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5944:         foreach my $type (@{$types}) {
                   5945:             if (&usertools_access($env{'user.name'},
                   5946:                                   $env{'user.domain'},
                   5947:                                   $type,undef,'requestcourses')) {
                   5948:                 $canreq ++;
1.1036    raeburn  5949:                 if (ref($request_domains) eq 'HASH') {
                   5950:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5951:                 }
1.1035    raeburn  5952:                 if ($dom eq $env{'user.domain'}) {
                   5953:                     $can_request->{$type} = 1;
                   5954:                 }
                   5955:             }
                   5956:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5957:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5958:                 if (@curr > 0) {
1.1036    raeburn  5959:                     foreach my $item (@curr) {
                   5960:                         if (ref($request_domains) eq 'HASH') {
                   5961:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5962:                             if ($otherdom ne '') {
                   5963:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5964:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5965:                                         push(@{$request_domains->{$type}},$otherdom);
                   5966:                                     }
                   5967:                                 } else {
                   5968:                                     push(@{$request_domains->{$type}},$otherdom);
                   5969:                                 }
                   5970:                             }
                   5971:                         }
                   5972:                     }
                   5973:                     unless($dom eq $env{'user.domain'}) {
                   5974:                         $canreq ++;
1.1035    raeburn  5975:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5976:                             $can_request->{$type} = 1;
                   5977:                         }
                   5978:                     }
                   5979:                 }
                   5980:             }
                   5981:         }
                   5982:     }
                   5983:     return $canreq;
                   5984: }
                   5985: 
1.341     www      5986: # ---------------------------------------------- Custom access rule evaluation
                   5987: 
                   5988: sub customaccess {
                   5989:     my ($priv,$uri)=@_;
1.807     albertel 5990:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5991:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5992:     $udom = &LONCAPA::clean_domain($udom);
                   5993:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5994:     my $access=0;
1.800     albertel 5995:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5996: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5997: 	if ($type eq 'user') {
                   5998: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5999: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6000: 		if ($tdom) {
                   6001: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6002: 		}
1.896     albertel 6003: 		if ($tuname) {
                   6004: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6005: 		}
                   6006: 		$access=($effect eq 'allow');
                   6007: 		last;
                   6008: 	    }
                   6009: 	} else {
                   6010: 	    if ($role) {
                   6011: 		if ($role ne $urole) { next; }
                   6012: 	    }
                   6013: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6014: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6015: 		if ($tdom) {
                   6016: 		    if ($tdom ne $udom) { next; }
                   6017: 		}
                   6018: 		if ($tcrs) {
                   6019: 		    if ($tcrs ne $ucrs) { next; }
                   6020: 		}
                   6021: 		if ($tsec) {
                   6022: 		    if ($tsec ne $usec) { next; }
                   6023: 		}
                   6024: 		$access=($effect eq 'allow');
                   6025: 		last;
                   6026: 	    }
                   6027: 	    if ($realm eq '' && $role eq '') {
                   6028: 		$access=($effect eq 'allow');
                   6029: 	    }
1.402     bowersj2 6030: 	}
1.341     www      6031:     }
                   6032:     return $access;
                   6033: }
                   6034: 
1.103     harris41 6035: # ------------------------------------------------- Check for a user privilege
1.12      www      6036: 
                   6037: sub allowed {
1.810     raeburn  6038:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6039:     my $ver_orguri=$uri;
1.439     www      6040:     $uri=&deversion($uri);
1.152     www      6041:     my $orguri=$uri;
1.52      www      6042:     $uri=&declutter($uri);
1.809     raeburn  6043: 
1.810     raeburn  6044:     if ($priv eq 'evb') {
                   6045: # Evade communication block restrictions for specified role in a course
                   6046:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6047:             return $1;
                   6048:         } else {
                   6049:             return;
                   6050:         }
                   6051:     }
                   6052: 
1.620     albertel 6053:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6054: # Free bre access to adm and meta resources
1.775     albertel 6055:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6056: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6057: 	&& ($priv eq 'bre')) {
1.14      www      6058: 	return 'F';
1.159     www      6059:     }
                   6060: 
1.545     banghart 6061: # Free bre access to user's own portfolio contents
1.714     raeburn  6062:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6063:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6064: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6065:         my %setters;
                   6066:         my ($startblock,$endblock) = 
                   6067:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6068:         if ($startblock && $endblock) {
                   6069:             return 'B';
                   6070:         } else {
                   6071:             return 'F';
                   6072:         }
1.545     banghart 6073:     }
                   6074: 
1.762     raeburn  6075: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6076:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6077:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6078:         if (exists($env{'request.course.id'})) {
                   6079:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6080:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6081:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6082:                 my $courseprivid=$env{'request.course.id'};
                   6083:                 $courseprivid=~s/\_/\//;
                   6084:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6085:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6086:                     return $1; 
1.762     raeburn  6087:                 } else {
                   6088:                     if ($env{'request.course.sec'}) {
                   6089:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6090:                     }
                   6091:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6092:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6093:                         return $2;
                   6094:                     }
1.714     raeburn  6095:                 }
                   6096:             }
                   6097:         }
                   6098:     }
                   6099: 
1.159     www      6100: # Free bre to public access
                   6101: 
                   6102:     if ($priv eq 'bre') {
1.238     www      6103:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6104: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6105:            return 'F'; 
                   6106:         }
1.238     www      6107:         if ($copyright eq 'priv') {
                   6108:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6109: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6110: 		return '';
                   6111:             }
                   6112:         }
                   6113:         if ($copyright eq 'domain') {
                   6114:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6115: 	    unless (($env{'user.domain'} eq $1) ||
                   6116:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6117: 		return '';
                   6118:             }
1.262     matthew  6119:         }
1.620     albertel 6120:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6121:             # Library role, so allow browsing of resources in this domain.
                   6122:             return 'F';
1.238     www      6123:         }
1.341     www      6124:         if ($copyright eq 'custom') {
                   6125: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6126:         }
1.14      www      6127:     }
1.264     matthew  6128:     # Domain coordinator is trying to create a course
1.620     albertel 6129:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6130:         # uri is the requested domain in this case.
                   6131:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6132:         # a role of dc for the domain in question.
1.620     albertel 6133:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6134:     }
1.29      www      6135: 
1.52      www      6136:     my $thisallowed='';
                   6137:     my $statecond=0;
                   6138:     my $courseprivid='';
                   6139: 
1.1039    raeburn  6140:     my $ownaccess;
1.1043    raeburn  6141:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6142:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6143:         if ($uri eq '') {
                   6144:             $ownaccess = 1;
                   6145:         } else {
                   6146:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6147:                 my $udom = $env{'user.domain'};
                   6148:                 my $uname = $env{'user.name'};
                   6149:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6150:                     $ownaccess = 1;
1.1040    raeburn  6151:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6152:                     unless ($uri =~ m{\.\./}) {
                   6153:                         $ownaccess = 1;
                   6154:                     }
                   6155:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6156:                     my $now = time;
                   6157:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6158:                         my $adom = $1;
                   6159:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6160:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6161:                                 my ($start,$end) = split('.',$env{$key});
                   6162:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6163:                                     $ownaccess = 1;
                   6164:                                     last;
                   6165:                                 }
                   6166:                             }
                   6167:                         }
                   6168:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6169:                         my $adom = $1;
                   6170:                         my $aname = $2;
1.1042    raeburn  6171:                         foreach my $role ('ca','aa') { 
                   6172:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6173:                                 my ($start,$end) =
                   6174:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6175:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6176:                                     $ownaccess = 1;
                   6177:                                     last;
                   6178:                                 }
1.1039    raeburn  6179:                             }
                   6180:                         }
                   6181:                     }
                   6182:                 }
                   6183:             }
                   6184:         }
                   6185:     }
                   6186: 
1.52      www      6187: # Course
                   6188: 
1.620     albertel 6189:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6190:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6191:             $thisallowed.=$1;
                   6192:         }
1.52      www      6193:     }
1.29      www      6194: 
1.52      www      6195: # Domain
                   6196: 
1.620     albertel 6197:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6198:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6199:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6200:             $thisallowed.=$1;
                   6201:         }
1.12      www      6202:     }
1.52      www      6203: 
1.1141    raeburn  6204: # User who is not author or co-author might still be able to edit
                   6205: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6206:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6207:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6208:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6209:             $thisallowed.=$1;
                   6210:         }
                   6211:     }
                   6212: 
1.52      www      6213: # Course: uri itself is a course
1.66      www      6214:     my $courseuri=$uri;
                   6215:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6216:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6217: 
1.620     albertel 6218:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6219:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6220:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6221:             $thisallowed.=$1;
                   6222:         }
1.12      www      6223:     }
1.29      www      6224: 
1.665     albertel 6225: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6226: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6227:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6228: 	$thisallowed='';
1.671     raeburn  6229:         my ($match)=&is_on_map($uri);
                   6230:         if ($match) {
                   6231:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6232:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6233:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6234:                 if (@blockers > 0) {
                   6235:                     $thisallowed = 'B';
                   6236:                 } else {
                   6237:                     $thisallowed.=$1;
                   6238:                 }
1.671     raeburn  6239:             }
                   6240:         } else {
1.705     albertel 6241:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6242:             if ($refuri) {
                   6243:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6244:                     $thisallowed='F';
1.671     raeburn  6245:                 } else {
                   6246:                     $refuri=&declutter($refuri);
                   6247:                     my ($match) = &is_on_map($refuri);
                   6248:                     if ($match) {
1.1162    raeburn  6249:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6250:                         if (@blockers > 0) {
                   6251:                             $thisallowed = 'B';
                   6252:                         } else {
                   6253:                             $thisallowed='F';
                   6254:                         }
1.671     raeburn  6255:                     }
1.669     raeburn  6256:                 }
1.671     raeburn  6257:             }
                   6258:         }
1.314     www      6259:     }
1.492     albertel 6260: 
1.766     albertel 6261:     if ($priv eq 'bre'
                   6262: 	&& $thisallowed ne 'F' 
                   6263: 	&& $thisallowed ne '2'
                   6264: 	&& &is_portfolio_url($uri)) {
                   6265: 	$thisallowed = &portfolio_access($uri);
                   6266:     }
                   6267:     
1.52      www      6268: # Full access at system, domain or course-wide level? Exit.
1.29      www      6269:     if ($thisallowed=~/F/) {
                   6270: 	return 'F';
                   6271:     }
                   6272: 
1.52      www      6273: # If this is generating or modifying users, exit with special codes
1.29      www      6274: 
1.643     www      6275:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6276: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6277: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6278: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6279: 	    unless ($auname) { return $thisallowed; }
                   6280: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6281: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6282: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6283: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6284: 	}
1.52      www      6285: 	return $thisallowed;
                   6286:     }
                   6287: #
1.103     harris41 6288: # Gathered so far: system, domain and course wide privileges
1.52      www      6289: #
                   6290: # Course: See if uri or referer is an individual resource that is part of 
                   6291: # the course
                   6292: 
1.620     albertel 6293:     if ($env{'request.course.id'}) {
1.232     www      6294: 
1.620     albertel 6295:        $courseprivid=$env{'request.course.id'};
                   6296:        if ($env{'request.course.sec'}) {
                   6297:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6298:        }
                   6299:        $courseprivid=~s/\_/\//;
                   6300:        my $checkreferer=1;
1.232     www      6301:        my ($match,$cond)=&is_on_map($uri);
                   6302:        if ($match) {
                   6303:            $statecond=$cond;
1.620     albertel 6304:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6305:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6306:                my $value = $1;
                   6307:                if ($priv eq 'bre') {
                   6308:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6309:                    if (@blockers > 0) {
                   6310:                        $thisallowed = 'B';
                   6311:                    } else {
                   6312:                        $thisallowed.=$value;
                   6313:                    }
                   6314:                } else {
                   6315:                    $thisallowed.=$value;
                   6316:                }
1.52      www      6317:                $checkreferer=0;
                   6318:            }
1.29      www      6319:        }
1.83      www      6320:        
1.148     www      6321:        if ($checkreferer) {
1.620     albertel 6322: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6323:             unless ($refuri) {
1.800     albertel 6324:                 foreach my $key (keys(%env)) {
                   6325: 		    if ($key=~/^httpref\..*\*/) {
                   6326: 			my $pattern=$key;
1.156     www      6327:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6328:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6329:                         $pattern=~s/\//\\\//g;
1.152     www      6330:                         if ($orguri=~/$pattern/) {
1.800     albertel 6331: 			    $refuri=$env{$key};
1.148     www      6332:                         }
                   6333:                     }
1.191     harris41 6334:                 }
1.148     www      6335:             }
1.232     www      6336: 
1.148     www      6337:          if ($refuri) { 
1.152     www      6338: 	  $refuri=&declutter($refuri);
1.232     www      6339:           my ($match,$cond)=&is_on_map($refuri);
                   6340:             if ($match) {
                   6341:               my $refstatecond=$cond;
1.620     albertel 6342:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6343:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6344:                   my $value = $1;
                   6345:                   if ($priv eq 'bre') {
                   6346:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6347:                       if (@blockers > 0) {
                   6348:                           $thisallowed = 'B';
                   6349:                       } else {
                   6350:                           $thisallowed.=$value;
                   6351:                       }
                   6352:                   } else {
                   6353:                       $thisallowed.=$value;
                   6354:                   }
1.53      www      6355:                   $uri=$refuri;
                   6356:                   $statecond=$refstatecond;
1.52      www      6357:               }
                   6358:           }
1.148     www      6359:         }
1.29      www      6360:        }
1.52      www      6361:    }
1.29      www      6362: 
1.52      www      6363: #
1.103     harris41 6364: # Gathered now: all privileges that could apply, and condition number
1.52      www      6365: # 
                   6366: #
                   6367: # Full or no access?
                   6368: #
1.29      www      6369: 
1.52      www      6370:     if ($thisallowed=~/F/) {
                   6371: 	return 'F';
                   6372:     }
1.29      www      6373: 
1.52      www      6374:     unless ($thisallowed) {
                   6375:         return '';
                   6376:     }
1.29      www      6377: 
1.52      www      6378: # Restrictions exist, deal with them
                   6379: #
                   6380: #   C:according to course preferences
                   6381: #   R:according to resource settings
                   6382: #   L:unless locked
                   6383: #   X:according to user session state
                   6384: #
                   6385: 
                   6386: # Possibly locked functionality, check all courses
1.54      www      6387: # Locks might take effect only after 10 minutes cache expiration for other
                   6388: # courses, and 2 minutes for current course
1.52      www      6389: 
                   6390:     my $envkey;
                   6391:     if ($thisallowed=~/L/) {
1.1000    raeburn  6392:         foreach $envkey (keys(%env)) {
1.54      www      6393:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6394:                my $courseid=$2;
                   6395:                my $roleid=$1.'.'.$2;
1.92      www      6396:                $courseid=~s/^\///;
1.54      www      6397:                my $expiretime=600;
1.620     albertel 6398:                if ($env{'request.role'} eq $roleid) {
1.54      www      6399: 		  $expiretime=120;
                   6400:                }
                   6401: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6402:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6403:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6404: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6405:                }
1.620     albertel 6406:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6407:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6408: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6409:                        &log($env{'user.domain'},$env{'user.name'},
                   6410:                             $env{'user.home'},
1.57      www      6411:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6412:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6413:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6414: 		       return '';
                   6415:                    }
                   6416:                }
1.620     albertel 6417:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6418:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6419: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6420:                        &log($env{'user.domain'},$env{'user.name'},
                   6421:                             $env{'user.home'},
1.57      www      6422:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6423:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6424:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6425: 		       return '';
                   6426:                    }
                   6427:                }
                   6428: 	   }
1.29      www      6429:        }
1.52      www      6430:     }
                   6431:    
                   6432: #
                   6433: # Rest of the restrictions depend on selected course
                   6434: #
                   6435: 
1.620     albertel 6436:     unless ($env{'request.course.id'}) {
1.766     albertel 6437: 	if ($thisallowed eq 'A') {
                   6438: 	    return 'A';
1.814     raeburn  6439:         } elsif ($thisallowed eq 'B') {
                   6440:             return 'B';
1.766     albertel 6441: 	} else {
                   6442: 	    return '1';
                   6443: 	}
1.52      www      6444:     }
1.29      www      6445: 
1.52      www      6446: #
                   6447: # Now user is definitely in a course
                   6448: #
1.53      www      6449: 
                   6450: 
                   6451: # Course preferences
                   6452: 
                   6453:    if ($thisallowed=~/C/) {
1.620     albertel 6454:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6455:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6456:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6457: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6458: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6459: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6460: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6461: 			$env{'request.course.id'});
                   6462: 	   }
1.237     www      6463:            return '';
                   6464:        }
                   6465: 
1.620     albertel 6466:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6467: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6468: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6469: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6470: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6471: 			$env{'request.course.id'});
                   6472: 	   }
1.54      www      6473:            return '';
                   6474:        }
1.53      www      6475:    }
                   6476: 
                   6477: # Resource preferences
                   6478: 
                   6479:    if ($thisallowed=~/R/) {
1.620     albertel 6480:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6481:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6482: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6483: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6484: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6485: 	   }
                   6486: 	   return '';
1.54      www      6487:        }
1.53      www      6488:    }
1.30      www      6489: 
1.246     www      6490: # Restricted by state or randomout?
1.30      www      6491: 
1.52      www      6492:    if ($thisallowed=~/X/) {
1.620     albertel 6493:       if ($env{'acc.randomout'}) {
1.579     albertel 6494: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6495:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6496:             return ''; 
                   6497:          }
1.247     www      6498:       }
                   6499:       if (&condval($statecond)) {
1.52      www      6500: 	 return '2';
                   6501:       } else {
                   6502:          return '';
                   6503:       }
                   6504:    }
1.30      www      6505: 
1.766     albertel 6506:     if ($thisallowed eq 'A') {
                   6507: 	return 'A';
1.814     raeburn  6508:     } elsif ($thisallowed eq 'B') {
                   6509:         return 'B';
1.766     albertel 6510:     }
1.52      www      6511:    return 'F';
1.232     www      6512: }
1.1162    raeburn  6513: 
                   6514: sub get_comm_blocks {
                   6515:     my ($cdom,$cnum) = @_;
                   6516:     if ($cdom eq '' || $cnum eq '') {
                   6517:         return unless ($env{'request.course.id'});
                   6518:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6519:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6520:     }
                   6521:     my %commblocks;
                   6522:     my $hashid=$cdom.'_'.$cnum;
                   6523:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6524:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6525:         %commblocks = %{$blocksref};
                   6526:     } else {
                   6527:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6528:         my $cachetime = 600;
                   6529:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6530:     }
                   6531:     return %commblocks;
                   6532: }
                   6533: 
                   6534: sub has_comm_blocking {
                   6535:     my ($priv,$symb,$uri,$blocks) = @_;
                   6536:     return unless ($env{'request.course.id'});
                   6537:     return unless ($priv eq 'bre');
                   6538:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6539:     my %commblocks;
                   6540:     if (ref($blocks) eq 'HASH') {
                   6541:         %commblocks = %{$blocks};
                   6542:     } else {
                   6543:         %commblocks = &get_comm_blocks();
                   6544:     }
                   6545:     return unless (keys(%commblocks) > 0);
                   6546:     if (!$symb) { $symb=&symbread($uri,1); }
                   6547:     my ($map,$resid,undef)=&decode_symb($symb);
                   6548:     my %tocheck = (
                   6549:                     maps      => $map,
                   6550:                     resources => $symb,
                   6551:                   );
                   6552:     my @blockers;
                   6553:     my $now = time;
1.1163    raeburn  6554:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6555:     foreach my $block (keys(%commblocks)) {
                   6556:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6557:             my ($start,$end) = ($1,$2);
                   6558:             if ($start <= $now && $end >= $now) {
                   6559:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6560:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6561:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6562:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6563:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6564:                                     push(@blockers,$block);
                   6565:                                 }
                   6566:                             }
                   6567:                         }
                   6568:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6569:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6570:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6571:                                     push(@blockers,$block);
                   6572:                                 }
                   6573:                             }
                   6574:                         }
                   6575:                     }
                   6576:                 }
                   6577:             }
                   6578:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6579:             my $item = $1;
1.1163    raeburn  6580:             my @to_test;
1.1162    raeburn  6581:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6582:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6583:                     my $check_interval;
                   6584:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6585:                         my @interval;
                   6586:                         my $type = 'map';
                   6587:                         if ($item eq 'course') {
                   6588:                             $type = 'course';
                   6589:                             @interval=&EXT("resource.0.interval");
                   6590:                         } else {
                   6591:                             if ($item =~ /___\d+___/) {
                   6592:                                 $type = 'resource';
                   6593:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6594:                                 if (ref($navmap)) {                        
                   6595:                                     my $res = $navmap->getBySymb($item); 
                   6596:                                     push(@to_test,$res);
                   6597:                                 }
1.1162    raeburn  6598:                             } else {
                   6599:                                 my $mapsymb = &symbread($item,1);
                   6600:                                 if ($mapsymb) {
                   6601:                                     if (ref($navmap)) {
                   6602:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6603:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6604:                                         foreach my $res (@to_test) {
1.1162    raeburn  6605:                                             my $symb = $res->symb();
                   6606:                                             next if ($symb eq $mapsymb);
                   6607:                                             if ($symb ne '') {
                   6608:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6609:                                                 last;
                   6610:                                             }
                   6611:                                         }
                   6612:                                     }
                   6613:                                 }
                   6614:                             }
                   6615:                         }
                   6616:                         if ($interval[0] =~ /\d+/) {
                   6617:                             my $first_access;
                   6618:                             if ($type eq 'resource') {
                   6619:                                 $first_access=&get_first_access($interval[1],$item);
                   6620:                             } elsif ($type eq 'map') {
                   6621:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6622:                             } else {
                   6623:                                 $first_access=&get_first_access($interval[1]);
                   6624:                             }
                   6625:                             if ($first_access) {
                   6626:                                 my $timesup = $first_access+$interval[0];
                   6627:                                 if ($timesup > $now) {
1.1163    raeburn  6628:                                     foreach my $res (@to_test) {
                   6629:                                         if ($res->is_problem()) {
                   6630:                                             if ($res->completable()) {
                   6631:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6632:                                                     push(@blockers,$block);
                   6633:                                                 }
                   6634:                                                 last;
                   6635:                                             }
                   6636:                                         }
1.1162    raeburn  6637:                                     }
                   6638:                                 }
                   6639:                             }
                   6640:                         }
                   6641:                     }
                   6642:                 }
                   6643:             }
                   6644:         }
                   6645:     }
                   6646:     return @blockers;
                   6647: }
                   6648: 
                   6649: sub check_docs_block {
                   6650:     my ($docsblock,$tocheck) =@_;
                   6651:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6652:         return;
                   6653:     }
                   6654:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6655:         if ($tocheck->{'maps'}) {
                   6656:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6657:                 return 1;
                   6658:             }
                   6659:         }
                   6660:     }
                   6661:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6662:         if ($tocheck->{'resources'}) {
                   6663:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6664:                 return 1;
                   6665:             }
                   6666:         }
                   6667:     }
                   6668:     return;
                   6669: }
                   6670: 
1.1133    foxr     6671: #
                   6672: #   Removes the versino from a URI and
                   6673: #   splits it in to its filename and path to the filename.
                   6674: #   Seems like File::Basename could have done this more clearly.
                   6675: #   Parameters:
                   6676: #      $uri   - input URI
                   6677: #   Returns:
                   6678: #     Two element list consisting of 
                   6679: #     $pathname  - the URI up to and excluding the trailing /
                   6680: #     $filename  - The part of the URI following the last /
                   6681: #  NOTE:
                   6682: #    Another realization of this is simply:
                   6683: #    use File::Basename;
                   6684: #    ...
                   6685: #    $uri = shift;
                   6686: #    $filename = basename($uri);
                   6687: #    $path     = dirname($uri);
                   6688: #    return ($filename, $path);
                   6689: #
                   6690: #     The implementation below is probably faster however.
                   6691: #
1.710     albertel 6692: sub split_uri_for_cond {
                   6693:     my $uri=&deversion(&declutter(shift));
                   6694:     my @uriparts=split(/\//,$uri);
                   6695:     my $filename=pop(@uriparts);
                   6696:     my $pathname=join('/',@uriparts);
                   6697:     return ($pathname,$filename);
                   6698: }
1.232     www      6699: # --------------------------------------------------- Is a resource on the map?
                   6700: 
                   6701: sub is_on_map {
1.710     albertel 6702:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6703:     #Trying to find the conditional for the file
1.620     albertel 6704:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6705: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6706:     if ($match) {
1.289     bowersj2 6707: 	return (1,$1);
                   6708:     } else {
1.434     www      6709: 	return (0,0);
1.289     bowersj2 6710:     }
1.12      www      6711: }
                   6712: 
1.427     www      6713: # --------------------------------------------------------- Get symb from alias
                   6714: 
                   6715: sub get_symb_from_alias {
                   6716:     my $symb=shift;
                   6717:     my ($map,$resid,$url)=&decode_symb($symb);
                   6718: # Already is a symb
                   6719:     if ($url) { return $symb; }
                   6720: # Must be an alias
                   6721:     my $aliassymb='';
                   6722:     my %bighash;
1.620     albertel 6723:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6724:                             &GDBM_READER(),0640)) {
                   6725:         my $rid=$bighash{'mapalias_'.$symb};
                   6726: 	if ($rid) {
                   6727: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6728: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6729: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6730: 	}
                   6731:         untie %bighash;
                   6732:     }
                   6733:     return $aliassymb;
                   6734: }
                   6735: 
1.12      www      6736: # ----------------------------------------------------------------- Define Role
                   6737: 
                   6738: sub definerole {
                   6739:   if (allowed('mcr','/')) {
                   6740:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6741:     foreach my $role (split(':',$sysrole)) {
                   6742: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6743:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6744:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6745: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6746:                return "refused:s:$crole&$cqual"; 
                   6747:             }
                   6748:         }
1.191     harris41 6749:     }
1.800     albertel 6750:     foreach my $role (split(':',$domrole)) {
                   6751: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6752:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6753:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6754: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6755:                return "refused:d:$crole&$cqual"; 
                   6756:             }
                   6757:         }
1.191     harris41 6758:     }
1.800     albertel 6759:     foreach my $role (split(':',$courole)) {
                   6760: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6761:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6762:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6763: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6764:                return "refused:c:$crole&$cqual"; 
                   6765:             }
                   6766:         }
1.191     harris41 6767:     }
1.620     albertel 6768:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6769:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6770: 	        "rolesdef_$rolename=".
                   6771:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6772:     return reply($command,$env{'user.home'});
1.12      www      6773:   } else {
                   6774:     return 'refused';
                   6775:   }
1.105     harris41 6776: }
                   6777: 
                   6778: # ---------------- Make a metadata query against the network of library servers
                   6779: 
                   6780: sub metadata_query {
1.244     matthew  6781:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6782:     my %rhash;
1.845     albertel 6783:     my %libserv = &all_library();
1.244     matthew  6784:     my @server_list = (defined($server_array) ? @$server_array
                   6785:                                               : keys(%libserv) );
                   6786:     for my $server (@server_list) {
1.118     harris41 6787: 	unless ($custom or $customshow) {
                   6788: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6789: 	    $rhash{$server}=$reply;
                   6790: 	}
                   6791: 	else {
                   6792: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6793: 			     &escape($custom).':'.&escape($customshow),
                   6794: 			     $server);
                   6795: 	    $rhash{$server}=$reply;
                   6796: 	}
1.112     harris41 6797:     }
1.118     harris41 6798:     return \%rhash;
1.240     www      6799: }
                   6800: 
                   6801: # ----------------------------------------- Send log queries and wait for reply
                   6802: 
                   6803: sub log_query {
                   6804:     my ($uname,$udom,$query,%filters)=@_;
                   6805:     my $uhome=&homeserver($uname,$udom);
                   6806:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6807:     my $uhost=&hostname($uhome);
1.800     albertel 6808:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6809:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6810:                        $uhome);
1.479     albertel 6811:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6812:     return get_query_reply($queryid);
                   6813: }
                   6814: 
1.818     raeburn  6815: # -------------------------- Update MySQL table for portfolio file
                   6816: 
                   6817: sub update_portfolio_table {
1.821     raeburn  6818:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6819:     if ($group ne '') {
                   6820:         $file_name =~s /^\Q$group\E//;
                   6821:     }
1.818     raeburn  6822:     my $homeserver = &homeserver($uname,$udom);
                   6823:     my $queryid=
1.821     raeburn  6824:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6825:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6826:     my $reply = &get_query_reply($queryid);
                   6827:     return $reply;
                   6828: }
                   6829: 
1.899     raeburn  6830: # -------------------------- Update MySQL allusers table
                   6831: 
                   6832: sub update_allusers_table {
                   6833:     my ($uname,$udom,$names) = @_;
                   6834:     my $homeserver = &homeserver($uname,$udom);
                   6835:     my $queryid=
                   6836:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6837:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6838:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6839:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6840:                'generation='.&escape($names->{'generation'}).'%%'.
                   6841:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6842:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6843:     return;
1.899     raeburn  6844: }
                   6845: 
1.508     raeburn  6846: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6847: 
                   6848: sub fetch_enrollment_query {
1.511     raeburn  6849:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6850:     my $homeserver;
1.547     raeburn  6851:     my $maxtries = 1;
1.508     raeburn  6852:     if ($context eq 'automated') {
                   6853:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6854:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6855:     } else {
                   6856:         $homeserver = &homeserver($cnum,$dom);
                   6857:     }
1.838     albertel 6858:     my $host=&hostname($homeserver);
1.506     raeburn  6859:     my $cmd = '';
1.1000    raeburn  6860:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6861:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6862:     }
                   6863:     $cmd =~ s/%%$//;
                   6864:     $cmd = &escape($cmd);
                   6865:     my $query = 'fetchenrollment';
1.620     albertel 6866:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6867:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6868:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6869:         return 'error: '.$queryid;
                   6870:     }
1.506     raeburn  6871:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6872:     my $tries = 1;
                   6873:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6874:         $reply = &get_query_reply($queryid);
                   6875:         $tries ++;
                   6876:     }
1.526     raeburn  6877:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6878:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6879:     } else {
1.901     albertel 6880:         my @responses = split(/:/,$reply);
1.515     raeburn  6881:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6882:             foreach my $line (@responses) {
                   6883:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6884:                 $$replyref{$key} = $value;
                   6885:             }
                   6886:         } else {
1.1117    foxr     6887:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6888:             foreach my $line (@responses) {
                   6889:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6890:                 $$replyref{$key} = $value;
                   6891:                 if ($value > 0) {
1.800     albertel 6892:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6893:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6894:                         my $destname = $pathname.'/'.$filename;
                   6895:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6896:                         if ($xml_classlist =~ /^error/) {
                   6897:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6898:                         } else {
1.506     raeburn  6899:                             if ( open(FILE,">$destname") ) {
                   6900:                                 print FILE &unescape($xml_classlist);
                   6901:                                 close(FILE);
1.526     raeburn  6902:                             } else {
                   6903:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6904:                             }
                   6905:                         }
                   6906:                     }
                   6907:                 }
                   6908:             }
                   6909:         }
                   6910:         return 'ok';
                   6911:     }
                   6912:     return 'error';
                   6913: }
                   6914: 
1.242     www      6915: sub get_query_reply {
                   6916:     my $queryid=shift;
1.1117    foxr     6917:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6918:     my $reply='';
                   6919:     for (1..100) {
                   6920: 	sleep 2;
                   6921:         if (-e $replyfile.'.end') {
1.448     albertel 6922: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6923: 		$reply = join('',<$fh>);
                   6924: 		close($fh);
1.240     www      6925: 	   } else { return 'error: reply_file_error'; }
1.242     www      6926:            return &unescape($reply);
                   6927: 	}
1.240     www      6928:     }
1.242     www      6929:     return 'timeout:'.$queryid;
1.240     www      6930: }
                   6931: 
                   6932: sub courselog_query {
1.241     www      6933: #
                   6934: # possible filters:
                   6935: # url: url or symb
                   6936: # username
                   6937: # domain
                   6938: # action: view, submit, grade
                   6939: # start: timestamp
                   6940: # end: timestamp
                   6941: #
1.240     www      6942:     my (%filters)=@_;
1.620     albertel 6943:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6944:     if ($filters{'url'}) {
                   6945: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6946:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6947:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6948:     }
1.620     albertel 6949:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6950:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6951:     return &log_query($cname,$cdom,'courselog',%filters);
                   6952: }
                   6953: 
                   6954: sub userlog_query {
1.858     raeburn  6955: #
                   6956: # possible filters:
                   6957: # action: log check role
                   6958: # start: timestamp
                   6959: # end: timestamp
                   6960: #
1.240     www      6961:     my ($uname,$udom,%filters)=@_;
                   6962:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6963: }
                   6964: 
1.506     raeburn  6965: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6966: 
                   6967: sub auto_run {
1.508     raeburn  6968:     my ($cnum,$cdom) = @_;
1.876     raeburn  6969:     my $response = 0;
                   6970:     my $settings;
                   6971:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6972:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6973:         $settings = $domconfig{'autoenroll'};
                   6974:         if ($settings->{'run'} eq '1') {
                   6975:             $response = 1;
                   6976:         }
                   6977:     } else {
1.934     raeburn  6978:         my $homeserver;
                   6979:         if (&is_course($cdom,$cnum)) {
                   6980:             $homeserver = &homeserver($cnum,$cdom);
                   6981:         } else {
                   6982:             $homeserver = &domain($cdom,'primary');
                   6983:         }
                   6984:         if ($homeserver ne 'no_host') {
                   6985:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6986:         }
1.876     raeburn  6987:     }
1.506     raeburn  6988:     return $response;
                   6989: }
1.776     albertel 6990: 
1.506     raeburn  6991: sub auto_get_sections {
1.508     raeburn  6992:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6993:     my $homeserver;
                   6994:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6995:         $homeserver = &homeserver($cnum,$cdom);
                   6996:     }
                   6997:     if (!defined($homeserver)) { 
                   6998:         if ($cdom =~ /^$match_domain$/) {
                   6999:             $homeserver = &domain($cdom,'primary');
                   7000:         }
                   7001:     }
                   7002:     my @secs;
                   7003:     if (defined($homeserver)) {
                   7004:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7005:         unless ($response eq 'refused') {
                   7006:             @secs = split(/:/,$response);
                   7007:         }
1.506     raeburn  7008:     }
                   7009:     return @secs;
                   7010: }
1.776     albertel 7011: 
1.506     raeburn  7012: sub auto_new_course {
1.1099    raeburn  7013:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7014:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7015:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7016:     return $response;
                   7017: }
1.776     albertel 7018: 
1.506     raeburn  7019: sub auto_validate_courseID {
1.508     raeburn  7020:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7021:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7022:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7023:     return $response;
                   7024: }
1.776     albertel 7025: 
1.1007    raeburn  7026: sub auto_validate_instcode {
1.1020    raeburn  7027:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7028:     my ($homeserver,$response);
                   7029:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7030:         $homeserver = &homeserver($cnum,$cdom);
                   7031:     }
                   7032:     if (!defined($homeserver)) {
                   7033:         if ($cdom =~ /^$match_domain$/) {
                   7034:             $homeserver = &domain($cdom,'primary');
                   7035:         }
                   7036:     }
1.1065    raeburn  7037:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7038:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  7039:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   7040:     return ($outcome,$description);
1.1007    raeburn  7041: }
                   7042: 
1.506     raeburn  7043: sub auto_create_password {
1.873     raeburn  7044:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7045:     my ($homeserver,$response);
1.506     raeburn  7046:     my $create_passwd = 0;
                   7047:     my $authchk = '';
1.873     raeburn  7048:     if ($udom =~ /^$match_domain$/) {
                   7049:         $homeserver = &domain($udom,'primary');
                   7050:     }
                   7051:     if ($homeserver eq '') {
                   7052:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7053:             $homeserver = &homeserver($cnum,$cdom);
                   7054:         }
                   7055:     }
                   7056:     if ($homeserver eq '') {
                   7057:         $authchk = 'nodomain';
1.506     raeburn  7058:     } else {
1.873     raeburn  7059:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7060:         if ($response eq 'refused') {
                   7061:             $authchk = 'refused';
                   7062:         } else {
1.901     albertel 7063:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7064:         }
1.506     raeburn  7065:     }
                   7066:     return ($authparam,$create_passwd,$authchk);
                   7067: }
                   7068: 
1.706     raeburn  7069: sub auto_photo_permission {
                   7070:     my ($cnum,$cdom,$students) = @_;
                   7071:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7072:     my ($outcome,$perm_reqd,$conditions) = 
                   7073: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7074:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7075: 	return (undef,undef);
                   7076:     }
1.706     raeburn  7077:     return ($outcome,$perm_reqd,$conditions);
                   7078: }
                   7079: 
                   7080: sub auto_checkphotos {
                   7081:     my ($uname,$udom,$pid) = @_;
                   7082:     my $homeserver = &homeserver($uname,$udom);
                   7083:     my ($result,$resulttype);
                   7084:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7085: 				   &escape($uname).':'.&escape($pid),
                   7086: 				   $homeserver));
1.709     albertel 7087:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7088: 	return (undef,undef);
                   7089:     }
1.706     raeburn  7090:     if ($outcome) {
                   7091:         ($result,$resulttype) = split(/:/,$outcome);
                   7092:     } 
                   7093:     return ($result,$resulttype);
                   7094: }
                   7095: 
                   7096: sub auto_photochoice {
                   7097:     my ($cnum,$cdom) = @_;
                   7098:     my $homeserver = &homeserver($cnum,$cdom);
                   7099:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7100: 						       &escape($cdom),
                   7101: 						       $homeserver)));
1.709     albertel 7102:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7103: 	return (undef,undef);
                   7104:     }
1.706     raeburn  7105:     return ($update,$comment);
                   7106: }
                   7107: 
                   7108: sub auto_photoupdate {
                   7109:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7110:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7111:     my $host=&hostname($homeserver);
1.706     raeburn  7112:     my $cmd = '';
                   7113:     my $maxtries = 1;
1.800     albertel 7114:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7115:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7116:     }
                   7117:     $cmd =~ s/%%$//;
                   7118:     $cmd = &escape($cmd);
                   7119:     my $query = 'institutionalphotos';
                   7120:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7121:     unless ($queryid=~/^\Q$host\E\_/) {
                   7122:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7123:         return 'error: '.$queryid;
                   7124:     }
                   7125:     my $reply = &get_query_reply($queryid);
                   7126:     my $tries = 1;
                   7127:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7128:         $reply = &get_query_reply($queryid);
                   7129:         $tries ++;
                   7130:     }
                   7131:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7132:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7133:     } else {
                   7134:         my @responses = split(/:/,$reply);
                   7135:         my $outcome = shift(@responses); 
                   7136:         foreach my $item (@responses) {
                   7137:             my ($key,$value) = split(/=/,$item);
                   7138:             $$photo{$key} = $value;
                   7139:         }
                   7140:         return $outcome;
                   7141:     }
                   7142:     return 'error';
                   7143: }
                   7144: 
1.521     raeburn  7145: sub auto_instcode_format {
1.793     albertel 7146:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7147: 	$cat_order) = @_;
1.521     raeburn  7148:     my $courses = '';
1.772     raeburn  7149:     my @homeservers;
1.521     raeburn  7150:     if ($caller eq 'global') {
1.841     albertel 7151: 	my %servers = &get_servers($codedom,'library');
                   7152: 	foreach my $tryserver (keys(%servers)) {
                   7153: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7154: 		push(@homeservers,$tryserver);
                   7155: 	    }
1.584     raeburn  7156:         }
1.1022    raeburn  7157:     } elsif ($caller eq 'requests') {
                   7158:         if ($codedom =~ /^$match_domain$/) {
                   7159:             my $chome = &domain($codedom,'primary');
                   7160:             unless ($chome eq 'no_host') {
                   7161:                 push(@homeservers,$chome);
                   7162:             }
                   7163:         }
1.521     raeburn  7164:     } else {
1.772     raeburn  7165:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7166:     }
1.793     albertel 7167:     foreach my $code (keys(%{$instcodes})) {
                   7168:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7169:     }
                   7170:     chop($courses);
1.772     raeburn  7171:     my $ok_response = 0;
                   7172:     my $response;
                   7173:     while (@homeservers > 0 && $ok_response == 0) {
                   7174:         my $server = shift(@homeservers); 
                   7175:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7176:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7177:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7178: 		split(/:/,$response);
1.772     raeburn  7179:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7180:             push(@{$codetitles},&str2array($codetitles_str));
                   7181:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7182:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7183:             $ok_response = 1;
                   7184:         }
                   7185:     }
                   7186:     if ($ok_response) {
1.521     raeburn  7187:         return 'ok';
1.772     raeburn  7188:     } else {
                   7189:         return $response;
1.521     raeburn  7190:     }
                   7191: }
                   7192: 
1.792     raeburn  7193: sub auto_instcode_defaults {
                   7194:     my ($domain,$returnhash,$code_order) = @_;
                   7195:     my @homeservers;
1.841     albertel 7196: 
                   7197:     my %servers = &get_servers($domain,'library');
                   7198:     foreach my $tryserver (keys(%servers)) {
                   7199: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7200: 	    push(@homeservers,$tryserver);
                   7201: 	}
1.792     raeburn  7202:     }
1.841     albertel 7203: 
1.792     raeburn  7204:     my $response;
1.841     albertel 7205:     foreach my $server (@homeservers) {
1.792     raeburn  7206:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7207:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7208: 	
                   7209: 	foreach my $pair (split(/\&/,$response)) {
                   7210: 	    my ($name,$value)=split(/\=/,$pair);
                   7211: 	    if ($name eq 'code_order') {
                   7212: 		@{$code_order} = split(/\&/,&unescape($value));
                   7213: 	    } else {
                   7214: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7215: 	    }
                   7216: 	}
                   7217: 	return 'ok';
1.792     raeburn  7218:     }
1.841     albertel 7219: 
                   7220:     return $response;
1.1003    raeburn  7221: }
                   7222: 
                   7223: sub auto_possible_instcodes {
1.1007    raeburn  7224:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7225:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7226:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7227:         return;
                   7228:     }
1.1003    raeburn  7229:     my (@homeservers,$uhome);
                   7230:     if (defined(&domain($domain,'primary'))) {
                   7231:         $uhome=&domain($domain,'primary');
                   7232:         push(@homeservers,&domain($domain,'primary'));
                   7233:     } else {
                   7234:         my %servers = &get_servers($domain,'library');
                   7235:         foreach my $tryserver (keys(%servers)) {
                   7236:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7237:                 push(@homeservers,$tryserver);
                   7238:             }
                   7239:         }
                   7240:     }
                   7241:     my $response;
                   7242:     foreach my $server (@homeservers) {
                   7243:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7244:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7245:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7246:             split(':',$response);
                   7247:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7248:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7249:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7250:             my ($name,$value)=split('=',$item);
                   7251:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7252:         }
                   7253:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7254:             my ($name,$value)=split('=',$item);
                   7255:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7256:         }
                   7257:         return 'ok';
                   7258:     }
                   7259:     return $response;
                   7260: }
1.792     raeburn  7261: 
1.1010    raeburn  7262: sub auto_courserequest_checks {
                   7263:     my ($dom) = @_;
1.1020    raeburn  7264:     my ($homeserver,%validations);
                   7265:     if ($dom =~ /^$match_domain$/) {
                   7266:         $homeserver = &domain($dom,'primary');
                   7267:     }
                   7268:     unless ($homeserver eq 'no_host') {
                   7269:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7270:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7271:             my @items = split(/&/,$response);
                   7272:             foreach my $item (@items) {
                   7273:                 my ($key,$value) = split('=',$item);
                   7274:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7275:             }
                   7276:         }
                   7277:     }
1.1010    raeburn  7278:     return %validations; 
                   7279: }
                   7280: 
1.1020    raeburn  7281: sub auto_courserequest_validation {
                   7282:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7283:     my ($homeserver,$response);
                   7284:     if ($dom =~ /^$match_domain$/) {
                   7285:         $homeserver = &domain($dom,'primary');
                   7286:     }
                   7287:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7288:           
1.1020    raeburn  7289:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7290:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7291:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7292:                                     $homeserver));
                   7293:     }
                   7294:     return $response;
                   7295: }
                   7296: 
1.777     albertel 7297: sub auto_validate_class_sec {
1.918     raeburn  7298:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7299:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7300:     my $ownerlist;
                   7301:     if (ref($owners) eq 'ARRAY') {
                   7302:         $ownerlist = join(',',@{$owners});
                   7303:     } else {
                   7304:         $ownerlist = $owners;
                   7305:     }
1.773     raeburn  7306:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7307:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7308:     return $response;
                   7309: }
                   7310: 
1.679     raeburn  7311: # ------------------------------------------------------- Course Group routines
                   7312: 
                   7313: sub get_coursegroups {
1.809     raeburn  7314:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7315:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7316: }
                   7317: 
1.679     raeburn  7318: sub modify_coursegroup {
                   7319:     my ($cdom,$cnum,$groupsettings) = @_;
                   7320:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7321: }
                   7322: 
1.809     raeburn  7323: sub toggle_coursegroup_status {
                   7324:     my ($cdom,$cnum,$group,$action) = @_;
                   7325:     my ($from_namespace,$to_namespace);
                   7326:     if ($action eq 'delete') {
                   7327:         $from_namespace = 'coursegroups';
                   7328:         $to_namespace = 'deleted_groups';
                   7329:     } else {
                   7330:         $from_namespace = 'deleted_groups';
                   7331:         $to_namespace = 'coursegroups';
                   7332:     }
                   7333:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7334:     if (my $tmp = &error(%curr_group)) {
                   7335:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7336:         return ('read error',$tmp);
                   7337:     } else {
                   7338:         my %savedsettings = %curr_group; 
1.809     raeburn  7339:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7340:         my $deloutcome;
                   7341:         if ($result eq 'ok') {
1.809     raeburn  7342:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7343:         } else {
                   7344:             return ('write error',$result);
                   7345:         }
                   7346:         if ($deloutcome eq 'ok') {
                   7347:             return 'ok';
                   7348:         } else {
                   7349:             return ('delete error',$deloutcome);
                   7350:         }
                   7351:     }
                   7352: }
                   7353: 
1.679     raeburn  7354: sub modify_group_roles {
1.957     raeburn  7355:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7356:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7357:     my $role = 'gr/'.&escape($userprivs);
                   7358:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7359:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7360:     if ($result eq 'ok') {
                   7361:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7362:     }
1.679     raeburn  7363:     return $result;
                   7364: }
                   7365: 
                   7366: sub modify_coursegroup_membership {
                   7367:     my ($cdom,$cnum,$membership) = @_;
                   7368:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7369:     return $result;
                   7370: }
                   7371: 
1.682     raeburn  7372: sub get_active_groups {
                   7373:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7374:     my $now = time;
                   7375:     my %groups = ();
                   7376:     foreach my $key (keys(%env)) {
1.811     albertel 7377:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7378:             my ($start,$end) = split(/\./,$env{$key});
                   7379:             if (($end!=0) && ($end<$now)) { next; }
                   7380:             if (($start!=0) && ($start>$now)) { next; }
                   7381:             if ($1 eq $cdom && $2 eq $cnum) {
                   7382:                 $groups{$3} = $env{$key} ;
                   7383:             }
                   7384:         }
                   7385:     }
                   7386:     return %groups;
                   7387: }
                   7388: 
1.683     raeburn  7389: sub get_group_membership {
                   7390:     my ($cdom,$cnum,$group) = @_;
                   7391:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7392: }
                   7393: 
                   7394: sub get_users_groups {
                   7395:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7396:     my @usersgroups;
1.683     raeburn  7397:     my $cachetime=1800;
                   7398: 
                   7399:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7400:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7401:     if (defined($cached)) {
1.734     albertel 7402:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7403:     } else {  
                   7404:         $grouplist = '';
1.816     raeburn  7405:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7406:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7407:         my $access_end = $env{'course.'.$courseid.
                   7408:                               '.default_enrollment_end_date'};
                   7409:         my $now = time;
                   7410:         foreach my $key (keys(%roleshash)) {
                   7411:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7412:                 my $group = $1;
                   7413:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7414:                     my $start = $2;
                   7415:                     my $end = $1;
                   7416:                     if ($start == -1) { next; } # deleted from group
                   7417:                     if (($start!=0) && ($start>$now)) { next; }
                   7418:                     if (($end!=0) && ($end<$now)) {
                   7419:                         if ($access_end && $access_end < $now) {
                   7420:                             if ($access_end - $end < 86400) {
                   7421:                                 push(@usersgroups,$group);
1.733     raeburn  7422:                             }
                   7423:                         }
1.817     raeburn  7424:                         next;
1.733     raeburn  7425:                     }
1.817     raeburn  7426:                     push(@usersgroups,$group);
1.683     raeburn  7427:                 }
                   7428:             }
                   7429:         }
1.817     raeburn  7430:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7431:         $grouplist = join(':',@usersgroups);
                   7432:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7433:     }
1.733     raeburn  7434:     return @usersgroups;
1.683     raeburn  7435: }
                   7436: 
                   7437: sub devalidate_getgroups_cache {
                   7438:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7439:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7440: 
1.683     raeburn  7441:     my $hashid="$udom:$uname:$courseid";
                   7442:     &devalidate_cache_new('getgroups',$hashid);
                   7443: }
                   7444: 
1.12      www      7445: # ------------------------------------------------------------------ Plain Text
                   7446: 
                   7447: sub plaintext {
1.988     raeburn  7448:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7449:     if ($short =~ m{^cr/}) {
1.758     albertel 7450: 	return (split('/',$short))[-1];
                   7451:     }
1.742     raeburn  7452:     if (!defined($cid)) {
                   7453:         $cid = $env{'request.course.id'};
                   7454:     }
                   7455:     my %rolenames = (
1.1008    raeburn  7456:                       Course    => 'std',
                   7457:                       Community => 'alt1',
1.742     raeburn  7458:                     );
1.1037    raeburn  7459:     if ($cid ne '') {
                   7460:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7461:             unless ($forcedefault) {
                   7462:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7463:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7464:                 return &Apache::lonlocal::mt($roletext);
                   7465:             }
                   7466:         }
                   7467:     }
                   7468:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7469:         (defined($rolenames{$type})) && 
                   7470:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7471:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7472:     } elsif ($cid ne '') {
                   7473:         my $crstype = $env{'course.'.$cid.'.type'};
                   7474:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7475:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7476:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7477:         }
1.742     raeburn  7478:     }
1.1037    raeburn  7479:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7480: }
                   7481: 
                   7482: # ----------------------------------------------------------------- Assign Role
                   7483: 
                   7484: sub assignrole {
1.957     raeburn  7485:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7486:         $context)=@_;
1.21      www      7487:     my $mrole;
                   7488:     if ($role =~ /^cr\//) {
1.393     www      7489:         my $cwosec=$url;
1.811     albertel 7490:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7491: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7492:            my $refused = 1;
                   7493:            if ($context eq 'requestcourses') {
                   7494:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7495:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7496:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7497:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7498:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7499:                            if ($crsenv{'internal.courseowner'} eq
                   7500:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7501:                                $refused = '';
                   7502:                            }
                   7503:                        }
                   7504:                    }
                   7505:                }
                   7506:            }
                   7507:            if ($refused) {
                   7508:                &logthis('Refused custom assignrole: '.
                   7509:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7510:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7511:                return 'refused';
                   7512:            }
1.104     www      7513:         }
1.21      www      7514:         $mrole='cr';
1.678     raeburn  7515:     } elsif ($role =~ /^gr\//) {
                   7516:         my $cwogrp=$url;
1.811     albertel 7517:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7518:         unless (&allowed('mdg',$cwogrp)) {
                   7519:             &logthis('Refused group assignrole: '.
                   7520:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7521:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7522:             return 'refused';
                   7523:         }
                   7524:         $mrole='gr';
1.21      www      7525:     } else {
1.82      www      7526:         my $cwosec=$url;
1.811     albertel 7527:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7528:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7529:             my $refused;
                   7530:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7531:                 if (!(&allowed('c'.$role,$url))) {
                   7532:                     $refused = 1;
                   7533:                 }
                   7534:             } else {
                   7535:                 $refused = 1;
                   7536:             }
1.947     raeburn  7537:             if ($refused) {
1.1045    raeburn  7538:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7539:                 if (!$selfenroll && $context eq 'course') {
                   7540:                     my %crsenv;
                   7541:                     if ($role eq 'cc' || $role eq 'co') {
                   7542:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7543:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7544:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7545:                                 if ($crsenv{'internal.courseowner'} eq 
                   7546:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7547:                                     $refused = '';
                   7548:                                 }
                   7549:                             }
                   7550:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7551:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7552:                                 if ($crsenv{'internal.courseowner'} eq 
                   7553:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7554:                                     $refused = '';
                   7555:                                 }
                   7556:                             }
                   7557:                         }
                   7558:                     }
                   7559:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7560:                     $refused = '';
1.1017    raeburn  7561:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7562:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7563:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7564:                         my $wrongcc;
                   7565:                         if ($cnum =~ /^$match_community$/) {
                   7566:                             $wrongcc = 1 if ($role eq 'cc');
                   7567:                         } else {
                   7568:                             $wrongcc = 1 if ($role eq 'co');
                   7569:                         }
                   7570:                         unless ($wrongcc) {
                   7571:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7572:                             if ($crsenv{'internal.courseowner'} eq 
                   7573:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7574:                                 $refused = '';
                   7575:                             }
1.1017    raeburn  7576:                         }
                   7577:                     }
1.1183    raeburn  7578:                 } elsif ($context eq 'requestauthor') {
                   7579:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   7580:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7581:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7582:                             $refused = '';
                   7583:                         } else {
                   7584:                             my %domdefaults = &get_domain_defaults($udom);
                   7585:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7586:                                 my $checkbystatus;
                   7587:                                 if ($env{'user.adv'}) { 
                   7588:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7589:                                     if ($disposition eq 'automatic') {
                   7590:                                         $refused = '';
                   7591:                                     } elsif ($disposition eq '') {
                   7592:                                         $checkbystatus = 1;
                   7593:                                     } 
                   7594:                                 } else {
                   7595:                                     $checkbystatus = 1;
                   7596:                                 }
                   7597:                                 if ($checkbystatus) {
                   7598:                                     if ($env{'environment.inststatus'}) {
                   7599:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7600:                                         foreach my $type (@inststatuses) {
                   7601:                                             if (($type ne '') &&
                   7602:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7603:                                                 $refused = '';
                   7604:                                             }
                   7605:                                         }
                   7606:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   7607:                                         $refused = '';
                   7608:                                     }
                   7609:                                 }
                   7610:                             }
                   7611:                         }
                   7612:                     }
1.1017    raeburn  7613:                 }
                   7614:                 if ($refused) {
1.947     raeburn  7615:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7616:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7617: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7618:                     return 'refused';
                   7619:                 }
1.932     raeburn  7620:             }
1.1131    raeburn  7621:         } elsif ($role eq 'au') {
                   7622:             if ($url ne '/'.$udom.'/') {
                   7623:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7624:                          ' to assign author role for '.$uname.':'.$udom.
                   7625:                          ' in domain: '.$url.' refused (wrong domain).');
                   7626:                 return 'refused';
                   7627:             }
1.104     www      7628:         }
1.21      www      7629:         $mrole=$role;
                   7630:     }
1.620     albertel 7631:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7632:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7633:     if ($end) { $command.='_'.$end; }
1.21      www      7634:     if ($start) {
                   7635: 	if ($end) { 
1.81      www      7636:            $command.='_'.$start; 
1.21      www      7637:         } else {
1.81      www      7638:            $command.='_0_'.$start;
1.21      www      7639:         }
                   7640:     }
1.739     raeburn  7641:     my $origstart = $start;
                   7642:     my $origend = $end;
1.957     raeburn  7643:     my $delflag;
1.357     www      7644: # actually delete
                   7645:     if ($deleteflag) {
1.373     www      7646: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7647: # modify command to delete the role
1.620     albertel 7648:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7649:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7650: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7651: # set start and finish to negative values for userrolelog
                   7652:            $start=-1;
                   7653:            $end=-1;
1.957     raeburn  7654:            $delflag = 1;
1.357     www      7655:         }
                   7656:     }
                   7657: # send command
1.349     www      7658:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7659: # log new user role if status is ok
1.349     www      7660:     if ($answer eq 'ok') {
1.663     raeburn  7661: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7662: # for course roles, perform group memberships changes triggered by role change.
                   7663:         unless ($role =~ /^gr/) {
                   7664:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7665:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7666:         }
1.1184    raeburn  7667:         if (($role eq 'cc') || ($role eq 'in') ||
                   7668:             ($role eq 'ep') || ($role eq 'ad') ||
                   7669:             ($role eq 'ta') || ($role eq 'st') ||
                   7670:             ($role=~/^cr/) || ($role eq 'gr') ||
                   7671:             ($role eq 'co')) {
                   7672:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7673:                            $selfenroll,$context);
                   7674:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   7675:                  ($role eq 'au') || ($role eq 'dc')) {
                   7676:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7677:                            $context);
                   7678:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   7679:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7680:                              $context); 
                   7681:         }
1.1053    raeburn  7682:         if ($role eq 'cc') {
                   7683:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7684:         }
1.349     www      7685:     }
                   7686:     return $answer;
1.169     harris41 7687: }
                   7688: 
1.1053    raeburn  7689: sub autoupdate_coowners {
                   7690:     my ($url,$end,$start,$uname,$udom) = @_;
                   7691:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7692:     if (($cdom ne '') && ($cnum ne '')) {
                   7693:         my $now = time;
                   7694:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7695:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7696:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7697:             my $instcode = $coursehash{'internal.coursecode'};
                   7698:             if ($instcode ne '') {
1.1056    raeburn  7699:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7700:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7701:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7702:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7703:                         if ($result eq 'valid') {
                   7704:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7705:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7706:                                     push(@newcoowners,$coowner);
                   7707:                                 }
                   7708:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7709:                                     push(@newcoowners,$uname.':'.$udom);
                   7710:                                 }
                   7711:                                 @newcoowners = sort(@newcoowners);
                   7712:                             } else {
                   7713:                                 push(@newcoowners,$uname.':'.$udom);
                   7714:                             }
                   7715:                         } else {
                   7716:                             if ($coursehash{'internal.co-owners'}) {
                   7717:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7718:                                     unless ($coowner eq $uname.':'.$udom) {
                   7719:                                         push(@newcoowners,$coowner);
                   7720:                                     }
                   7721:                                 }
                   7722:                                 unless (@newcoowners > 0) {
                   7723:                                     $delcoowners = 1;
                   7724:                                     $coowners = '';
                   7725:                                 }
                   7726:                             }
                   7727:                         }
                   7728:                         if (@newcoowners || $delcoowners) {
                   7729:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7730:                                             $delcoowners,@newcoowners);
                   7731:                         }
                   7732:                     }
                   7733:                 }
                   7734:             }
                   7735:         }
                   7736:     }
                   7737: }
                   7738: 
                   7739: sub store_coowners {
                   7740:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7741:     my $cid = $cdom.'_'.$cnum;
                   7742:     my ($coowners,$delresult,$putresult);
                   7743:     if (@newcoowners) {
                   7744:         $coowners = join(',',@newcoowners);
                   7745:         my %coownershash = (
                   7746:                             'internal.co-owners' => $coowners,
                   7747:                            );
                   7748:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7749:         if ($putresult eq 'ok') {
                   7750:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7751:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7752:             }
                   7753:         }
                   7754:     }
                   7755:     if ($delcoowners) {
                   7756:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7757:         if ($delresult eq 'ok') {
                   7758:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7759:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7760:             }
                   7761:         }
                   7762:     }
                   7763:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7764:         my %crsinfo =
                   7765:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7766:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7767:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7768:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7769:         }
                   7770:     }
                   7771: }
                   7772: 
1.169     harris41 7773: # -------------------------------------------------- Modify user authentication
1.197     www      7774: # Overrides without validation
                   7775: 
1.169     harris41 7776: sub modifyuserauth {
                   7777:     my ($udom,$uname,$umode,$upass)=@_;
                   7778:     my $uhome=&homeserver($uname,$udom);
1.197     www      7779:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7780:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7781:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7782:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7783:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7784: 		     &escape($upass),$uhome);
1.620     albertel 7785:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7786:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7787:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7788:     &log($udom,,$uname,$uhome,
1.620     albertel 7789:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7790:                                      $env{'user.name'}.', '.$umode.
1.197     www      7791:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7792:     unless ($reply eq 'ok') {
1.197     www      7793:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7794: 	return 'error: '.$reply;
                   7795:     }   
1.170     harris41 7796:     return 'ok';
1.80      www      7797: }
                   7798: 
1.81      www      7799: # --------------------------------------------------------------- Modify a user
1.80      www      7800: 
1.81      www      7801: sub modifyuser {
1.206     matthew  7802:     my ($udom,    $uname, $uid,
                   7803:         $umode,   $upass, $first,
                   7804:         $middle,  $last,  $gene,
1.1058    raeburn  7805:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7806:     $udom= &LONCAPA::clean_domain($udom);
                   7807:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7808:     my $showcandelete = 'none';
                   7809:     if (ref($candelete) eq 'ARRAY') {
                   7810:         if (@{$candelete} > 0) {
                   7811:             $showcandelete = join(', ',@{$candelete});
                   7812:         }
                   7813:     }
1.81      www      7814:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7815:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7816: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7817:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7818:                                      ' desiredhome not specified'). 
1.620     albertel 7819:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7820:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7821:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7822:     my $newuser;
                   7823:     if ($uhome eq 'no_host') {
                   7824:         $newuser = 1;
                   7825:     }
1.80      www      7826: # ----------------------------------------------------------------- Create User
1.406     albertel 7827:     if (($uhome eq 'no_host') && 
                   7828: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7829:         my $unhome='';
1.844     albertel 7830:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7831:             $unhome = $desiredhome;
1.620     albertel 7832: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7833: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7834:         } else { # load balancing routine for determining $unhome
1.81      www      7835:             my $loadm=10000000;
1.841     albertel 7836: 	    my %servers = &get_servers($udom,'library');
                   7837: 	    foreach my $tryserver (keys(%servers)) {
                   7838: 		my $answer=reply('load',$tryserver);
                   7839: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7840: 		    $loadm=$answer;
                   7841: 		    $unhome=$tryserver;
                   7842: 		}
1.80      www      7843: 	    }
                   7844:         }
                   7845:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7846: 	    return 'error: unable to find a home server for '.$uname.
                   7847:                    ' in domain '.$udom;
1.80      www      7848:         }
                   7849:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7850:                          &escape($upass),$unhome);
                   7851: 	unless ($reply eq 'ok') {
                   7852:             return 'error: '.$reply;
                   7853:         }   
1.230     stredwic 7854:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7855:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7856: 	    return 'error: unable verify users home machine.';
1.80      www      7857:         }
1.209     matthew  7858:     }   # End of creation of new user
1.80      www      7859: # ---------------------------------------------------------------------- Add ID
                   7860:     if ($uid) {
                   7861:        $uid=~tr/A-Z/a-z/;
                   7862:        my %uidhash=&idrget($udom,$uname);
1.196     www      7863:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7864:          && (!$forceid)) {
1.80      www      7865: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7866: 	      return 'error: user id "'.$uid.'" does not match '.
                   7867:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7868:           }
                   7869:        } else {
                   7870: 	  &idput($udom,($uname => $uid));
                   7871:        }
                   7872:     }
                   7873: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7874:     my @tmp=&get('environment',
1.899     raeburn  7875: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7876:                     'permanentemail','inststatus'],
1.134     albertel 7877: 		   $udom,$uname);
1.1075    raeburn  7878:     my (%names,%oldnames);
1.313     matthew  7879:     if ($tmp[0] =~ m/^error:.*/) { 
                   7880:         %names=(); 
                   7881:     } else {
                   7882:         %names = @tmp;
1.1075    raeburn  7883:         %oldnames = %names;
1.313     matthew  7884:     }
1.388     www      7885: #
1.1058    raeburn  7886: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7887: # of users did not contain them), do not overwrite existing values
                   7888: # unless field is in $candelete array ref.  
                   7889: #
                   7890: 
                   7891:     my @fields = ('firstname','middlename','lastname','generation',
                   7892:                   'permanentemail','id');
                   7893:     my %newvalues;
                   7894:     if (ref($candelete) eq 'ARRAY') {
                   7895:         foreach my $field (@fields) {
                   7896:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7897:                 if ($field eq 'firstname') {
                   7898:                     $names{$field} = $first;
                   7899:                 } elsif ($field eq 'middlename') {
                   7900:                     $names{$field} = $middle;
                   7901:                 } elsif ($field eq 'lastname') {
                   7902:                     $names{$field} = $last;
                   7903:                 } elsif ($field eq 'generation') { 
                   7904:                     $names{$field} = $gene;
                   7905:                 } elsif ($field eq 'permanentemail') {
                   7906:                     $names{$field} = $email;
                   7907:                 } elsif ($field eq 'id') {
                   7908:                     $names{$field}  = $uid;
                   7909:                 }
                   7910:             }
                   7911:         }
                   7912:     }
1.388     www      7913:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7914:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7915:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7916:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7917:     if ($email) {
                   7918:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7919:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7920:     }
1.899     raeburn  7921:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7922:     if (defined($inststatus)) {
                   7923:         $names{'inststatus'} = '';
                   7924:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7925:         if (ref($usertypes) eq 'HASH') {
                   7926:             my @okstatuses; 
                   7927:             foreach my $item (split(/:/,$inststatus)) {
                   7928:                 if (defined($usertypes->{$item})) {
                   7929:                     push(@okstatuses,$item);  
                   7930:                 }
                   7931:             }
                   7932:             if (@okstatuses) {
                   7933:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7934:             }
                   7935:         }
                   7936:     }
1.1075    raeburn  7937:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7938:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7939:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7940:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7941:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7942:     } else {
                   7943:         $logmsg .= ' during self creation';
                   7944:     }
1.1075    raeburn  7945:     my $changed;
                   7946:     if ($newuser) {
                   7947:         $changed = 1;
                   7948:     } else {
                   7949:         foreach my $field (@fields) {
                   7950:             if ($names{$field} ne $oldnames{$field}) {
                   7951:                 $changed = 1;
                   7952:                 last;
                   7953:             }
                   7954:         }
                   7955:     }
                   7956:     unless ($changed) {
                   7957:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7958:         &logthis($logmsg);
                   7959:         return 'ok';
                   7960:     }
                   7961:     my $reply = &put('environment', \%names, $udom,$uname);
                   7962:     if ($reply ne 'ok') { 
                   7963:         return 'error: '.$reply;
                   7964:     }
1.1087    raeburn  7965:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7966:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7967:     }
1.1075    raeburn  7968:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7969:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7970:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7971:     &logthis($logmsg);
1.134     albertel 7972:     return 'ok';
1.80      www      7973: }
                   7974: 
1.81      www      7975: # -------------------------------------------------------------- Modify student
1.80      www      7976: 
1.81      www      7977: sub modifystudent {
                   7978:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7979:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7980:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7981:     if (!$cid) {
1.620     albertel 7982: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7983: 	    return 'not_in_class';
                   7984: 	}
1.80      www      7985:     }
                   7986: # --------------------------------------------------------------- Make the user
1.81      www      7987:     my $reply=&modifyuser
1.209     matthew  7988: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7989:          $desiredhome,$email,$inststatus);
1.80      www      7990:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7991:     # This will cause &modify_student_enrollment to get the uid from the
                   7992:     # students environment
                   7993:     $uid = undef if (!$forceid);
1.455     albertel 7994:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7995: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7996:     return $reply;
                   7997: }
                   7998: 
                   7999: sub modify_student_enrollment {
1.957     raeburn  8000:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 8001:     my ($cdom,$cnum,$chome);
                   8002:     if (!$cid) {
1.620     albertel 8003: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8004: 	    return 'not_in_class';
                   8005: 	}
1.620     albertel 8006: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8007: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8008:     } else {
                   8009: 	($cdom,$cnum)=split(/_/,$cid);
                   8010:     }
1.620     albertel 8011:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8012:     if (!$chome) {
1.457     raeburn  8013: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8014:     }
1.455     albertel 8015:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8016:     # Make sure the user exists
1.81      www      8017:     my $uhome=&homeserver($uname,$udom);
                   8018:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8019: 	return 'error: no such user';
                   8020:     }
1.297     matthew  8021:     # Get student data if we were not given enough information
                   8022:     if (!defined($first)  || $first  eq '' || 
                   8023:         !defined($last)   || $last   eq '' || 
                   8024:         !defined($uid)    || $uid    eq '' || 
                   8025:         !defined($middle) || $middle eq '' || 
                   8026:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8027:         # They did not supply us with enough data to enroll the student, so
                   8028:         # we need to pick up more information.
1.297     matthew  8029:         my %tmp = &get('environment',
1.294     matthew  8030:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8031:                        ,$udom,$uname);
                   8032: 
1.800     albertel 8033:         #foreach my $key (keys(%tmp)) {
                   8034:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8035:         #}
1.294     matthew  8036:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8037:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8038:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8039:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8040:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8041:     }
1.556     albertel 8042:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8043:     my $user = "$uname:$udom";
                   8044:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8045:     my $reply=cput('classlist',
1.1148    raeburn  8046: 		   {$user => 
1.515     raeburn  8047: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 8048: 		   $cdom,$cnum);
1.1148    raeburn  8049:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8050:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8051:     } else { 
1.81      www      8052: 	return 'error: '.$reply;
                   8053:     }
1.297     matthew  8054:     # Add student role to user
1.83      www      8055:     my $uurl='/'.$cid;
1.81      www      8056:     $uurl=~s/\_/\//g;
                   8057:     if ($usec) {
                   8058: 	$uurl.='/'.$usec;
                   8059:     }
1.1148    raeburn  8060:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8061:                              $selfenroll,$context);
                   8062:     if ($result ne 'ok') {
                   8063:         if ($old_entry{$user} ne '') {
                   8064:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8065:         } else {
                   8066:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8067:         }
                   8068:     }
                   8069:     return $result; 
1.21      www      8070: }
                   8071: 
1.556     albertel 8072: sub format_name {
                   8073:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8074:     my $name;
                   8075:     if ($first ne 'lastname') {
                   8076: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8077:     } else {
                   8078: 	if ($lastname=~/\S/) {
                   8079: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8080: 	    $name=~s/\s+,/,/;
                   8081: 	} else {
                   8082: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8083: 	}
                   8084:     }
                   8085:     $name=~s/^\s+//;
                   8086:     $name=~s/\s+$//;
                   8087:     $name=~s/\s+/ /g;
                   8088:     return $name;
                   8089: }
                   8090: 
1.84      www      8091: # ------------------------------------------------- Write to course preferences
                   8092: 
                   8093: sub writecoursepref {
                   8094:     my ($courseid,%prefs)=@_;
                   8095:     $courseid=~s/^\///;
                   8096:     $courseid=~s/\_/\//g;
                   8097:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8098:     my $chome=homeserver($cnum,$cdomain);
                   8099:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8100: 	return 'error: no such course';
                   8101:     }
                   8102:     my $cstring='';
1.800     albertel 8103:     foreach my $pref (keys(%prefs)) {
                   8104: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8105:     }
1.84      www      8106:     $cstring=~s/\&$//;
                   8107:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8108: }
                   8109: 
                   8110: # ---------------------------------------------------------- Make/modify course
                   8111: 
                   8112: sub createcourse {
1.741     raeburn  8113:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8114:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8115:     $url=&declutter($url);
                   8116:     my $cid='';
1.1028    raeburn  8117:     if ($context eq 'requestcourses') {
                   8118:         my $can_create = 0;
                   8119:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8120:         if ($udom eq $ownerdom) {
                   8121:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8122:                                   $context)) {
                   8123:                 $can_create = 1;
                   8124:             }
                   8125:         } else {
                   8126:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8127:                                            $category);
                   8128:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8129:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8130:                 if (@curr > 0) {
                   8131:                     my @options = qw(approval validate autolimit);
                   8132:                     my $optregex = join('|',@options);
                   8133:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8134:                         $can_create = 1;
                   8135:                     }
                   8136:                 }
                   8137:             }
                   8138:         }
                   8139:         if ($can_create) {
                   8140:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8141:                 unless (&allowed('ccc',$udom)) {
                   8142:                     return 'refused'; 
                   8143:                 }
1.1017    raeburn  8144:             }
                   8145:         } else {
                   8146:             return 'refused';
                   8147:         }
1.1028    raeburn  8148:     } elsif (!&allowed('ccc',$udom)) {
                   8149:         return 'refused';
1.84      www      8150:     }
1.1011    raeburn  8151: # --------------------------------------------------------------- Get Unique ID
                   8152:     my $uname;
                   8153:     if ($cnum =~ /^$match_courseid$/) {
                   8154:         my $chome=&homeserver($cnum,$udom,'true');
                   8155:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8156:             $uname = $cnum;
                   8157:         } else {
1.1038    raeburn  8158:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8159:         }
                   8160:     } else {
1.1038    raeburn  8161:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8162:     }
                   8163:     return $uname if ($uname =~ /^error/);
                   8164: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8165:     if (!defined($course_server)) {
                   8166:         if (defined(&domain($udom,'primary'))) {
                   8167:             $course_server = &domain($udom,'primary');
                   8168:         } else {
                   8169:             $course_server = $env{'user.home'}; 
                   8170:         }
                   8171:     }
                   8172:     my %host_servers =
                   8173:         &Apache::lonnet::get_servers($udom,'library');
                   8174:     unless ($host_servers{$course_server}) {
                   8175:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8176:     }
1.84      www      8177: # ------------------------------------------------------------- Make the course
                   8178:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8179:                       $course_server);
1.84      www      8180:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8181:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8182:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8183: 	return 'error: no such course';
                   8184:     }
1.271     www      8185: # ----------------------------------------------------------------- Course made
1.516     raeburn  8186: # log existence
1.1029    raeburn  8187:     my $now = time;
1.918     raeburn  8188:     my $newcourse = {
                   8189:                     $udom.'_'.$uname => {
1.921     raeburn  8190:                                      description => $description,
                   8191:                                      inst_code   => $inst_code,
                   8192:                                      owner       => $course_owner,
                   8193:                                      type        => $crstype,
1.1029    raeburn  8194:                                      creator     => $env{'user.name'}.':'.
                   8195:                                                     $env{'user.domain'},
                   8196:                                      created     => $now,
                   8197:                                      context     => $context,
1.918     raeburn  8198:                                                 },
                   8199:                     };
1.921     raeburn  8200:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8201: # set toplevel url
1.271     www      8202:     my $topurl=$url;
                   8203:     unless ($nonstandard) {
                   8204: # ------------------------------------------ For standard courses, make top url
                   8205:         my $mapurl=&clutter($url);
1.278     www      8206:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8207:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8208: <map>
                   8209: <resource id="1" type="start"></resource>
                   8210: <resource id="2" src="$mapurl"></resource>
                   8211: <resource id="3" type="finish"></resource>
                   8212: <link index="1" from="1" to="2"></link>
                   8213: <link index="2" from="2" to="3"></link>
                   8214: </map>
                   8215: ENDINITMAP
                   8216:         $topurl=&declutter(
1.638     albertel 8217:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8218:                           );
                   8219:     }
                   8220: # ----------------------------------------------------------- Write preferences
1.84      www      8221:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8222:                      ('description'              => $description,
                   8223:                       'url'                      => $topurl,
                   8224:                       'internal.creator'         => $env{'user.name'}.':'.
                   8225:                                                     $env{'user.domain'},
                   8226:                       'internal.created'         => $now,
                   8227:                       'internal.creationcontext' => $context)
                   8228:                     );
1.84      www      8229:     return '/'.$udom.'/'.$uname;
                   8230: }
                   8231: 
1.1011    raeburn  8232: # ------------------------------------------------------------------- Create ID
                   8233: sub generate_coursenum {
1.1038    raeburn  8234:     my ($udom,$crstype) = @_;
1.1011    raeburn  8235:     my $domdesc = &domain($udom);
                   8236:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8237:     my $first;
                   8238:     if ($crstype eq 'Community') {
                   8239:         $first = '0';
                   8240:     } else {
                   8241:         $first = int(1+rand(9)); 
                   8242:     } 
                   8243:     my $uname=$first.
1.1011    raeburn  8244:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8245:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8246:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8247: # ----------------------------------------------- Make sure that does not exist
                   8248:     my $uhome=&homeserver($uname,$udom,'true');
                   8249:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8250:         if ($crstype eq 'Community') {
                   8251:             $first = '0';
                   8252:         } else {
                   8253:             $first = int(1+rand(9));
                   8254:         }
                   8255:         $uname=$first.
1.1011    raeburn  8256:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8257:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8258:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8259:         $uhome=&homeserver($uname,$udom,'true');
                   8260:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8261:             return 'error: unable to generate unique course-ID';
                   8262:         }
                   8263:     }
                   8264:     return $uname;
                   8265: }
                   8266: 
1.813     albertel 8267: sub is_course {
1.1167    droeschl 8268:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8269:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8270: 
                   8271:     return unless $cdom and $cnum;
                   8272: 
                   8273:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8274:         '.');
                   8275: 
                   8276:     return unless exists($courses{$cdom.'_'.$cnum});
                   8277:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8278: }
                   8279: 
1.1015    raeburn  8280: sub store_userdata {
                   8281:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8282:     my $result;
1.1016    raeburn  8283:     if ($datakey ne '') {
1.1013    raeburn  8284:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8285:             if ($udom eq '' || $uname eq '') {
                   8286:                 $udom = $env{'user.domain'};
                   8287:                 $uname = $env{'user.name'};
                   8288:             }
                   8289:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8290:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8291:                 $result = 'error: no_host';
                   8292:             } else {
                   8293:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8294:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8295: 
                   8296:                 my $namevalue='';
                   8297:                 foreach my $key (keys(%{$storehash})) {
                   8298:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8299:                 }
                   8300:                 $namevalue=~s/\&$//;
1.1105    raeburn  8301:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8302:                                   $namevalue,$uhome);
1.1013    raeburn  8303:             }
                   8304:         } else {
                   8305:             $result = 'error: data to store was not a hash reference'; 
                   8306:         }
                   8307:     } else {
                   8308:         $result= 'error: invalid requestkey'; 
                   8309:     }
                   8310:     return $result;
                   8311: }
                   8312: 
1.21      www      8313: # ---------------------------------------------------------- Assign Custom Role
                   8314: 
                   8315: sub assigncustomrole {
1.957     raeburn  8316:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8317:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8318:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8319: }
                   8320: 
                   8321: # ----------------------------------------------------------------- Revoke Role
                   8322: 
                   8323: sub revokerole {
1.957     raeburn  8324:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8325:     my $now=time;
1.965     raeburn  8326:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8327: }
                   8328: 
                   8329: # ---------------------------------------------------------- Revoke Custom Role
                   8330: 
                   8331: sub revokecustomrole {
1.957     raeburn  8332:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8333:     my $now=time;
1.357     www      8334:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8335:            $deleteflag,$selfenroll,$context);
1.17      www      8336: }
                   8337: 
1.533     banghart 8338: # ------------------------------------------------------------ Disk usage
1.535     albertel 8339: sub diskusage {
1.955     raeburn  8340:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8341:     $directorypath =~ s/\/$//;
                   8342:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8343:                        .&escape($getpropath).':'.&escape($uname).':'
                   8344:                        .&escape($udom),homeserver($uname,$udom));
                   8345:     if ($listing eq 'unknown_cmd') {
                   8346:         if ($getpropath) {
                   8347:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8348:         }
                   8349:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8350:     }
1.514     albertel 8351:     return $listing;
1.512     banghart 8352: }
                   8353: 
1.566     banghart 8354: sub is_locked {
1.1096    raeburn  8355:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8356:     my @check;
                   8357:     my $is_locked;
1.1093    raeburn  8358:     push (@check,$file_name);
1.613     albertel 8359:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8360: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8361:     my ($tmp)=keys(%locked);
                   8362:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8363:     
1.566     banghart 8364:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8365:         $is_locked = 'false';
                   8366:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8367:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8368:                $is_locked = 'true';
1.1096    raeburn  8369:                if (ref($which) eq 'ARRAY') {
                   8370:                    push(@{$which},$entry);
                   8371:                } else {
                   8372:                    last;
                   8373:                }
1.745     raeburn  8374:            }
                   8375:        }
1.566     banghart 8376:     } else {
                   8377:         $is_locked = 'false';
                   8378:     }
1.1093    raeburn  8379:     return $is_locked;
1.566     banghart 8380: }
                   8381: 
1.759     albertel 8382: sub declutter_portfile {
                   8383:     my ($file) = @_;
1.833     albertel 8384:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8385:     return $file;
                   8386: }
                   8387: 
1.559     banghart 8388: # ------------------------------------------------------------- Mark as Read Only
                   8389: 
                   8390: sub mark_as_readonly {
                   8391:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8392:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8393:     my ($tmp)=keys(%current_permissions);
                   8394:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8395:     foreach my $file (@{$files}) {
1.759     albertel 8396: 	$file = &declutter_portfile($file);
1.561     banghart 8397:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8398:     }
1.613     albertel 8399:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8400:     return;
                   8401: }
                   8402: 
1.572     banghart 8403: # ------------------------------------------------------------Save Selected Files
                   8404: 
                   8405: sub save_selected_files {
                   8406:     my ($user, $path, @files) = @_;
                   8407:     my $filename = $user."savedfiles";
1.573     banghart 8408:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8409:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8410:     foreach my $file (@files) {
1.620     albertel 8411:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8412:     }
                   8413:     foreach my $file (@other_files) {
1.574     banghart 8414:         print (OUT $file."\n");
1.572     banghart 8415:     }
1.574     banghart 8416:     close (OUT);
1.572     banghart 8417:     return 'ok';
                   8418: }
                   8419: 
1.574     banghart 8420: sub clear_selected_files {
                   8421:     my ($user) = @_;
                   8422:     my $filename = $user."savedfiles";
1.1117    foxr     8423:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8424:     print (OUT undef);
                   8425:     close (OUT);
                   8426:     return ("ok");    
                   8427: }
                   8428: 
1.572     banghart 8429: sub files_in_path {
                   8430:     my ($user, $path) = @_;
                   8431:     my $filename = $user."savedfiles";
                   8432:     my %return_files;
1.1117    foxr     8433:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8434:     while (my $line_in = <IN>) {
1.574     banghart 8435:         chomp ($line_in);
                   8436:         my @paths_and_file = split (m!/!, $line_in);
                   8437:         my $file_part = pop (@paths_and_file);
                   8438:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8439:         $path_part.='/';
                   8440:         my $path_and_file = $path_part.$file_part;
                   8441:         if ($path_part eq $path) {
                   8442:             $return_files{$file_part}= 'selected';
                   8443:         }
                   8444:     }
1.574     banghart 8445:     close (IN);
                   8446:     return (\%return_files);
1.572     banghart 8447: }
                   8448: 
                   8449: # called in portfolio select mode, to show files selected NOT in current directory
                   8450: sub files_not_in_path {
                   8451:     my ($user, $path) = @_;
                   8452:     my $filename = $user."savedfiles";
                   8453:     my @return_files;
                   8454:     my $path_part;
1.1117    foxr     8455:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8456:     while (my $line = <IN>) {
1.572     banghart 8457:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8458:         my @paths_and_file = split(m|/|, $line);
                   8459:         my $file_part = pop(@paths_and_file);
                   8460:         chomp($file_part);
                   8461:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8462:         $path_part .= '/';
                   8463:         my $path_and_file = $path_part.$file_part;
                   8464:         if ($path_part ne $path) {
1.800     albertel 8465:             push(@return_files, ($path_and_file));
1.572     banghart 8466:         }
                   8467:     }
1.800     albertel 8468:     close(OUT);
1.574     banghart 8469:     return (@return_files);
1.572     banghart 8470: }
                   8471: 
1.745     raeburn  8472: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8473: 
1.745     raeburn  8474: sub get_portfile_permissions {
                   8475:     my ($domain,$user) = @_;
1.613     albertel 8476:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8477:     my ($tmp)=keys(%current_permissions);
                   8478:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8479:     return \%current_permissions;
                   8480: }
                   8481: 
                   8482: #---------------------------------------------Get portfolio file access controls
                   8483: 
1.749     raeburn  8484: sub get_access_controls {
1.745     raeburn  8485:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8486:     my %access;
                   8487:     my $real_file = $file;
                   8488:     $file =~ s/\.meta$//;
1.745     raeburn  8489:     if (defined($file)) {
1.749     raeburn  8490:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8491:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8492:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8493:             }
                   8494:         }
1.745     raeburn  8495:     } else {
1.749     raeburn  8496:         foreach my $key (keys(%{$current_permissions})) {
                   8497:             if ($key =~ /\0accesscontrol$/) {
                   8498:                 if (defined($group)) {
                   8499:                     if ($key !~ m-^\Q$group\E/-) {
                   8500:                         next;
                   8501:                     }
                   8502:                 }
                   8503:                 my ($fullpath) = split(/\0/,$key);
                   8504:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8505:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8506:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8507:                     }
                   8508:                 }
                   8509:             }
                   8510:         }
                   8511:     }
                   8512:     return %access;
                   8513: }
                   8514: 
                   8515: sub modify_access_controls {
                   8516:     my ($file_name,$changes,$domain,$user)=@_;
                   8517:     my ($outcome,$deloutcome);
                   8518:     my %store_permissions;
                   8519:     my %new_values;
                   8520:     my %new_control;
                   8521:     my %translation;
                   8522:     my @deletions = ();
                   8523:     my $now = time;
                   8524:     if (exists($$changes{'activate'})) {
                   8525:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8526:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8527:             my $numnew = scalar(@newitems);
                   8528:             for (my $i=0; $i<$numnew; $i++) {
                   8529:                 my $newkey = $newitems[$i];
                   8530:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8531:                 if ($newkey =~ /^\d+:/) { 
                   8532:                     $newkey =~ s/^(\d+)/$newid/;
                   8533:                     $translation{$1} = $newid;
                   8534:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8535:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8536:                     $translation{$1} = $newid;
                   8537:                 }
1.749     raeburn  8538:                 $new_values{$file_name."\0".$newkey} = 
                   8539:                                           $$changes{'activate'}{$newitems[$i]};
                   8540:                 $new_control{$newkey} = $now;
                   8541:             }
                   8542:         }
                   8543:     }
                   8544:     my %todelete;
                   8545:     my %changed_items;
                   8546:     foreach my $action ('delete','update') {
                   8547:         if (exists($$changes{$action})) {
                   8548:             if (ref($$changes{$action}) eq 'HASH') {
                   8549:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8550:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8551:                     if ($action eq 'delete') { 
                   8552:                         $todelete{$itemnum} = 1;
                   8553:                     } else {
                   8554:                         $changed_items{$itemnum} = $key;
                   8555:                     }
                   8556:                 }
1.745     raeburn  8557:             }
                   8558:         }
1.749     raeburn  8559:     }
                   8560:     # get lock on access controls for file.
                   8561:     my $lockhash = {
                   8562:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8563:                                                        ':'.$env{'user.domain'},
                   8564:                    }; 
                   8565:     my $tries = 0;
                   8566:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8567:    
                   8568:     while (($gotlock ne 'ok') && $tries <3) {
                   8569:         $tries ++;
                   8570:         sleep 1;
                   8571:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8572:     }
                   8573:     if ($gotlock eq 'ok') {
                   8574:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8575:         my ($tmp)=keys(%curr_permissions);
                   8576:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8577:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8578:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8579:             if (ref($curr_controls) eq 'HASH') {
                   8580:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8581:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8582:                     if (defined($todelete{$itemnum})) {
                   8583:                         push(@deletions,$file_name."\0".$control_item);
                   8584:                     } else {
                   8585:                         if (defined($changed_items{$itemnum})) {
                   8586:                             $new_control{$changed_items{$itemnum}} = $now;
                   8587:                             push(@deletions,$file_name."\0".$control_item);
                   8588:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8589:                         } else {
                   8590:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8591:                         }
                   8592:                     }
1.745     raeburn  8593:                 }
                   8594:             }
                   8595:         }
1.970     raeburn  8596:         my ($group);
                   8597:         if (&is_course($domain,$user)) {
                   8598:             ($group,my $file) = split(/\//,$file_name,2);
                   8599:         }
1.749     raeburn  8600:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8601:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8602:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8603:         #  remove lock
                   8604:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8605:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8606:         my $sqlresult =
1.970     raeburn  8607:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8608:                                     $group);
1.749     raeburn  8609:     } else {
                   8610:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8611:     }
1.749     raeburn  8612:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8613: }
                   8614: 
1.827     raeburn  8615: sub make_public_indefinitely {
                   8616:     my ($requrl) = @_;
                   8617:     my $now = time;
                   8618:     my $action = 'activate';
                   8619:     my $aclnum = 0;
                   8620:     if (&is_portfolio_url($requrl)) {
                   8621:         my (undef,$udom,$unum,$file_name,$group) =
                   8622:             &parse_portfolio_url($requrl);
                   8623:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8624:         my %access_controls = &get_access_controls($current_perms,
                   8625:                                                    $group,$file_name);
                   8626:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8627:             my ($num,$scope,$end,$start) = 
                   8628:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8629:             if ($scope eq 'public') {
                   8630:                 if ($start <= $now && $end == 0) {
                   8631:                     $action = 'none';
                   8632:                 } else {
                   8633:                     $action = 'update';
                   8634:                     $aclnum = $num;
                   8635:                 }
                   8636:                 last;
                   8637:             }
                   8638:         }
                   8639:         if ($action eq 'none') {
                   8640:              return 'ok';
                   8641:         } else {
                   8642:             my %changes;
                   8643:             my $newend = 0;
                   8644:             my $newstart = $now;
                   8645:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8646:             $changes{$action}{$newkey} = {
                   8647:                 type => 'public',
                   8648:                 time => {
                   8649:                     start => $newstart,
                   8650:                     end   => $newend,
                   8651:                 },
                   8652:             };
                   8653:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8654:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8655:             return $outcome;
                   8656:         }
                   8657:     } else {
                   8658:         return 'invalid';
                   8659:     }
                   8660: }
                   8661: 
1.745     raeburn  8662: #------------------------------------------------------Get Marked as Read Only
                   8663: 
                   8664: sub get_marked_as_readonly {
                   8665:     my ($domain,$user,$what,$group) = @_;
                   8666:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8667:     my @readonly_files;
1.629     banghart 8668:     my $cmp1=$what;
                   8669:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8670:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8671:         if (defined($group)) {
                   8672:             if ($file_name !~ m-^\Q$group\E/-) {
                   8673:                 next;
                   8674:             }
                   8675:         }
1.561     banghart 8676:         if (ref($value) eq "ARRAY"){
                   8677:             foreach my $stored_what (@{$value}) {
1.629     banghart 8678:                 my $cmp2=$stored_what;
1.759     albertel 8679:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8680:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8681:                 }
1.629     banghart 8682:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8683:                     push(@readonly_files, $file_name);
1.745     raeburn  8684:                     last;
1.563     banghart 8685:                 } elsif (!defined($what)) {
                   8686:                     push(@readonly_files, $file_name);
1.745     raeburn  8687:                     last;
1.561     banghart 8688:                 }
                   8689:             }
1.745     raeburn  8690:         }
1.561     banghart 8691:     }
                   8692:     return @readonly_files;
                   8693: }
1.577     banghart 8694: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8695: 
1.577     banghart 8696: sub get_marked_as_readonly_hash {
1.745     raeburn  8697:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8698:     my %readonly_files;
1.745     raeburn  8699:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8700:         if (defined($group)) {
                   8701:             if ($file_name !~ m-^\Q$group\E/-) {
                   8702:                 next;
                   8703:             }
                   8704:         }
1.577     banghart 8705:         if (ref($value) eq "ARRAY"){
                   8706:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8707:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8708:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8709:                         if ($lock_descriptor eq 'graded') {
                   8710:                             $readonly_files{$file_name} = 'graded';
                   8711:                         } elsif ($lock_descriptor eq 'handback') {
                   8712:                             $readonly_files{$file_name} = 'handback';
                   8713:                         } else {
                   8714:                             if (!exists($readonly_files{$file_name})) {
                   8715:                                 $readonly_files{$file_name} = 'locked';
                   8716:                             }
                   8717:                         }
1.745     raeburn  8718:                     }
1.750     banghart 8719:                 } 
1.577     banghart 8720:             }
                   8721:         } 
                   8722:     }
                   8723:     return %readonly_files;
                   8724: }
1.559     banghart 8725: # ------------------------------------------------------------ Unmark as Read Only
                   8726: 
                   8727: sub unmark_as_readonly {
1.629     banghart 8728:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8729:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8730:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8731:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8732:     my $symb_crs = $what;
                   8733:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8734:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8735:     my ($tmp)=keys(%current_permissions);
                   8736:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8737:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8738:     foreach my $file (@readonly_files) {
1.759     albertel 8739: 	my $clean_file = &declutter_portfile($file);
                   8740: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8741: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8742:         my @new_locks;
                   8743:         my @del_keys;
                   8744:         if (ref($current_locks) eq "ARRAY"){
                   8745:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8746:                 my $compare=$locker;
1.749     raeburn  8747:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8748:                     $compare=join('',@{$locker});
1.746     raeburn  8749:                     if ($compare ne $symb_crs) {
                   8750:                         push(@new_locks, $locker);
                   8751:                     }
1.563     banghart 8752:                 }
                   8753:             }
1.650     albertel 8754:             if (scalar(@new_locks) > 0) {
1.563     banghart 8755:                 $current_permissions{$file} = \@new_locks;
                   8756:             } else {
                   8757:                 push(@del_keys, $file);
1.613     albertel 8758:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8759:                 delete($current_permissions{$file});
1.563     banghart 8760:             }
                   8761:         }
1.561     banghart 8762:     }
1.613     albertel 8763:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8764:     return;
                   8765: }
1.512     banghart 8766: 
1.17      www      8767: # ------------------------------------------------------------ Directory lister
                   8768: 
                   8769: sub dirlist {
1.955     raeburn  8770:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8771:     $uri=~s/^\///;
                   8772:     $uri=~s/\/$//;
1.253     stredwic 8773:     my ($udom, $uname);
1.955     raeburn  8774:     if ($getuserdir) {
1.253     stredwic 8775:         $udom = $userdomain;
                   8776:         $uname = $username;
1.955     raeburn  8777:     } else {
                   8778:         (undef,$udom,$uname)=split(/\//,$uri);
                   8779:         if(defined($userdomain)) {
                   8780:             $udom = $userdomain;
                   8781:         }
                   8782:         if(defined($username)) {
                   8783:             $uname = $username;
                   8784:         }
1.253     stredwic 8785:     }
1.955     raeburn  8786:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8787: 
1.955     raeburn  8788:     $dirRoot = $perlvar{'lonDocRoot'};
                   8789:     if (defined($getpropath)) {
                   8790:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8791:         $dirRoot =~ s/\/$//;
1.955     raeburn  8792:     } elsif (defined($getuserdir)) {
                   8793:         my $subdir=$uname.'__';
                   8794:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8795:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8796:                    ."/$udom/$subdir/$uname";
                   8797:     } elsif (defined($alternateRoot)) {
                   8798:         $dirRoot = $alternateRoot;
1.751     banghart 8799:     }
1.253     stredwic 8800: 
                   8801:     if($udom) {
                   8802:         if($uname) {
1.1135    raeburn  8803:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8804:             if ($uhome eq 'no_host') {
                   8805:                 return ([],'no_host');
                   8806:             }
1.955     raeburn  8807:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8808:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8809:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8810:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8811:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8812:             } else {
                   8813:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8814:             }
1.605     matthew  8815:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8816:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8817:                 @listing_results = split(/:/,$listing);
                   8818:             } else {
                   8819:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8820:             }
1.1135    raeburn  8821:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8822:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8823:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8824:                 return ([],$listing);
                   8825:             } else {
                   8826:                 return (\@listing_results);
1.1135    raeburn  8827:             }
1.955     raeburn  8828:         } elsif(!$alternateRoot) {
1.1136    raeburn  8829:             my (%allusers,%listerror);
1.841     albertel 8830: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8831:  	    foreach my $tryserver (keys(%servers)) {
                   8832:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8833:                                   &escape($udom),$tryserver);
                   8834:                 if ($listing eq 'unknown_cmd') {
                   8835: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8836: 				      $udom, $tryserver);
                   8837:                 } else {
                   8838:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8839:                 }
1.841     albertel 8840: 		if ($listing eq 'unknown_cmd') {
                   8841: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8842: 				      $udom, $tryserver);
                   8843: 		    @listing_results = split(/:/,$listing);
                   8844: 		} else {
                   8845: 		    @listing_results =
                   8846: 			map { &unescape($_); } split(/:/,$listing);
                   8847: 		}
1.1136    raeburn  8848:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8849:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8850:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8851:                     $listerror{$tryserver} = $listing;
                   8852:                 } else {
1.841     albertel 8853: 		    foreach my $line (@listing_results) {
                   8854: 			my ($entry) = split(/&/,$line,2);
                   8855: 			$allusers{$entry} = 1;
                   8856: 		    }
                   8857: 		}
1.253     stredwic 8858:             }
1.1136    raeburn  8859:             my @alluserslist=();
1.800     albertel 8860:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8861:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8862:             }
1.1136    raeburn  8863:             return (\@alluserslist);
1.253     stredwic 8864:         } else {
1.1136    raeburn  8865:             return ([],'missing username');
1.253     stredwic 8866:         }
1.955     raeburn  8867:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8868:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8869:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8870:         return (\@all_domains);
1.955     raeburn  8871:     } else {
1.1136    raeburn  8872:         return ([],'missing domain');
1.275     stredwic 8873:     }
                   8874: }
                   8875: 
                   8876: # --------------------------------------------- GetFileTimestamp
                   8877: # This function utilizes dirlist and returns the date stamp for
                   8878: # when it was last modified.  It will also return an error of -1
                   8879: # if an error occurs
                   8880: 
                   8881: sub GetFileTimestamp {
1.955     raeburn  8882:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8883:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8884:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8885:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8886:                                     undef,$getuserdir);
                   8887:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8888:         return -1;
                   8889:     }
                   8890:     if (ref($fileref) eq 'ARRAY') {
                   8891:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8892:         # @stats contains first the filename, then the stat output
                   8893:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8894:     } else {
                   8895:         return -1;
1.253     stredwic 8896:     }
1.26      www      8897: }
                   8898: 
1.712     albertel 8899: sub stat_file {
                   8900:     my ($uri) = @_;
1.787     albertel 8901:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8902: 
1.955     raeburn  8903:     my ($udom,$uname,$file);
1.712     albertel 8904:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8905: 	($udom,$uname,$file) =
1.811     albertel 8906: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8907: 	$file = 'userfiles/'.$file;
                   8908:     }
                   8909:     if ($uri =~ m-^/res/-) {
                   8910: 	($udom,$uname) = 
1.807     albertel 8911: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8912: 	$file = $uri;
                   8913:     }
                   8914: 
                   8915:     if (!$udom || !$uname || !$file) {
                   8916: 	# unable to handle the uri
                   8917: 	return ();
                   8918:     }
1.956     raeburn  8919:     my $getpropath;
                   8920:     if ($file =~ /^userfiles\//) {
                   8921:         $getpropath = 1;
                   8922:     }
1.1136    raeburn  8923:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8924:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8925:         return ();
                   8926:     } else {
                   8927:         if (ref($listref) eq 'ARRAY') {
                   8928:             my @stats = split('&',$listref->[0]);
                   8929: 	    shift(@stats); #filename is first
                   8930: 	    return @stats;
                   8931:         }
1.712     albertel 8932:     }
                   8933:     return ();
                   8934: }
                   8935: 
1.26      www      8936: # -------------------------------------------------------- Value of a Condition
                   8937: 
1.713     albertel 8938: # gets the value of a specific preevaluated condition
                   8939: #    stored in the string  $env{user.state.<cid>}
                   8940: # or looks up a condition reference in the bighash and if if hasn't
                   8941: # already been evaluated recurses into docondval to get the value of
                   8942: # the condition, then memoizing it to 
                   8943: #   $env{user.state.<cid>.<condition>}
1.40      www      8944: sub directcondval {
                   8945:     my $number=shift;
1.620     albertel 8946:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8947: 	&Apache::lonuserstate::evalstate();
                   8948:     }
1.713     albertel 8949:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8950: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8951:     } elsif ($number =~ /^_/) {
                   8952: 	my $sub_condition;
                   8953: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8954: 		&GDBM_READER(),0640)) {
                   8955: 	    $sub_condition=$bighash{'conditions'.$number};
                   8956: 	    untie(%bighash);
                   8957: 	}
                   8958: 	my $value = &docondval($sub_condition);
1.949     raeburn  8959: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8960: 	return $value;
                   8961:     }
1.620     albertel 8962:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8963:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8964:     } else {
                   8965:        return 2;
                   8966:     }
                   8967: }
                   8968: 
1.713     albertel 8969: # get the collection of conditions for this resource
1.26      www      8970: sub condval {
                   8971:     my $condidx=shift;
1.54      www      8972:     my $allpathcond='';
1.713     albertel 8973:     foreach my $cond (split(/\|/,$condidx)) {
                   8974: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8975: 	    $allpathcond.=
                   8976: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8977: 	}
1.191     harris41 8978:     }
1.54      www      8979:     $allpathcond=~s/\|$//;
1.713     albertel 8980:     return &docondval($allpathcond);
                   8981: }
                   8982: 
                   8983: #evaluates an expression of conditions
                   8984: sub docondval {
                   8985:     my ($allpathcond) = @_;
                   8986:     my $result=0;
                   8987:     if ($env{'request.course.id'}
                   8988: 	&& defined($allpathcond)) {
                   8989: 	my $operand='|';
                   8990: 	my @stack;
                   8991: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8992: 	    if ($chunk eq '(') {
                   8993: 		push @stack,($operand,$result);
                   8994: 	    } elsif ($chunk eq ')') {
                   8995: 		my $before=pop @stack;
                   8996: 		if (pop @stack eq '&') {
                   8997: 		    $result=$result>$before?$before:$result;
                   8998: 		} else {
                   8999: 		    $result=$result>$before?$result:$before;
                   9000: 		}
                   9001: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9002: 		$operand=$chunk;
                   9003: 	    } else {
                   9004: 		my $new=directcondval($chunk);
                   9005: 		if ($operand eq '&') {
                   9006: 		    $result=$result>$new?$new:$result;
                   9007: 		} else {
                   9008: 		    $result=$result>$new?$result:$new;
                   9009: 		}
                   9010: 	    }
                   9011: 	}
1.26      www      9012:     }
                   9013:     return $result;
1.421     albertel 9014: }
                   9015: 
                   9016: # ---------------------------------------------------- Devalidate courseresdata
                   9017: 
                   9018: sub devalidatecourseresdata {
                   9019:     my ($coursenum,$coursedomain)=@_;
                   9020:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9021:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9022: }
                   9023: 
1.763     www      9024: 
1.200     www      9025: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9026: #
                   9027: #  Parameters:
                   9028: #      $coursenum    - Number of the course.
                   9029: #      $coursedomain - Domain at which the course was created.
                   9030: #  Returns:
                   9031: #     A hash of the course parameters along (I think) with timestamps
                   9032: #     and version info.
1.877     foxr     9033: 
1.624     albertel 9034: sub get_courseresdata {
                   9035:     my ($coursenum,$coursedomain)=@_;
1.200     www      9036:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9037:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9038:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9039:     my %dumpreply;
1.417     albertel 9040:     unless (defined($cached)) {
1.624     albertel 9041: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9042: 	$result=\%dumpreply;
1.251     albertel 9043: 	my ($tmp) = keys(%dumpreply);
                   9044: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9045: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9046: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9047: 	    return $tmp;
1.416     albertel 9048: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9049: 	    $result=undef;
1.599     albertel 9050: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9051: 	}
                   9052:     }
1.624     albertel 9053:     return $result;
                   9054: }
                   9055: 
1.633     albertel 9056: sub devalidateuserresdata {
                   9057:     my ($uname,$udom)=@_;
                   9058:     my $hashid="$udom:$uname";
                   9059:     &devalidate_cache_new('userres',$hashid);
                   9060: }
                   9061: 
1.624     albertel 9062: sub get_userresdata {
                   9063:     my ($uname,$udom)=@_;
                   9064:     #most student don\'t have any data set, check if there is some data
                   9065:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9066: 
                   9067:     my $hashid="$udom:$uname";
                   9068:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9069:     if (!defined($cached)) {
                   9070: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9071: 	$result=\%resourcedata;
                   9072: 	&do_cache_new('userres',$hashid,$result,600);
                   9073:     }
                   9074:     my ($tmp)=keys(%$result);
                   9075:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9076: 	return $result;
                   9077:     }
                   9078:     #error 2 occurs when the .db doesn't exist
                   9079:     if ($tmp!~/error: 2 /) {
1.672     albertel 9080: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9081: 		 " Trying to get resource data for ".
                   9082: 		 $uname." at ".$udom.": ".
                   9083: 		 $tmp."</font>");
                   9084:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9085: 	#&EXT_cache_set($udom,$uname);
                   9086: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9087: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9088:     }
                   9089:     return $tmp;
                   9090: }
1.879     foxr     9091: #----------------------------------------------- resdata - return resource data
                   9092: #  Purpose:
                   9093: #    Return resource data for either users or for a course.
                   9094: #  Parameters:
                   9095: #     $name      - Course/user name.
                   9096: #     $domain    - Name of the domain the user/course is registered on.
                   9097: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9098: #     @which     - Array of names of resources desired.
                   9099: #  Returns:
                   9100: #     The value of the first reasource in @which that is found in the
                   9101: #     resource hash.
                   9102: #  Exceptional Conditions:
                   9103: #     If the $type passed in is not valid (not the string 'course' or 
                   9104: #     'user', an undefined  reference is returned.
                   9105: #     If none of the resources are found, an undef is returned
1.624     albertel 9106: sub resdata {
                   9107:     my ($name,$domain,$type,@which)=@_;
                   9108:     my $result;
                   9109:     if ($type eq 'course') {
                   9110: 	$result=&get_courseresdata($name,$domain);
                   9111:     } elsif ($type eq 'user') {
                   9112: 	$result=&get_userresdata($name,$domain);
                   9113:     }
                   9114:     if (!ref($result)) { return $result; }    
1.251     albertel 9115:     foreach my $item (@which) {
1.927     albertel 9116: 	if (defined($result->{$item->[0]})) {
                   9117: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9118: 	}
1.250     albertel 9119:     }
1.291     albertel 9120:     return undef;
1.200     www      9121: }
                   9122: 
1.379     matthew  9123: #
                   9124: # EXT resource caching routines
                   9125: #
                   9126: 
                   9127: sub clear_EXT_cache_status {
1.383     albertel 9128:     &delenv('cache.EXT.');
1.379     matthew  9129: }
                   9130: 
                   9131: sub EXT_cache_status {
                   9132:     my ($target_domain,$target_user) = @_;
1.383     albertel 9133:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9134:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9135:         # We know already the user has no data
                   9136:         return 1;
                   9137:     } else {
                   9138:         return 0;
                   9139:     }
                   9140: }
                   9141: 
                   9142: sub EXT_cache_set {
                   9143:     my ($target_domain,$target_user) = @_;
1.383     albertel 9144:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9145:     #&appenv({$cachename => time});
1.379     matthew  9146: }
                   9147: 
1.28      www      9148: # --------------------------------------------------------- Value of a Variable
1.58      www      9149: sub EXT {
1.715     albertel 9150: 
1.395     albertel 9151:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9152:     unless ($varname) { return ''; }
1.218     albertel 9153:     #get real user name/domain, courseid and symb
                   9154:     my $courseid;
1.359     albertel 9155:     my $publicuser;
1.427     www      9156:     if ($symbparm) {
                   9157: 	$symbparm=&get_symb_from_alias($symbparm);
                   9158:     }
1.218     albertel 9159:     if (!($uname && $udom)) {
1.790     albertel 9160:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9161:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9162:     } else {
1.620     albertel 9163: 	$courseid=$env{'request.course.id'};
1.218     albertel 9164:     }
1.48      www      9165:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9166:     my $rest;
1.320     albertel 9167:     if (defined($therest[0])) {
1.48      www      9168:        $rest=join('.',@therest);
                   9169:     } else {
                   9170:        $rest='';
                   9171:     }
1.320     albertel 9172: 
1.57      www      9173:     my $qualifierrest=$qualifier;
                   9174:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9175:     my $spacequalifierrest=$space;
                   9176:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9177:     if ($realm eq 'user') {
1.48      www      9178: # --------------------------------------------------------------- user.resource
                   9179: 	if ($space eq 'resource') {
1.651     albertel 9180: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9181: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9182: 		 &&
1.744     albertel 9183: 		 ($symbparm eq &symbread()) ) {	
                   9184: 		# if we are in the middle of processing the resource the
                   9185: 		# get the value we are planning on committing
                   9186:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9187:                     return $Apache::lonhomework::results{$qualifierrest};
                   9188:                 } else {
                   9189:                     return $Apache::lonhomework::history{$qualifierrest};
                   9190:                 }
1.335     albertel 9191: 	    } else {
1.359     albertel 9192: 		my %restored;
1.620     albertel 9193: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9194: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9195: 		} else {
                   9196: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9197: 		}
1.335     albertel 9198: 		return $restored{$qualifierrest};
                   9199: 	    }
1.48      www      9200: # ----------------------------------------------------------------- user.access
                   9201:         } elsif ($space eq 'access') {
1.218     albertel 9202: 	    # FIXME - not supporting calls for a specific user
1.48      www      9203:             return &allowed($qualifier,$rest);
                   9204: # ------------------------------------------ user.preferences, user.environment
                   9205:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9206: 	    if (($uname eq $env{'user.name'}) &&
                   9207: 		($udom eq $env{'user.domain'})) {
                   9208: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9209: 	    } else {
1.359     albertel 9210: 		my %returnhash;
                   9211: 		if (!$publicuser) {
                   9212: 		    %returnhash=&userenvironment($udom,$uname,
                   9213: 						 $qualifierrest);
                   9214: 		}
1.218     albertel 9215: 		return $returnhash{$qualifierrest};
                   9216: 	    }
1.48      www      9217: # ----------------------------------------------------------------- user.course
                   9218:         } elsif ($space eq 'course') {
1.218     albertel 9219: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9220:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9221: # ------------------------------------------------------------------- user.role
                   9222:         } elsif ($space eq 'role') {
1.218     albertel 9223: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9224:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9225:             if ($qualifier eq 'value') {
                   9226: 		return $role;
                   9227:             } elsif ($qualifier eq 'extent') {
                   9228:                 return $where;
                   9229:             }
                   9230: # ----------------------------------------------------------------- user.domain
                   9231:         } elsif ($space eq 'domain') {
1.218     albertel 9232:             return $udom;
1.48      www      9233: # ------------------------------------------------------------------- user.name
                   9234:         } elsif ($space eq 'name') {
1.218     albertel 9235:             return $uname;
1.48      www      9236: # ---------------------------------------------------- Any other user namespace
1.29      www      9237:         } else {
1.359     albertel 9238: 	    my %reply;
                   9239: 	    if (!$publicuser) {
                   9240: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9241: 	    }
                   9242: 	    return $reply{$qualifierrest};
1.48      www      9243:         }
1.236     www      9244:     } elsif ($realm eq 'query') {
                   9245: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9246:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9247: 						[$spacequalifierrest]);
1.620     albertel 9248: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9249:    } elsif ($realm eq 'request') {
1.48      www      9250: # ------------------------------------------------------------- request.browser
                   9251:         if ($space eq 'browser') {
1.1145    bisitz   9252:             return $env{'browser.'.$qualifier};
1.57      www      9253: # ------------------------------------------------------------ request.filename
                   9254:         } else {
1.620     albertel 9255:             return $env{'request.'.$spacequalifierrest};
1.29      www      9256:         }
1.28      www      9257:     } elsif ($realm eq 'course') {
1.48      www      9258: # ---------------------------------------------------------- course.description
1.620     albertel 9259:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9260:     } elsif ($realm eq 'resource') {
1.165     www      9261: 
1.620     albertel 9262: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9263: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9264: 	}
1.693     albertel 9265: 
                   9266: 	if ($space eq 'title') {
                   9267: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9268: 	    return &gettitle($symbparm);
                   9269: 	}
                   9270: 	
                   9271: 	if ($space eq 'map') {
                   9272: 	    my ($map) = &decode_symb($symbparm);
                   9273: 	    return &symbread($map);
                   9274: 	}
1.905     albertel 9275: 	if ($space eq 'filename') {
                   9276: 	    if ($symbparm) {
                   9277: 		return &clutter((&decode_symb($symbparm))[2]);
                   9278: 	    }
                   9279: 	    return &hreflocation('',$env{'request.filename'});
                   9280: 	}
1.693     albertel 9281: 
                   9282: 	my ($section, $group, @groups);
1.593     albertel 9283: 	my ($courselevelm,$courselevel);
1.539     albertel 9284: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9285: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9286: 
1.218     albertel 9287: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9288: 
1.60      www      9289: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9290: 	    my $symbp=$symbparm;
1.735     albertel 9291: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9292: 
                   9293: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9294: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9295: 
1.620     albertel 9296: 	    if (($env{'user.name'} eq $uname) &&
                   9297: 		($env{'user.domain'} eq $udom)) {
                   9298: 		$section=$env{'request.course.sec'};
1.733     raeburn  9299:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9300:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9301: 	    } else {
1.539     albertel 9302: 		if (! defined($usection)) {
1.551     albertel 9303: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9304: 		} else {
                   9305: 		    $section = $usection;
                   9306: 		}
1.733     raeburn  9307:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9308: 	    }
                   9309: 
                   9310: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9311: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9312: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9313: 
1.593     albertel 9314: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9315: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9316: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9317: 
1.60      www      9318: # ----------------------------------------------------------- first, check user
1.624     albertel 9319: 
                   9320: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9321: 				       ([$courselevelr,'resource'],
                   9322: 					[$courselevelm,'map'     ],
                   9323: 					[$courselevel, 'course'  ]));
1.931     albertel 9324: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9325: 
1.594     albertel 9326: # ------------------------------------------------ second, check some of course
1.684     raeburn  9327:             my $coursereply;
1.691     raeburn  9328:             if (@groups > 0) {
                   9329:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9330:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9331:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9332:             }
1.96      www      9333: 
1.684     raeburn  9334: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9335: 				  $env{'course.'.$courseid.'.domain'},
                   9336: 				  'course',
                   9337: 				  ([$seclevelr,   'resource'],
                   9338: 				   [$seclevelm,   'map'     ],
                   9339: 				   [$seclevel,    'course'  ],
                   9340: 				   [$courselevelr,'resource']));
                   9341: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9342: 
1.60      www      9343: # ------------------------------------------------------ third, check map parms
1.218     albertel 9344: 	    my %parmhash=();
                   9345: 	    my $thisparm='';
                   9346: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9347: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9348: 		    &GDBM_READER(),0640)) {
1.218     albertel 9349: 		$thisparm=$parmhash{$symbparm};
                   9350: 		untie(%parmhash);
                   9351: 	    }
1.927     albertel 9352: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9353: 	}
1.594     albertel 9354: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9355: 
1.218     albertel 9356: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9357: 	my $filename;
                   9358: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9359: 	if ($symbparm) {
1.409     www      9360: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9361: 	} else {
1.620     albertel 9362: 	    $filename=$env{'request.filename'};
1.282     albertel 9363: 	}
                   9364: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9365: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9366: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9367: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9368: 
1.927     albertel 9369: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9370: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9371: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9372: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9373: 				     $env{'course.'.$courseid.'.domain'},
                   9374: 				     'course',
1.927     albertel 9375: 				     ([$courselevelm,'map'   ],
                   9376: 				      [$courselevel, 'course']));
                   9377: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9378: 	}
1.145     www      9379: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9380: 	unless ($space eq '0') {
1.336     albertel 9381: 	    my @parts=split(/_/,$space);
                   9382: 	    my $id=pop(@parts);
                   9383: 	    my $part=join('_',@parts);
                   9384: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9385: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9386: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9387: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9388: 	}
1.395     albertel 9389: 	if ($recurse) { return undef; }
                   9390: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9391: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9392: # ---------------------------------------------------- Any other user namespace
                   9393:     } elsif ($realm eq 'environment') {
                   9394: # ----------------------------------------------------------------- environment
1.620     albertel 9395: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9396: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9397: 	} else {
1.770     albertel 9398: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9399: 		return '';
                   9400: 	    }
1.219     albertel 9401: 	    my %returnhash=&userenvironment($udom,$uname,
                   9402: 					    $spacequalifierrest);
                   9403: 	    return $returnhash{$spacequalifierrest};
                   9404: 	}
1.28      www      9405:     } elsif ($realm eq 'system') {
1.48      www      9406: # ----------------------------------------------------------------- system.time
                   9407: 	if ($space eq 'time') {
                   9408: 	    return time;
                   9409:         }
1.696     albertel 9410:     } elsif ($realm eq 'server') {
                   9411: # ----------------------------------------------------------------- system.time
                   9412: 	if ($space eq 'name') {
                   9413: 	    return $ENV{'SERVER_NAME'};
                   9414:         }
1.28      www      9415:     }
1.48      www      9416:     return '';
1.61      www      9417: }
                   9418: 
1.927     albertel 9419: sub get_reply {
                   9420:     my ($reply_value) = @_;
1.940     raeburn  9421:     if (ref($reply_value) eq 'ARRAY') {
                   9422:         if (wantarray) {
                   9423: 	    return @$reply_value;
                   9424:         }
                   9425:         return $reply_value->[0];
                   9426:     } else {
                   9427:         return $reply_value;
1.927     albertel 9428:     }
                   9429: }
                   9430: 
1.691     raeburn  9431: sub check_group_parms {
                   9432:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9433:     my @groupitems = ();
                   9434:     my $resultitem;
1.927     albertel 9435:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9436:     foreach my $group (@{$groups}) {
                   9437:         foreach my $level (@levels) {
1.927     albertel 9438:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9439:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9440:         }
                   9441:     }
                   9442:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9443:                             $env{'course.'.$courseid.'.domain'},
                   9444:                                      'course',@groupitems);
                   9445:     return $coursereply;
                   9446: }
                   9447: 
                   9448: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9449:     my ($courseid,@groups) = @_;
                   9450:     @groups = sort(@groups);
1.691     raeburn  9451:     return @groups;
                   9452: }
                   9453: 
1.395     albertel 9454: sub packages_tab_default {
                   9455:     my ($uri,$varname)=@_;
                   9456:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9457: 
                   9458:     my (@extension,@specifics,$do_default);
                   9459:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9460: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9461: 	if ($pack_type eq 'default') {
                   9462: 	    $do_default=1;
                   9463: 	} elsif ($pack_type eq 'extension') {
                   9464: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9465: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9466: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9467: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9468: 	}
                   9469:     }
                   9470:     # first look for a package that matches the requested part id
                   9471:     foreach my $package (@specifics) {
                   9472: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9473: 	next if ($pack_part ne $part);
                   9474: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9475: 	    return $packagetab{"$pack_type&$name&default"};
                   9476: 	}
                   9477:     }
                   9478:     # look for any possible matching non extension_ package
                   9479:     foreach my $package (@specifics) {
                   9480: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9481: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9482: 	    return $packagetab{"$pack_type&$name&default"};
                   9483: 	}
1.585     albertel 9484: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9485: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9486: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9487: 	}
                   9488:     }
1.738     albertel 9489:     # look for any posible extension_ match
                   9490:     foreach my $package (@extension) {
                   9491: 	my ($package,$pack_type)=@{$package};
                   9492: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9493: 	    return $packagetab{"$pack_type&$name&default"};
                   9494: 	}
                   9495: 	if (defined($packagetab{$package."&$name&default"})) {
                   9496: 	    return $packagetab{$package."&$name&default"};
                   9497: 	}
                   9498:     }
                   9499:     # look for a global default setting
                   9500:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9501: 	return $packagetab{"default&$name&default"};
                   9502:     }
1.395     albertel 9503:     return undef;
                   9504: }
                   9505: 
1.334     albertel 9506: sub add_prefix_and_part {
                   9507:     my ($prefix,$part)=@_;
                   9508:     my $keyroot;
                   9509:     if (defined($prefix) && $prefix !~ /^__/) {
                   9510: 	# prefix that has a part already
                   9511: 	$keyroot=$prefix;
                   9512:     } elsif (defined($prefix)) {
                   9513: 	# prefix that is missing a part
                   9514: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9515:     } else {
                   9516: 	# no prefix at all
                   9517: 	if (defined($part)) { $keyroot='_'.$part; }
                   9518:     }
                   9519:     return $keyroot;
                   9520: }
                   9521: 
1.71      www      9522: # ---------------------------------------------------------------- Get metadata
                   9523: 
1.599     albertel 9524: my %metaentry;
1.1070    www      9525: my %importedpartids;
1.71      www      9526: sub metadata {
1.176     www      9527:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9528:     $uri=&declutter($uri);
1.288     albertel 9529:     # if it is a non metadata possible uri return quickly
1.529     albertel 9530:     if (($uri eq '') || 
                   9531: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9532: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9533:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9534: 	return undef;
                   9535:     }
1.1140    www      9536:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9537: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9538: 	return undef;
1.288     albertel 9539:     }
1.73      www      9540:     my $filename=$uri;
                   9541:     $uri=~s/\.meta$//;
1.172     www      9542: #
                   9543: # Is the metadata already cached?
1.177     www      9544: # Look at timestamp of caching
1.172     www      9545: # Everything is cached by the main uri, libraries are never directly cached
                   9546: #
1.428     albertel 9547:     if (!defined($liburi)) {
1.599     albertel 9548: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9549: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9550:     }
                   9551:     {
1.1069    www      9552: # Imported parts would go here
1.1070    www      9553:         my %importedids=();
                   9554:         my @origfileimportpartids=();
1.1069    www      9555:         my $importedparts=0;
1.172     www      9556: #
                   9557: # Is this a recursive call for a library?
                   9558: #
1.599     albertel 9559: #	if (! exists($metacache{$uri})) {
                   9560: #	    $metacache{$uri}={};
                   9561: #	}
1.924     albertel 9562: 	my $cachetime = 60*60;
1.171     www      9563:         if ($liburi) {
                   9564: 	    $liburi=&declutter($liburi);
                   9565:             $filename=$liburi;
1.401     bowersj2 9566:         } else {
1.599     albertel 9567: 	    &devalidate_cache_new('meta',$uri);
                   9568: 	    undef(%metaentry);
1.401     bowersj2 9569: 	}
1.140     www      9570:         my %metathesekeys=();
1.73      www      9571:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9572: 	my $metastring;
1.1140    www      9573: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9574: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9575: 	    $metastring = 
1.929     albertel 9576: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9577: 					  ('grade_target' => 'meta'));
                   9578: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9579: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9580:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9581: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9582: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9583: 	    $metastring=&getfile($file);
1.489     albertel 9584: 	}
1.208     albertel 9585:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9586:         my $token;
1.140     www      9587:         undef %metathesekeys;
1.71      www      9588:         while ($token=$parser->get_token) {
1.339     albertel 9589: 	    if ($token->[0] eq 'S') {
                   9590: 		if (defined($token->[2]->{'package'})) {
1.172     www      9591: #
                   9592: # This is a package - get package info
                   9593: #
1.339     albertel 9594: 		    my $package=$token->[2]->{'package'};
                   9595: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9596: 		    if (defined($token->[2]->{'id'})) { 
                   9597: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9598: 		    }
1.599     albertel 9599: 		    if ($metaentry{':packages'}) {
                   9600: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9601: 		    } else {
1.599     albertel 9602: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9603: 		    }
1.736     albertel 9604: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9605: 			my $part=$keyroot;
                   9606: 			$part=~s/^\_//;
1.736     albertel 9607: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9608: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9609: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9610: 			    # ignore package.tab specified default values
                   9611:                             # here &package_tab_default() will fetch those
                   9612: 			    if ($subp eq 'default') { next; }
1.736     albertel 9613: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9614: 			    my $unikey;
                   9615: 			    if ($pack =~ /_0$/) {
                   9616: 				$unikey='parameter_0_'.$name;
                   9617: 				$part=0;
                   9618: 			    } else {
                   9619: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9620: 			    }
1.339     albertel 9621: 			    if ($subp eq 'display') {
                   9622: 				$value.=' [Part: '.$part.']';
                   9623: 			    }
1.599     albertel 9624: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9625: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9626: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9627: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9628: 			    }
1.599     albertel 9629: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9630: 				$metaentry{':'.$unikey}=
                   9631: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9632: 			    }
1.339     albertel 9633: 			}
                   9634: 		    }
                   9635: 		} else {
1.172     www      9636: #
                   9637: # This is not a package - some other kind of start tag
1.339     albertel 9638: #
                   9639: 		    my $entry=$token->[1];
1.1068    www      9640: 		    my $unikey='';
1.175     www      9641: 
1.339     albertel 9642: 		    if ($entry eq 'import') {
1.175     www      9643: #
                   9644: # Importing a library here
1.339     albertel 9645: #
1.1067    www      9646:                         my $location=$parser->get_text('/import');
                   9647:                         my $dir=$filename;
                   9648:                         $dir=~s|[^/]*$||;
                   9649:                         $location=&filelocation($dir,$location);
1.1069    www      9650:                        
1.1068    www      9651:                         my $importmode=$token->[2]->{'importmode'};
                   9652:                         if ($importmode eq 'problem') {
1.1069    www      9653: # Import as problem/response
1.1068    www      9654:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9655:                         } elsif ($importmode eq 'part') {
                   9656: # Import as part(s)
1.1069    www      9657:                            $importedparts=1;
                   9658: # We need to get the original file and the imported file to get the part order correct
                   9659: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9660: # Load and inspect original file
1.1070    www      9661:                            if ($#origfileimportpartids<0) {
                   9662:                               undef(%importedpartids);
                   9663:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9664:                               my $origfile=&getfile($origfilelocation);
                   9665:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9666:                            }
                   9667: 
1.1069    www      9668: # Load and inspect imported file
                   9669:                            my $impfile=&getfile($location);
                   9670:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9671:                            if ($#impfilepartids>=0) {
                   9672: # This problem had parts
1.1070    www      9673:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9674:                            } else {
                   9675: # Importing by turning a single problem into a problem part
                   9676: # It gets the import-tags ID as part-ID
                   9677:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9678:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9679:                            }
1.1068    www      9680:                         } else {
                   9681: # Normal import
                   9682:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9683:                            if (defined($token->[2]->{'id'})) {
                   9684:                               $unikey.='_'.$token->[2]->{'id'};
                   9685:                            }
1.1067    www      9686:                         }
                   9687: 
1.339     albertel 9688: 			if ($depthcount<20) {
1.736     albertel 9689: 			    my $metadata = 
                   9690: 				&metadata($uri,'keys', $location,$unikey,
                   9691: 					  $depthcount+1);
                   9692: 			    foreach my $meta (split(',',$metadata)) {
                   9693: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9694: 				$metathesekeys{$meta}=1;
1.339     albertel 9695: 			    }
1.1068    www      9696: 			
                   9697:                         }
1.1067    www      9698: 		    } else {
                   9699: #
                   9700: # Not importing, some other kind of non-package, non-library start tag
                   9701: # 
                   9702:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9703:                         if (defined($token->[2]->{'id'})) {
                   9704:                             $unikey.='_'.$token->[2]->{'id'};
                   9705:                         }
1.339     albertel 9706: 			if (defined($token->[2]->{'name'})) { 
                   9707: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9708: 			}
                   9709: 			$metathesekeys{$unikey}=1;
1.736     albertel 9710: 			foreach my $param (@{$token->[3]}) {
                   9711: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9712: 				$token->[2]->{$param};
1.339     albertel 9713: 			}
                   9714: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9715: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9716: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9717: 		 # only ws inside the tag, and not in default, so use default
                   9718: 		 # as value
1.599     albertel 9719: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9720: 			} elsif ( $internaltext =~ /\S/ ) {
                   9721: 		  # something interesting inside the tag
                   9722: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9723: 			} else {
1.908     albertel 9724: 		  # no interesting values, don't set a default
1.339     albertel 9725: 			}
1.172     www      9726: # end of not-a-package not-a-library import
1.339     albertel 9727: 		    }
1.172     www      9728: # end of not-a-package start tag
1.339     albertel 9729: 		}
1.172     www      9730: # the next is the end of "start tag"
1.339     albertel 9731: 	    }
                   9732: 	}
1.483     albertel 9733: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9734: 	$extension = lc($extension);
                   9735: 	if ($extension eq 'htm') { $extension='html'; }
                   9736: 
1.737     albertel 9737: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9738: 	    #no specific packages #how's our extension
                   9739: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9740: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9741: 					 \%metathesekeys);
                   9742: 	}
1.883     albertel 9743: 
                   9744: 	if (!exists($metaentry{':packages'})
                   9745: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9746: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9747: 		#no specific packages well let's get default then
                   9748: 		if ($key!~/^default&/) { next; }
1.488     albertel 9749: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9750: 					     \%metathesekeys);
                   9751: 	    }
                   9752: 	}
1.338     www      9753: # are there custom rights to evaluate
1.599     albertel 9754: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9755: 
1.338     www      9756:     #
                   9757:     # Importing a rights file here
1.339     albertel 9758:     #
                   9759: 	    unless ($depthcount) {
1.599     albertel 9760: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9761: 		my $dir=$filename;
                   9762: 		$dir=~s|[^/]*$||;
                   9763: 		$location=&filelocation($dir,$location);
1.736     albertel 9764: 		my $rights_metadata =
                   9765: 		    &metadata($uri,'keys',$location,'_rights',
                   9766: 			      $depthcount+1);
                   9767: 		foreach my $rights (split(',',$rights_metadata)) {
                   9768: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9769: 		    $metathesekeys{$rights}=1;
1.339     albertel 9770: 		}
                   9771: 	    }
                   9772: 	}
1.737     albertel 9773: 	# uniqifiy package listing
                   9774: 	my %seen;
                   9775: 	my @uniq_packages =
                   9776: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9777: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9778: 
1.1070    www      9779:         if ($importedparts) {
                   9780: # We had imported parts and need to rebuild partorder
                   9781:            $metaentry{':partorder'}='';
                   9782:            $metathesekeys{'partorder'}=1;
                   9783:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9784:                if ($origfileimportpartids[$index] eq 'part') {
                   9785: # original part, part of the problem
                   9786:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9787:                } else {
                   9788: # we have imported parts at this position
                   9789:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9790:                }
                   9791:            }
                   9792:            $metaentry{':partorder'}=~s/^\,//;
                   9793:         }
                   9794: 
1.737     albertel 9795: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9796: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9797: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9798: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9799: # this is the end of "was not already recently cached
1.71      www      9800:     }
1.599     albertel 9801:     return $metaentry{':'.$what};
1.261     albertel 9802: }
                   9803: 
1.488     albertel 9804: sub metadata_create_package_def {
1.483     albertel 9805:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9806:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9807:     if ($subp eq 'default') { next; }
                   9808:     
1.599     albertel 9809:     if (defined($metaentry{':packages'})) {
                   9810: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9811:     } else {
1.599     albertel 9812: 	$metaentry{':packages'}=$package;
1.483     albertel 9813:     }
                   9814:     my $value=$packagetab{$key};
                   9815:     my $unikey;
                   9816:     $unikey='parameter_0_'.$name;
1.599     albertel 9817:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9818:     $$metathesekeys{$unikey}=1;
1.599     albertel 9819:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9820: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9821:     }
1.599     albertel 9822:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9823: 	$metaentry{':'.$unikey}=
                   9824: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9825:     }
                   9826: }
                   9827: 
1.261     albertel 9828: sub metadata_generate_part0 {
                   9829:     my ($metadata,$metacache,$uri) = @_;
                   9830:     my %allnames;
1.737     albertel 9831:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9832: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9833: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9834: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9835: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9836: 	    $allnames{$name}=$part;
                   9837: 	  }
                   9838: 	}
                   9839:     }
                   9840:     foreach my $name (keys(%allnames)) {
                   9841:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9842:       my $key=":parameter_0_$name";
1.261     albertel 9843:       $$metacache{"$key.part"}='0';
                   9844:       $$metacache{"$key.name"}=$name;
1.428     albertel 9845:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9846: 					   $allnames{$name}.'_'.$name.
                   9847: 					   '.type'};
1.428     albertel 9848:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9849: 			     '.display'};
1.644     www      9850:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9851:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9852:       $$metacache{"$key.display"}=$olddis;
                   9853:     }
1.71      www      9854: }
                   9855: 
1.764     albertel 9856: # ------------------------------------------------------ Devalidate title cache
                   9857: 
                   9858: sub devalidate_title_cache {
                   9859:     my ($url)=@_;
                   9860:     if (!$env{'request.course.id'}) { return; }
                   9861:     my $symb=&symbread($url);
                   9862:     if (!$symb) { return; }
                   9863:     my $key=$env{'request.course.id'}."\0".$symb;
                   9864:     &devalidate_cache_new('title',$key);
                   9865: }
                   9866: 
1.1014    droeschl 9867: # ------------------------------------------------- Get the title of a course
                   9868: 
                   9869: sub current_course_title {
                   9870:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9871: }
1.301     www      9872: # ------------------------------------------------- Get the title of a resource
                   9873: 
                   9874: sub gettitle {
                   9875:     my $urlsymb=shift;
                   9876:     my $symb=&symbread($urlsymb);
1.534     albertel 9877:     if ($symb) {
1.620     albertel 9878: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9879: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9880: 	if (defined($cached)) { 
                   9881: 	    return $result;
                   9882: 	}
1.534     albertel 9883: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9884: 	my $title='';
1.907     albertel 9885: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9886: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9887: 	} else {
                   9888: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9889: 		    &GDBM_READER(),0640)) {
                   9890: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9891: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9892: 		untie(%bighash);
                   9893: 	    }
1.534     albertel 9894: 	}
                   9895: 	$title=~s/\&colon\;/\:/gs;
                   9896: 	if ($title) {
1.1159    www      9897: # Remember both $symb and $title for dynamic metadata
                   9898:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9899:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9900: # Cache this title and then return it
1.599     albertel 9901: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9902: 	}
                   9903: 	$urlsymb=$url;
                   9904:     }
                   9905:     my $title=&metadata($urlsymb,'title');
                   9906:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9907:     return $title;
1.301     www      9908: }
1.613     albertel 9909: 
1.614     albertel 9910: sub get_slot {
                   9911:     my ($which,$cnum,$cdom)=@_;
                   9912:     if (!$cnum || !$cdom) {
1.790     albertel 9913: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9914: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9915: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9916:     }
1.703     albertel 9917:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9918:     my %slotinfo;
                   9919:     if (exists($remembered{$key})) {
                   9920: 	$slotinfo{$which} = $remembered{$key};
                   9921:     } else {
                   9922: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9923: 	&Apache::lonhomework::showhash(%slotinfo);
                   9924: 	my ($tmp)=keys(%slotinfo);
                   9925: 	if ($tmp=~/^error:/) { return (); }
                   9926: 	$remembered{$key} = $slotinfo{$which};
                   9927:     }
1.616     albertel 9928:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9929: 	return %{$slotinfo{$which}};
                   9930:     }
                   9931:     return $slotinfo{$which};
1.614     albertel 9932: }
1.1150    raeburn  9933: 
                   9934: sub get_reservable_slots {
                   9935:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9936:     my $now = time;
                   9937:     my $reservable_info;
                   9938:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9939:     if (exists($remembered{$key})) {
                   9940:         $reservable_info = $remembered{$key};
                   9941:     } else {
                   9942:         my %resv;
                   9943:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9944:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9945:         $reservable_info = \%resv;
                   9946:         $remembered{$key} = $reservable_info;
                   9947:     }
                   9948:     return $reservable_info;
                   9949: }
                   9950: 
                   9951: sub get_course_slots {
                   9952:     my ($cnum,$cdom) = @_;
                   9953:     my $hashid=$cnum.':'.$cdom;
                   9954:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9955:     if (defined($cached)) {
                   9956:         if (ref($result) eq 'HASH') {
                   9957:             return %{$result};
                   9958:         }
                   9959:     } else {
                   9960:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9961:         my ($tmp) = keys(%slots);
                   9962:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9963:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9964:             return %slots;
                   9965:         }
                   9966:     }
                   9967:     return;
                   9968: }
                   9969: 
                   9970: sub devalidate_slots_cache {
                   9971:     my ($cnum,$cdom)=@_;
                   9972:     my $hashid=$cnum.':'.$cdom;
                   9973:     &devalidate_cache_new('allslots',$hashid);
                   9974: }
                   9975: 
1.1181    raeburn  9976: sub get_coursechange {
                   9977:     my ($cdom,$cnum) = @_;
                   9978:     if ($cdom eq '' || $cnum eq '') {
                   9979:         return unless ($env{'request.course.id'});
                   9980:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9981:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9982:     }
                   9983:     my $hashid=$cdom.'_'.$cnum;
                   9984:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   9985:     if ((defined($cached)) && ($change ne '')) {
                   9986:         return $change;
                   9987:     } else {
                   9988:         my %crshash;
                   9989:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   9990:         if ($crshash{'internal.contentchange'} eq '') {
                   9991:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   9992:             if ($change eq '') {
                   9993:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   9994:                 $change = $crshash{'internal.created'};
                   9995:             }
                   9996:         } else {
                   9997:             $change = $crshash{'internal.contentchange'};
                   9998:         }
                   9999:         my $cachetime = 600;
                   10000:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10001:     }
                   10002:     return $change;
                   10003: }
                   10004: 
                   10005: sub devalidate_coursechange_cache {
                   10006:     my ($cnum,$cdom)=@_;
                   10007:     my $hashid=$cnum.':'.$cdom;
                   10008:     &devalidate_cache_new('crschange',$hashid);
                   10009: }
                   10010: 
1.31      www      10011: # ------------------------------------------------- Update symbolic store links
                   10012: 
                   10013: sub symblist {
                   10014:     my ($mapname,%newhash)=@_;
1.438     www      10015:     $mapname=&deversion(&declutter($mapname));
1.31      www      10016:     my %hash;
1.620     albertel 10017:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10018:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10019:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10020: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10021: 		next if ($url eq 'last_known'
                   10022: 			 && $env{'form.no_update_last_known'});
                   10023: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10024: 						    $newhash{$url}->[1],
                   10025: 						    $newhash{$url}->[0]);
1.191     harris41 10026:             }
1.31      www      10027:             if (untie(%hash)) {
                   10028: 		return 'ok';
                   10029:             }
                   10030:         }
                   10031:     }
                   10032:     return 'error';
1.212     www      10033: }
                   10034: 
                   10035: # --------------------------------------------------------------- Verify a symb
                   10036: 
                   10037: sub symbverify {
1.1190    raeburn  10038:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10039:     my $thisfn=$thisurl;
1.439     www      10040:     $thisfn=&declutter($thisfn);
1.215     www      10041: # direct jump to resource in page or to a sequence - will construct own symbs
                   10042:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10043: # check URL part
1.409     www      10044:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10045: 
1.431     www      10046:     unless ($url eq $thisfn) { return 0; }
1.213     www      10047: 
1.216     www      10048:     $symb=&symbclean($symb);
1.510     www      10049:     $thisurl=&deversion($thisurl);
1.439     www      10050:     $thisfn=&deversion($thisfn);
1.213     www      10051: 
                   10052:     my %bighash;
                   10053:     my $okay=0;
1.431     www      10054: 
1.620     albertel 10055:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10056:                             &GDBM_READER(),0640)) {
1.1032    raeburn  10057:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10058:             $thisurl =~ s/\?.+$//;
                   10059:         }
1.510     www      10060:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  10061:         unless ($ids) {
                   10062:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10063:             $ids=$bighash{$idkey};
1.216     www      10064:         }
                   10065:         if ($ids) {
                   10066: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 10067: 	    foreach my $id (split(/\,/,$ids)) {
                   10068: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  10069:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10070:                    $symb =~ s/\?.+$//;
                   10071:                }
1.216     www      10072:                if (
                   10073:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10074:    eq $symb) {
                   10075:                    if (ref($encstate)) {
                   10076:                        $$encstate = $bighash{'encrypted_'.$id};
                   10077:                    }
1.620     albertel 10078: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10079: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10080:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10081: 		       $okay=1;
1.582     albertel 10082: 		   }
                   10083: 	       }
1.216     www      10084: 	   }
                   10085:         }
1.213     www      10086: 	untie(%bighash);
                   10087:     }
                   10088:     return $okay;
1.31      www      10089: }
                   10090: 
1.210     www      10091: # --------------------------------------------------------------- Clean-up symb
                   10092: 
                   10093: sub symbclean {
                   10094:     my $symb=shift;
1.568     albertel 10095:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10096: # remove version from map
                   10097:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10098: 
1.210     www      10099: # remove version from URL
                   10100:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10101: 
1.507     www      10102: # remove wrapper
                   10103: 
1.510     www      10104:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10105:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10106:     return $symb;
1.409     www      10107: }
                   10108: 
                   10109: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10110: 
                   10111: sub encode_symb {
                   10112:     my ($map,$resid,$url)=@_;
                   10113:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10114: }
1.409     www      10115: 
                   10116: sub decode_symb {
1.568     albertel 10117:     my $symb=shift;
                   10118:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10119:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10120:     return (&fixversion($map),$resid,&fixversion($url));
                   10121: }
                   10122: 
                   10123: sub fixversion {
                   10124:     my $fn=shift;
1.609     banghart 10125:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10126:     my %bighash;
                   10127:     my $uri=&clutter($fn);
1.620     albertel 10128:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10129: # is this cached?
1.599     albertel 10130:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10131:     if (defined($cached)) { return $result; }
                   10132: # unfortunately not cached, or expired
1.620     albertel 10133:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10134: 	    &GDBM_READER(),0640)) {
                   10135:  	if ($bighash{'version_'.$uri}) {
                   10136:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10137:  	    unless (($version eq 'mostrecent') || 
                   10138: 		    ($version==&getversion($uri))) {
1.440     www      10139:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10140:  	    }
                   10141:  	}
                   10142:  	untie %bighash;
1.413     www      10143:     }
1.599     albertel 10144:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10145: }
                   10146: 
                   10147: sub deversion {
                   10148:     my $url=shift;
                   10149:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10150:     return $url;
1.210     www      10151: }
                   10152: 
1.31      www      10153: # ------------------------------------------------------ Return symb list entry
                   10154: 
                   10155: sub symbread {
1.249     www      10156:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 10157:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1179    raeburn  10158:     if (defined($env{$cache_str})) {
                   10159:         if (($thisfn) || ($env{$cache_str} ne '')) {
                   10160:             return $env{$cache_str};
                   10161:         }
                   10162:     }
1.242     www      10163: # no filename provided? try from environment
1.44      www      10164:     unless ($thisfn) {
1.620     albertel 10165:         if ($env{'request.symb'}) {
                   10166: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10167: 	}
1.620     albertel 10168: 	$thisfn=$env{'request.filename'};
1.44      www      10169:     }
1.569     albertel 10170:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10171: # is that filename actually a symb? Verify, clean, and return
                   10172:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10173: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10174: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10175: 	}
1.242     www      10176:     }
1.44      www      10177:     $thisfn=declutter($thisfn);
1.31      www      10178:     my %hash;
1.37      www      10179:     my %bighash;
                   10180:     my $syval='';
1.620     albertel 10181:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10182:         my $targetfn = $thisfn;
1.609     banghart 10183:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10184:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10185:         }
1.687     albertel 10186: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10187: 	    $targetfn=$1;
                   10188: 	}
1.620     albertel 10189:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10190:                       &GDBM_READER(),0640)) {
1.481     raeburn  10191: 	    $syval=$hash{$targetfn};
1.37      www      10192:             untie(%hash);
                   10193:         }
                   10194: # ---------------------------------------------------------- There was an entry
                   10195:         if ($syval) {
1.601     albertel 10196: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10197: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10198: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10199: 		    #return $env{$cache_str}='';
1.601     albertel 10200: 		#}    
                   10201: 		#$syval.=$1;
                   10202: 	    #}
1.37      www      10203:         } else {
                   10204: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10205:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10206:                             &GDBM_READER(),0640)) {
1.37      www      10207: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10208:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10209:               unless ($ids) { 
                   10210:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10211:               }
                   10212:               unless ($ids) {
                   10213: # alias?
                   10214: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10215:               }
1.37      www      10216:               if ($ids) {
                   10217: # ------------------------------------------------------------------- Has ID(s)
                   10218:                  my @possibilities=split(/\,/,$ids);
1.39      www      10219:                  if ($#possibilities==0) {
                   10220: # ----------------------------------------------- There is only one possibility
1.37      www      10221: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10222: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10223: 						    $resid,$thisfn);
1.249     www      10224:                  } elsif (!$donotrecurse) {
1.39      www      10225: # ------------------------------------------ There is more than one possibility
                   10226:                      my $realpossible=0;
1.800     albertel 10227:                      foreach my $id (@possibilities) {
                   10228: 			 my $file=$bighash{'src_'.$id};
1.39      www      10229:                          if (&allowed('bre',$file)) {
1.800     albertel 10230:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10231:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10232: 				$realpossible++;
1.626     albertel 10233:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10234: 						    $resid,$thisfn);
1.39      www      10235:                             }
                   10236: 			 }
1.191     harris41 10237:                      }
1.39      www      10238: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10239:                  } else {
                   10240:                      $syval='';
1.37      www      10241:                  }
                   10242: 	      }
                   10243:               untie(%bighash)
1.481     raeburn  10244:            }
1.31      www      10245:         }
1.62      www      10246:         if ($syval) {
1.620     albertel 10247: 	    return $env{$cache_str}=$syval;
1.62      www      10248:         }
1.31      www      10249:     }
1.949     raeburn  10250:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10251:     return $env{$cache_str}='';
1.31      www      10252: }
                   10253: 
                   10254: # ---------------------------------------------------------- Return random seed
                   10255: 
1.32      www      10256: sub numval {
                   10257:     my $txt=shift;
                   10258:     $txt=~tr/A-J/0-9/;
                   10259:     $txt=~tr/a-j/0-9/;
                   10260:     $txt=~tr/K-T/0-9/;
                   10261:     $txt=~tr/k-t/0-9/;
                   10262:     $txt=~tr/U-Z/0-5/;
                   10263:     $txt=~tr/u-z/0-5/;
                   10264:     $txt=~s/\D//g;
1.564     albertel 10265:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10266:     return int($txt);
1.368     albertel 10267: }
                   10268: 
1.484     albertel 10269: sub numval2 {
                   10270:     my $txt=shift;
                   10271:     $txt=~tr/A-J/0-9/;
                   10272:     $txt=~tr/a-j/0-9/;
                   10273:     $txt=~tr/K-T/0-9/;
                   10274:     $txt=~tr/k-t/0-9/;
                   10275:     $txt=~tr/U-Z/0-5/;
                   10276:     $txt=~tr/u-z/0-5/;
                   10277:     $txt=~s/\D//g;
                   10278:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10279:     my $total;
                   10280:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10281:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10282:     return int($total);
                   10283: }
                   10284: 
1.575     albertel 10285: sub numval3 {
                   10286:     use integer;
                   10287:     my $txt=shift;
                   10288:     $txt=~tr/A-J/0-9/;
                   10289:     $txt=~tr/a-j/0-9/;
                   10290:     $txt=~tr/K-T/0-9/;
                   10291:     $txt=~tr/k-t/0-9/;
                   10292:     $txt=~tr/U-Z/0-5/;
                   10293:     $txt=~tr/u-z/0-5/;
                   10294:     $txt=~s/\D//g;
                   10295:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10296:     my $total;
                   10297:     foreach my $val (@txts) { $total+=$val; }
                   10298:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10299:     return $total;
                   10300: }
                   10301: 
1.675     albertel 10302: sub digest {
                   10303:     my ($data)=@_;
                   10304:     my $digest=&Digest::MD5::md5($data);
                   10305:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10306:     my ($e,$f);
                   10307:     {
                   10308:         use integer;
                   10309:         $e=($a+$b);
                   10310:         $f=($c+$d);
                   10311:         if ($_64bit) {
                   10312:             $e=(($e<<32)>>32);
                   10313:             $f=(($f<<32)>>32);
                   10314:         }
                   10315:     }
                   10316:     if (wantarray) {
                   10317: 	return ($e,$f);
                   10318:     } else {
                   10319: 	my $g;
                   10320: 	{
                   10321: 	    use integer;
                   10322: 	    $g=($e+$f);
                   10323: 	    if ($_64bit) {
                   10324: 		$g=(($g<<32)>>32);
                   10325: 	    }
                   10326: 	}
                   10327: 	return $g;
                   10328:     }
                   10329: }
                   10330: 
1.368     albertel 10331: sub latest_rnd_algorithm_id {
1.675     albertel 10332:     return '64bit5';
1.366     albertel 10333: }
1.32      www      10334: 
1.503     albertel 10335: sub get_rand_alg {
                   10336:     my ($courseid)=@_;
1.790     albertel 10337:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10338:     if ($courseid) {
1.620     albertel 10339: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10340:     }
                   10341:     return &latest_rnd_algorithm_id();
                   10342: }
                   10343: 
1.562     albertel 10344: sub validCODE {
                   10345:     my ($CODE)=@_;
                   10346:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10347:     return 0;
                   10348: }
                   10349: 
1.491     albertel 10350: sub getCODE {
1.620     albertel 10351:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10352:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10353: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10354: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10355: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10356:     }
                   10357:     return undef;
                   10358: }
1.1133    foxr     10359: #
                   10360: #  Determines the random seed for a specific context:
                   10361: #
                   10362: # parameters:
                   10363: #   symb      - in course context the symb for the seed.
                   10364: #   course_id - The course id of the form domain_coursenum.
                   10365: #   domain    - Domain for the user.
                   10366: #   course    - Course for the user.
                   10367: #   cenv      - environment of the course.
                   10368: #
                   10369: # NOTE:
                   10370: #   All parameters are picked out of the environment if missing
                   10371: #   or not defined.
                   10372: #   If a symb cannot be determined the current time is used instead.
                   10373: #
                   10374: #  For a given well defined symb, courside, domain, username,
                   10375: #  and course environment, the seed is reproducible.
                   10376: #
1.31      www      10377: sub rndseed {
1.1133    foxr     10378:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10379:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10380:     if (!defined($symb)) {
1.366     albertel 10381: 	unless ($symb=$wsymb) { return time; }
                   10382:     }
1.1146    foxr     10383:     if (!defined $courseid) { 
                   10384: 	$courseid=$wcourseid; 
                   10385:     }
                   10386:     if (!defined $domain) { $domain=$wdomain; }
                   10387:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10388: 
                   10389:     my $which;
                   10390:     if (defined($cenv->{'rndseed'})) {
                   10391: 	$which = $cenv->{'rndseed'};
                   10392:     } else {
                   10393: 	$which =&get_rand_alg($courseid);
                   10394:     }
1.491     albertel 10395:     if (defined(&getCODE())) {
1.1133    foxr     10396: 
1.675     albertel 10397: 	if ($which eq '64bit5') {
                   10398: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10399: 	} elsif ($which eq '64bit4') {
1.575     albertel 10400: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10401: 	} else {
                   10402: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10403: 	}
1.675     albertel 10404:     } elsif ($which eq '64bit5') {
                   10405: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10406:     } elsif ($which eq '64bit4') {
                   10407: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10408:     } elsif ($which eq '64bit3') {
                   10409: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10410:     } elsif ($which eq '64bit2') {
                   10411: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10412:     } elsif ($which eq '64bit') {
                   10413: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10414:     }
                   10415:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10416: }
                   10417: 
                   10418: sub rndseed_32bit {
                   10419:     my ($symb,$courseid,$domain,$username)=@_;
                   10420:     {
                   10421: 	use integer;
                   10422: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10423: 	my $symbseed=numval($symb) << 22;
                   10424: 	my $namechck=unpack("%32C*",$username) << 17;
                   10425: 	my $nameseed=numval($username) << 12;
                   10426: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10427: 	my $courseseed=unpack("%32C*",$courseid);
                   10428: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10429: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10430: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10431: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10432: 	return $num;
                   10433:     }
                   10434: }
                   10435: 
                   10436: sub rndseed_64bit {
                   10437:     my ($symb,$courseid,$domain,$username)=@_;
                   10438:     {
                   10439: 	use integer;
                   10440: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10441: 	my $symbseed=numval($symb) << 10;
                   10442: 	my $namechck=unpack("%32S*",$username);
                   10443: 	
                   10444: 	my $nameseed=numval($username) << 21;
                   10445: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10446: 	my $courseseed=unpack("%32S*",$courseid);
                   10447: 	
                   10448: 	my $num1=$symbchck+$symbseed+$namechck;
                   10449: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10450: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10451: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10452: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10453: 	return "$num1,$num2";
1.155     albertel 10454:     }
1.366     albertel 10455: }
                   10456: 
1.443     albertel 10457: sub rndseed_64bit2 {
                   10458:     my ($symb,$courseid,$domain,$username)=@_;
                   10459:     {
                   10460: 	use integer;
                   10461: 	# strings need to be an even # of cahracters long, it it is odd the
                   10462:         # last characters gets thrown away
                   10463: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10464: 	my $symbseed=numval($symb) << 10;
                   10465: 	my $namechck=unpack("%32S*",$username.' ');
                   10466: 	
                   10467: 	my $nameseed=numval($username) << 21;
1.501     albertel 10468: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10469: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10470: 	
                   10471: 	my $num1=$symbchck+$symbseed+$namechck;
                   10472: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10473: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10474: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10475: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10476: 	return "$num1,$num2";
                   10477:     }
                   10478: }
                   10479: 
                   10480: sub rndseed_64bit3 {
                   10481:     my ($symb,$courseid,$domain,$username)=@_;
                   10482:     {
                   10483: 	use integer;
                   10484: 	# strings need to be an even # of cahracters long, it it is odd the
                   10485:         # last characters gets thrown away
                   10486: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10487: 	my $symbseed=numval2($symb) << 10;
                   10488: 	my $namechck=unpack("%32S*",$username.' ');
                   10489: 	
                   10490: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10491: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10492: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10493: 	
                   10494: 	my $num1=$symbchck+$symbseed+$namechck;
                   10495: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10496: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10497: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10498: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10499: 	
1.503     albertel 10500: 	return "$num1:$num2";
1.443     albertel 10501:     }
                   10502: }
                   10503: 
1.575     albertel 10504: sub rndseed_64bit4 {
                   10505:     my ($symb,$courseid,$domain,$username)=@_;
                   10506:     {
                   10507: 	use integer;
                   10508: 	# strings need to be an even # of cahracters long, it it is odd the
                   10509:         # last characters gets thrown away
                   10510: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10511: 	my $symbseed=numval3($symb) << 10;
                   10512: 	my $namechck=unpack("%32S*",$username.' ');
                   10513: 	
                   10514: 	my $nameseed=numval3($username) << 21;
                   10515: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10516: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10517: 	
                   10518: 	my $num1=$symbchck+$symbseed+$namechck;
                   10519: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10520: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10521: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10522: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10523: 	
1.575     albertel 10524: 	return "$num1:$num2";
                   10525:     }
                   10526: }
                   10527: 
1.675     albertel 10528: sub rndseed_64bit5 {
                   10529:     my ($symb,$courseid,$domain,$username)=@_;
                   10530:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10531:     return "$num1:$num2";
                   10532: }
                   10533: 
1.366     albertel 10534: sub rndseed_CODE_64bit {
                   10535:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10536:     {
1.366     albertel 10537: 	use integer;
1.443     albertel 10538: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10539: 	my $symbseed=numval2($symb);
1.491     albertel 10540: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10541: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10542: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10543: 	my $num1=$symbseed+$CODEchck;
                   10544: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10545: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10546: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10547: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10548: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10549: 	return "$num1:$num2";
1.366     albertel 10550:     }
                   10551: }
                   10552: 
1.575     albertel 10553: sub rndseed_CODE_64bit4 {
                   10554:     my ($symb,$courseid,$domain,$username)=@_;
                   10555:     {
                   10556: 	use integer;
                   10557: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10558: 	my $symbseed=numval3($symb);
                   10559: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10560: 	my $CODEseed=numval3(&getCODE());
                   10561: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10562: 	my $num1=$symbseed+$CODEchck;
                   10563: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10564: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10565: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10566: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10567: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10568: 	return "$num1:$num2";
                   10569:     }
                   10570: }
                   10571: 
1.675     albertel 10572: sub rndseed_CODE_64bit5 {
                   10573:     my ($symb,$courseid,$domain,$username)=@_;
                   10574:     my $code = &getCODE();
                   10575:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10576:     return "$num1:$num2";
                   10577: }
                   10578: 
1.366     albertel 10579: sub setup_random_from_rndseed {
                   10580:     my ($rndseed)=@_;
1.503     albertel 10581:     if ($rndseed =~/([,:])/) {
                   10582: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10583: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10584:     } else {
                   10585: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10586:     }
1.36      albertel 10587: }
                   10588: 
1.474     albertel 10589: sub latest_receipt_algorithm_id {
1.835     albertel 10590:     return 'receipt3';
1.474     albertel 10591: }
                   10592: 
1.480     www      10593: sub recunique {
                   10594:     my $fucourseid=shift;
                   10595:     my $unique;
1.835     albertel 10596:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10597: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10598: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10599:     } else {
                   10600: 	$unique=$perlvar{'lonReceipt'};
                   10601:     }
                   10602:     return unpack("%32C*",$unique);
                   10603: }
                   10604: 
                   10605: sub recprefix {
                   10606:     my $fucourseid=shift;
                   10607:     my $prefix;
1.835     albertel 10608:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10609: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10610: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10611:     } else {
                   10612: 	$prefix=$perlvar{'lonHostID'};
                   10613:     }
                   10614:     return unpack("%32C*",$prefix);
                   10615: }
                   10616: 
1.76      www      10617: sub ireceipt {
1.474     albertel 10618:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10619: 
                   10620:     my $return =&recprefix($fucourseid).'-';
                   10621: 
                   10622:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10623: 	$env{'request.state'} eq 'construct') {
                   10624: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10625: 	return $return;
                   10626:     }
                   10627: 
1.76      www      10628:     my $cuname=unpack("%32C*",$funame);
                   10629:     my $cudom=unpack("%32C*",$fudom);
                   10630:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10631:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10632:     my $cunique=&recunique($fucourseid);
1.474     albertel 10633:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10634:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10635: 
1.790     albertel 10636: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10637: 			       
                   10638: 	$return.= ($cunique%$cuname+
                   10639: 		   $cunique%$cudom+
                   10640: 		   $cusymb%$cuname+
                   10641: 		   $cusymb%$cudom+
                   10642: 		   $cucourseid%$cuname+
                   10643: 		   $cucourseid%$cudom+
                   10644: 		   $cpart%$cuname+
                   10645: 		   $cpart%$cudom);
                   10646:     } else {
                   10647: 	$return.= ($cunique%$cuname+
                   10648: 		   $cunique%$cudom+
                   10649: 		   $cusymb%$cuname+
                   10650: 		   $cusymb%$cudom+
                   10651: 		   $cucourseid%$cuname+
                   10652: 		   $cucourseid%$cudom);
                   10653:     }
                   10654:     return $return;
1.76      www      10655: }
                   10656: 
                   10657: sub receipt {
1.474     albertel 10658:     my ($part)=@_;
1.790     albertel 10659:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10660:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10661: }
1.260     ng       10662: 
1.790     albertel 10663: sub whichuser {
                   10664:     my ($passedsymb)=@_;
                   10665:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10666:     if (defined($env{'form.grade_symb'})) {
                   10667: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10668: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10669: 	if (!$allowed &&
                   10670: 	    exists($env{'request.course.sec'}) &&
                   10671: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10672: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10673: 			      '/'.$env{'request.course.sec'});
                   10674: 	}
                   10675: 	if ($allowed) {
                   10676: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10677: 	    $courseid=$tmp_courseid;
                   10678: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10679: 	    ($name)=&get_env_multiple('form.grade_username');
                   10680: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10681: 	}
                   10682:     }
                   10683:     if (!$passedsymb) {
                   10684: 	$symb=&symbread();
                   10685:     } else {
                   10686: 	$symb=$passedsymb;
                   10687:     }
                   10688:     $courseid=$env{'request.course.id'};
                   10689:     $domain=$env{'user.domain'};
                   10690:     $name=$env{'user.name'};
                   10691:     if ($name eq 'public' && $domain eq 'public') {
                   10692: 	if (!defined($env{'form.username'})) {
                   10693: 	    $env{'form.username'}.=time.rand(10000000);
                   10694: 	}
                   10695: 	$name.=$env{'form.username'};
                   10696:     }
                   10697:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10698: 
                   10699: }
                   10700: 
1.36      albertel 10701: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10702: # returns either the contents of the file or 
                   10703: # -1 if the file doesn't exist
1.481     raeburn  10704: #
                   10705: # if the target is a file that was uploaded via DOCS, 
                   10706: # a check will be made to see if a current copy exists on the local server,
                   10707: # if it does this will be served, otherwise a copy will be retrieved from
                   10708: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10709: # the local server.   
1.472     albertel 10710: 
1.36      albertel 10711: sub getfile {
1.538     albertel 10712:     my ($file) = @_;
1.609     banghart 10713:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10714:     &repcopy($file);
                   10715:     return &readfile($file);
                   10716: }
                   10717: 
                   10718: sub repcopy_userfile {
                   10719:     my ($file)=@_;
1.1142    raeburn  10720:     my $londocroot = $perlvar{'lonDocRoot'};
                   10721:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10722:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10723:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10724: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10725:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10726:     if (-e "$file") {
1.828     www      10727: # we already have a local copy, check it out
1.538     albertel 10728: 	my @fileinfo = stat($file);
1.828     www      10729: 	my $rtncode;
                   10730: 	my $info;
1.538     albertel 10731: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10732: 	if ($lwpresp ne 'ok') {
1.828     www      10733: # there is no such file anymore, even though we had a local copy
1.482     albertel 10734: 	    if ($rtncode eq '404') {
1.538     albertel 10735: 		unlink($file);
1.482     albertel 10736: 	    }
                   10737: 	    return -1;
                   10738: 	}
                   10739: 	if ($info < $fileinfo[9]) {
1.828     www      10740: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10741: 	    return 'ok';
1.828     www      10742: 	} else {
                   10743: # the file is outdated, get rid of it
                   10744: 	    unlink($file);
1.482     albertel 10745: 	}
1.828     www      10746:     }
                   10747: # one way or the other, at this point, we don't have the file
                   10748: # construct the correct path for the file
                   10749:     my @parts = ($cdom,$cnum); 
                   10750:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10751: 	push @parts, split(/\//,$1);
                   10752:     }
                   10753:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10754:     foreach my $part (@parts) {
                   10755: 	$path .= '/'.$part;
                   10756: 	if (!-e $path) {
                   10757: 	    mkdir($path,0770);
1.482     albertel 10758: 	}
                   10759:     }
1.828     www      10760: # now the path exists for sure
                   10761: # get a user agent
                   10762:     my $ua=new LWP::UserAgent;
                   10763:     my $transferfile=$file.'.in.transfer';
                   10764: # FIXME: this should flock
                   10765:     if (-e $transferfile) { return 'ok'; }
                   10766:     my $request;
                   10767:     $uri=~s/^\///;
1.980     raeburn  10768:     my $homeserver = &homeserver($cnum,$cdom);
                   10769:     my $protocol = $protocol{$homeserver};
                   10770:     $protocol = 'http' if ($protocol ne 'https');
                   10771:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10772:     my $response=$ua->request($request,$transferfile);
                   10773: # did it work?
                   10774:     if ($response->is_error()) {
                   10775: 	unlink($transferfile);
                   10776: 	&logthis("Userfile repcopy failed for $uri");
                   10777: 	return -1;
                   10778:     }
                   10779: # worked, rename the transfer file
                   10780:     rename($transferfile,$file);
1.607     raeburn  10781:     return 'ok';
1.481     raeburn  10782: }
                   10783: 
1.517     albertel 10784: sub tokenwrapper {
                   10785:     my $uri=shift;
1.980     raeburn  10786:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10787:     $uri=~s|^/||;
1.620     albertel 10788:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10789:     my $token=$1;
1.552     albertel 10790:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10791:     if ($udom && $uname && $file) {
                   10792: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10793:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10794:         my $homeserver = &homeserver($uname,$udom);
                   10795:         my $protocol = $protocol{$homeserver};
                   10796:         $protocol = 'http' if ($protocol ne 'https');
                   10797:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10798:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10799:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10800:     } else {
                   10801:         return '/adm/notfound.html';
                   10802:     }
                   10803: }
                   10804: 
1.828     www      10805: # call with reqtype HEAD: get last modification time
                   10806: # call with reqtype GET: get the file contents
                   10807: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10808: #
1.481     raeburn  10809: sub getuploaded {
                   10810:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10811:     $uri=~s/^\///;
1.980     raeburn  10812:     my $homeserver = &homeserver($cnum,$cdom);
                   10813:     my $protocol = $protocol{$homeserver};
                   10814:     $protocol = 'http' if ($protocol ne 'https');
                   10815:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10816:     my $ua=new LWP::UserAgent;
                   10817:     my $request=new HTTP::Request($reqtype,$uri);
                   10818:     my $response=$ua->request($request);
                   10819:     $$rtncode = $response->code;
1.482     albertel 10820:     if (! $response->is_success()) {
                   10821: 	return 'failed';
                   10822:     }      
                   10823:     if ($reqtype eq 'HEAD') {
1.486     www      10824: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10825:     } elsif ($reqtype eq 'GET') {
                   10826: 	$$info = $response->content;
1.472     albertel 10827:     }
1.482     albertel 10828:     return 'ok';
1.36      albertel 10829: }
                   10830: 
1.481     raeburn  10831: sub readfile {
                   10832:     my $file = shift;
                   10833:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10834:     my $fh;
                   10835:     open($fh,"<$file");
                   10836:     my $a='';
1.800     albertel 10837:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10838:     return $a;
                   10839: }
                   10840: 
1.36      albertel 10841: sub filelocation {
1.590     banghart 10842:     my ($dir,$file) = @_;
                   10843:     my $location;
                   10844:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10845: 
                   10846:     if ($file =~ m-^/adm/-) {
                   10847: 	$file=~s-^/adm/wrapper/-/-;
                   10848: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10849:     }
1.882     albertel 10850: 
1.1139    www      10851:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10852:         $location = $file;
1.609     banghart 10853:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10854:         my ($udom,$uname,$filename)=
1.811     albertel 10855:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10856:         my $home=&homeserver($uname,$udom);
                   10857:         my $is_me=0;
                   10858:         my @ids=&current_machine_ids();
                   10859:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10860:         if ($is_me) {
1.1117    foxr     10861:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10862:         } else {
                   10863:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10864:   	      $udom.'/'.$uname.'/'.$filename;
                   10865:         }
1.882     albertel 10866:     } elsif ($file =~ m-^/adm/-) {
                   10867: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10868:     } else {
                   10869:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10870:         $file=~s:^/(res|priv)/:/:;
                   10871:         my $space=$1;
1.590     banghart 10872:         if ( !( $file =~ m:^/:) ) {
                   10873:             $location = $dir. '/'.$file;
                   10874:         } else {
1.1142    raeburn  10875:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10876:         }
1.59      albertel 10877:     }
1.590     banghart 10878:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10879:     while ($location=~m{/\.\./}) {
                   10880: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10881: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10882: 	} else {
                   10883: 	    $location=~ s{/\.\./}{/}g;
                   10884: 	}
                   10885:     } #remove dir/..
1.590     banghart 10886:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10887:     return $location;
1.46      www      10888: }
1.36      albertel 10889: 
1.46      www      10890: sub hreflocation {
                   10891:     my ($dir,$file)=@_;
1.980     raeburn  10892:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10893: 	$file=filelocation($dir,$file);
1.700     albertel 10894:     } elsif ($file=~m-^/adm/-) {
                   10895: 	$file=~s-^/adm/wrapper/-/-;
                   10896: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10897:     }
                   10898:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10899: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10900:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10901: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10902: 	        {/uploaded/$1/$2/}x;
1.46      www      10903:     }
1.913     albertel 10904:     if ($file=~ m{^/userfiles/}) {
                   10905: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10906:     }
1.462     albertel 10907:     return $file;
1.465     albertel 10908: }
                   10909: 
1.1139    www      10910: 
                   10911: 
                   10912: 
                   10913: 
1.465     albertel 10914: sub current_machine_domains {
1.853     albertel 10915:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10916: }
                   10917: 
                   10918: sub machine_domains {
                   10919:     my ($hostname) = @_;
1.465     albertel 10920:     my @domains;
1.838     albertel 10921:     my %hostname = &all_hostnames();
1.465     albertel 10922:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10923: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10924: 	if ($hostname eq $name) {
1.844     albertel 10925: 	    push(@domains,&host_domain($id));
1.465     albertel 10926: 	}
                   10927:     }
                   10928:     return @domains;
                   10929: }
                   10930: 
                   10931: sub current_machine_ids {
1.853     albertel 10932:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10933: }
                   10934: 
                   10935: sub machine_ids {
                   10936:     my ($hostname) = @_;
                   10937:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10938:     my @ids;
1.888     albertel 10939:     my %name_to_host = &all_names();
1.889     albertel 10940:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10941: 	return @{ $name_to_host{$hostname} };
                   10942:     }
                   10943:     return;
1.31      www      10944: }
                   10945: 
1.824     raeburn  10946: sub additional_machine_domains {
                   10947:     my @domains;
                   10948:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10949:     while( my $line = <$fh>) {
                   10950:         $line =~ s/\s//g;
                   10951:         push(@domains,$line);
                   10952:     }
                   10953:     return @domains;
                   10954: }
                   10955: 
                   10956: sub default_login_domain {
                   10957:     my $domain = $perlvar{'lonDefDomain'};
                   10958:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10959:     foreach my $posdom (&current_machine_domains(),
                   10960:                         &additional_machine_domains()) {
                   10961:         if (lc($posdom) eq lc($testdomain)) {
                   10962:             $domain=$posdom;
                   10963:             last;
                   10964:         }
                   10965:     }
                   10966:     return $domain;
                   10967: }
                   10968: 
1.31      www      10969: # ------------------------------------------------------------- Declutters URLs
                   10970: 
                   10971: sub declutter {
                   10972:     my $thisfn=shift;
1.569     albertel 10973:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10974:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10975:     $thisfn=~s/^\///;
1.697     albertel 10976:     $thisfn=~s|^adm/wrapper/||;
                   10977:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10978:     $thisfn=~s/^res\///;
1.1172    bisitz   10979:     $thisfn=~s/^priv\///;
1.1032    raeburn  10980:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10981:         $thisfn=~s/\?.+$//;
                   10982:     }
1.268     www      10983:     return $thisfn;
                   10984: }
                   10985: 
                   10986: # ------------------------------------------------------------- Clutter up URLs
                   10987: 
                   10988: sub clutter {
                   10989:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10990:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10991: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10992:        $thisfn='/res'.$thisfn; 
                   10993:     }
1.1031    raeburn  10994:     if ($thisfn !~m|^/adm|) {
                   10995: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10996: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10997: 	} else {
                   10998: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10999: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11000: 	    if ($embstyle eq 'ssi'
                   11001: 		|| ($embstyle eq 'hdn')
                   11002: 		|| ($embstyle eq 'rat')
                   11003: 		|| ($embstyle eq 'prv')
                   11004: 		|| ($embstyle eq 'ign')) {
                   11005: 		#do nothing with these
                   11006: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11007: 		|| ($embstyle eq 'emb')
                   11008: 		|| ($embstyle eq 'wrp')) {
                   11009: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11010: 	    } elsif ($embstyle eq 'unk'
                   11011: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11012: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11013: 	    } else {
1.718     www      11014: #		&logthis("Got a blank emb style");
1.695     albertel 11015: 	    }
1.694     albertel 11016: 	}
                   11017:     }
1.31      www      11018:     return $thisfn;
1.12      www      11019: }
                   11020: 
1.787     albertel 11021: sub clutter_with_no_wrapper {
                   11022:     my $uri = &clutter(shift);
                   11023:     if ($uri =~ m-^/adm/-) {
                   11024: 	$uri =~ s-^/adm/wrapper/-/-;
                   11025: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11026:     }
                   11027:     return $uri;
                   11028: }
                   11029: 
1.557     albertel 11030: sub freeze_escape {
                   11031:     my ($value)=@_;
                   11032:     if (ref($value)) {
                   11033: 	$value=&nfreeze($value);
                   11034: 	return '__FROZEN__'.&escape($value);
                   11035:     }
                   11036:     return &escape($value);
                   11037: }
                   11038: 
1.11      www      11039: 
1.557     albertel 11040: sub thaw_unescape {
                   11041:     my ($value)=@_;
                   11042:     if ($value =~ /^__FROZEN__/) {
                   11043: 	substr($value,0,10,undef);
                   11044: 	$value=&unescape($value);
                   11045: 	return &thaw($value);
                   11046:     }
                   11047:     return &unescape($value);
                   11048: }
                   11049: 
1.436     albertel 11050: sub correct_line_ends {
                   11051:     my ($result)=@_;
                   11052:     $$result =~s/\r\n/\n/mg;
                   11053:     $$result =~s/\r/\n/mg;
1.415     albertel 11054: }
1.1       albertel 11055: # ================================================================ Main Program
                   11056: 
1.184     www      11057: sub goodbye {
1.204     albertel 11058:    &logthis("Starting Shut down");
1.443     albertel 11059: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11060:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11061: #converted
1.599     albertel 11062: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11063:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11064: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11065: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11066: #1.1 only
1.870     albertel 11067: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11068: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11069: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11070: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11071:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11072:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11073:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11074:    &flushcourselogs();
                   11075:    &logthis("Shutting down");
                   11076: }
                   11077: 
1.852     albertel 11078: sub get_dns {
1.869     albertel 11079:     my ($url,$func,$ignore_cache) = @_;
                   11080:     if (!$ignore_cache) {
                   11081: 	my ($content,$cached)=
                   11082: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11083: 	if ($cached) {
                   11084: 	    &$func($content);
                   11085: 	    return;
                   11086: 	}
                   11087:     }
                   11088: 
                   11089:     my %alldns;
1.852     albertel 11090:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11091:     foreach my $dns (<$config>) {
                   11092: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11093:         my $line = $1;
                   11094:         my ($host,$protocol) = split(/:/,$line);
                   11095:         if ($protocol ne 'https') {
                   11096:             $protocol = 'http';
                   11097:         }
                   11098: 	$alldns{$host} = $protocol;
1.869     albertel 11099:     }
                   11100:     while (%alldns) {
                   11101: 	my ($dns) = keys(%alldns);
1.852     albertel 11102: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11103:         $ua->timeout(30);
1.979     raeburn  11104: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11105: 	my $response=$ua->request($request);
1.979     raeburn  11106:         delete($alldns{$dns});
1.852     albertel 11107: 	next if ($response->is_error());
                   11108: 	my @content = split("\n",$response->content);
1.869     albertel 11109: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 11110: 	&$func(\@content);
1.869     albertel 11111: 	return;
1.852     albertel 11112:     }
                   11113:     close($config);
1.871     albertel 11114:     my $which = (split('/',$url))[3];
                   11115:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11116:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11117:     my @content = <$config>;
                   11118:     &$func(\@content);
                   11119:     return;
1.852     albertel 11120: }
1.327     albertel 11121: # ------------------------------------------------------------ Read domain file
                   11122: {
1.852     albertel 11123:     my $loaded;
1.846     albertel 11124:     my %domain;
                   11125: 
1.852     albertel 11126:     sub parse_domain_tab {
                   11127: 	my ($lines) = @_;
                   11128: 	foreach my $line (@$lines) {
                   11129: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11130: 
1.846     albertel 11131: 	    chomp($line);
1.852     albertel 11132: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11133: 	    my %this_domain;
                   11134: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11135: 			       'lang_def', 'city', 'longi', 'lati',
                   11136: 			       'primary') {
                   11137: 		$this_domain{$field} = shift(@elements);
                   11138: 	    }
                   11139: 	    $domain{$name} = \%this_domain;
1.852     albertel 11140: 	}
                   11141:     }
1.864     albertel 11142: 
                   11143:     sub reset_domain_info {
                   11144: 	undef($loaded);
                   11145: 	undef(%domain);
                   11146:     }
                   11147: 
1.852     albertel 11148:     sub load_domain_tab {
1.869     albertel 11149: 	my ($ignore_cache) = @_;
                   11150: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11151: 	my $fh;
                   11152: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11153: 	    my @lines = <$fh>;
                   11154: 	    &parse_domain_tab(\@lines);
1.448     albertel 11155: 	}
1.852     albertel 11156: 	close($fh);
                   11157: 	$loaded = 1;
1.327     albertel 11158:     }
1.846     albertel 11159: 
                   11160:     sub domain {
1.852     albertel 11161: 	&load_domain_tab() if (!$loaded);
                   11162: 
1.846     albertel 11163: 	my ($name,$what) = @_;
                   11164: 	return if ( !exists($domain{$name}) );
                   11165: 
                   11166: 	if (!$what) {
                   11167: 	    return $domain{$name}{'description'};
                   11168: 	}
                   11169: 	return $domain{$name}{$what};
                   11170:     }
1.974     raeburn  11171: 
                   11172:     sub domain_info {
                   11173:         &load_domain_tab() if (!$loaded);
                   11174:         return %domain;
                   11175:     }
                   11176: 
1.327     albertel 11177: }
                   11178: 
                   11179: 
1.1       albertel 11180: # ------------------------------------------------------------- Read hosts file
                   11181: {
1.838     albertel 11182:     my %hostname;
1.844     albertel 11183:     my %hostdom;
1.845     albertel 11184:     my %libserv;
1.852     albertel 11185:     my $loaded;
1.888     albertel 11186:     my %name_to_host;
1.1074    raeburn  11187:     my %internetdom;
1.1107    raeburn  11188:     my %LC_dns_serv;
1.852     albertel 11189: 
                   11190:     sub parse_hosts_tab {
                   11191: 	my ($file) = @_;
                   11192: 	foreach my $configline (@$file) {
                   11193: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11194:             chomp($configline);
                   11195: 	    if ($configline =~ /^\^/) {
                   11196:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11197:                     $LC_dns_serv{$1} = 1;
                   11198:                 }
                   11199:                 next;
                   11200:             }
1.1074    raeburn  11201: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11202: 	    $name=~s/\s//g;
                   11203: 	    if ($id && $domain && $role && $name) {
                   11204: 		$hostname{$id}=$name;
1.888     albertel 11205: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11206: 		$hostdom{$id}=$domain;
                   11207: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11208:                 if (defined($protocol)) {
                   11209:                     if ($protocol eq 'https') {
                   11210:                         $protocol{$id} = $protocol;
                   11211:                     } else {
                   11212:                         $protocol{$id} = 'http'; 
                   11213:                     }
1.968     raeburn  11214:                 } else {
1.969     raeburn  11215:                     $protocol{$id} = 'http';
1.968     raeburn  11216:                 }
1.1074    raeburn  11217:                 if (defined($intdom)) {
                   11218:                     $internetdom{$id} = $intdom;
                   11219:                 }
1.852     albertel 11220: 	    }
                   11221: 	}
                   11222:     }
1.864     albertel 11223:     
                   11224:     sub reset_hosts_info {
1.897     albertel 11225: 	&purge_remembered();
1.864     albertel 11226: 	&reset_domain_info();
                   11227: 	&reset_hosts_ip_info();
1.892     albertel 11228: 	undef(%name_to_host);
1.864     albertel 11229: 	undef(%hostname);
                   11230: 	undef(%hostdom);
                   11231: 	undef(%libserv);
                   11232: 	undef($loaded);
                   11233:     }
1.1       albertel 11234: 
1.852     albertel 11235:     sub load_hosts_tab {
1.869     albertel 11236: 	my ($ignore_cache) = @_;
                   11237: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11238: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11239: 	my @config = <$config>;
                   11240: 	&parse_hosts_tab(\@config);
                   11241: 	close($config);
                   11242: 	$loaded=1;
1.1       albertel 11243:     }
1.852     albertel 11244: 
1.838     albertel 11245:     sub hostname {
1.852     albertel 11246: 	&load_hosts_tab() if (!$loaded);
                   11247: 
1.838     albertel 11248: 	my ($lonid) = @_;
                   11249: 	return $hostname{$lonid};
                   11250:     }
1.845     albertel 11251: 
1.838     albertel 11252:     sub all_hostnames {
1.852     albertel 11253: 	&load_hosts_tab() if (!$loaded);
                   11254: 
1.838     albertel 11255: 	return %hostname;
                   11256:     }
1.845     albertel 11257: 
1.888     albertel 11258:     sub all_names {
                   11259: 	&load_hosts_tab() if (!$loaded);
                   11260: 
                   11261: 	return %name_to_host;
                   11262:     }
                   11263: 
1.974     raeburn  11264:     sub all_host_domain {
                   11265:         &load_hosts_tab() if (!$loaded);
                   11266:         return %hostdom;
                   11267:     }
                   11268: 
1.845     albertel 11269:     sub is_library {
1.852     albertel 11270: 	&load_hosts_tab() if (!$loaded);
                   11271: 
1.845     albertel 11272: 	return exists($libserv{$_[0]});
                   11273:     }
                   11274: 
                   11275:     sub all_library {
1.852     albertel 11276: 	&load_hosts_tab() if (!$loaded);
                   11277: 
1.845     albertel 11278: 	return %libserv;
                   11279:     }
                   11280: 
1.1062    droeschl 11281:     sub unique_library {
                   11282: 	#2x reverse removes all hostnames that appear more than once
                   11283:         my %unique = reverse &all_library();
                   11284:         return reverse %unique;
                   11285:     }
                   11286: 
1.841     albertel 11287:     sub get_servers {
1.852     albertel 11288: 	&load_hosts_tab() if (!$loaded);
                   11289: 
1.841     albertel 11290: 	my ($domain,$type) = @_;
                   11291: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11292: 	                                          : %hostname;
                   11293: 	my %result;
1.842     albertel 11294: 	if (ref($domain) eq 'ARRAY') {
                   11295: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11296: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11297: 		    $result{$host} = $hostname;
                   11298: 		}
                   11299: 	    }
                   11300: 	} else {
                   11301: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11302: 		if ($hostdom{$host} eq $domain) {
                   11303: 		    $result{$host} = $hostname;
                   11304: 		}
1.841     albertel 11305: 	    }
                   11306: 	}
                   11307: 	return %result;
                   11308:     }
1.845     albertel 11309: 
1.1062    droeschl 11310:     sub get_unique_servers {
                   11311:         my %unique = reverse &get_servers(@_);
                   11312: 	return reverse %unique;
                   11313:     }
                   11314: 
1.844     albertel 11315:     sub host_domain {
1.852     albertel 11316: 	&load_hosts_tab() if (!$loaded);
                   11317: 
1.844     albertel 11318: 	my ($lonid) = @_;
                   11319: 	return $hostdom{$lonid};
                   11320:     }
                   11321: 
1.841     albertel 11322:     sub all_domains {
1.852     albertel 11323: 	&load_hosts_tab() if (!$loaded);
                   11324: 
1.841     albertel 11325: 	my %seen;
                   11326: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11327: 	return @uniq;
                   11328:     }
1.1074    raeburn  11329: 
                   11330:     sub internet_dom {
                   11331:         &load_hosts_tab() if (!$loaded);
                   11332: 
                   11333:         my ($lonid) = @_;
                   11334:         return $internetdom{$lonid};
                   11335:     }
1.1107    raeburn  11336: 
                   11337:     sub is_LC_dns {
                   11338:         &load_hosts_tab() if (!$loaded);
                   11339: 
                   11340:         my ($hostname) = @_;
                   11341:         return exists($LC_dns_serv{$hostname});
                   11342:     }
                   11343: 
1.1       albertel 11344: }
                   11345: 
1.847     albertel 11346: { 
                   11347:     my %iphost;
1.856     albertel 11348:     my %name_to_ip;
                   11349:     my %lonid_to_ip;
1.869     albertel 11350: 
1.847     albertel 11351:     sub get_hosts_from_ip {
                   11352: 	my ($ip) = @_;
                   11353: 	my %iphosts = &get_iphost();
                   11354: 	if (ref($iphosts{$ip})) {
                   11355: 	    return @{$iphosts{$ip}};
                   11356: 	}
                   11357: 	return;
1.839     albertel 11358:     }
1.864     albertel 11359:     
                   11360:     sub reset_hosts_ip_info {
                   11361: 	undef(%iphost);
                   11362: 	undef(%name_to_ip);
                   11363: 	undef(%lonid_to_ip);
                   11364:     }
1.856     albertel 11365: 
                   11366:     sub get_host_ip {
                   11367: 	my ($lonid) = @_;
                   11368: 	if (exists($lonid_to_ip{$lonid})) {
                   11369: 	    return $lonid_to_ip{$lonid};
                   11370: 	}
                   11371: 	my $name=&hostname($lonid);
                   11372:    	my $ip = gethostbyname($name);
                   11373: 	return if (!$ip || length($ip) ne 4);
                   11374: 	$ip=inet_ntoa($ip);
                   11375: 	$name_to_ip{$name}   = $ip;
                   11376: 	$lonid_to_ip{$lonid} = $ip;
                   11377: 	return $ip;
                   11378:     }
1.847     albertel 11379:     
                   11380:     sub get_iphost {
1.869     albertel 11381: 	my ($ignore_cache) = @_;
1.894     albertel 11382: 
1.869     albertel 11383: 	if (!$ignore_cache) {
                   11384: 	    if (%iphost) {
                   11385: 		return %iphost;
                   11386: 	    }
                   11387: 	    my ($ip_info,$cached)=
                   11388: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11389: 	    if ($cached) {
                   11390: 		%iphost      = %{$ip_info->[0]};
                   11391: 		%name_to_ip  = %{$ip_info->[1]};
                   11392: 		%lonid_to_ip = %{$ip_info->[2]};
                   11393: 		return %iphost;
                   11394: 	    }
                   11395: 	}
1.894     albertel 11396: 
                   11397: 	# get yesterday's info for fallback
                   11398: 	my %old_name_to_ip;
                   11399: 	my ($ip_info,$cached)=
                   11400: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11401: 	if ($cached) {
                   11402: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11403: 	}
                   11404: 
1.888     albertel 11405: 	my %name_to_host = &all_names();
                   11406: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11407: 	    my $ip;
                   11408: 	    if (!exists($name_to_ip{$name})) {
                   11409: 		$ip = gethostbyname($name);
                   11410: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11411: 		    if (defined($old_name_to_ip{$name})) {
                   11412: 			$ip = $old_name_to_ip{$name};
                   11413: 			&logthis("Can't find $name defaulting to old $ip");
                   11414: 		    } else {
                   11415: 			&logthis("Name $name no IP found");
                   11416: 			next;
                   11417: 		    }
                   11418: 		} else {
                   11419: 		    $ip=inet_ntoa($ip);
1.847     albertel 11420: 		}
                   11421: 		$name_to_ip{$name} = $ip;
                   11422: 	    } else {
                   11423: 		$ip = $name_to_ip{$name};
1.653     albertel 11424: 	    }
1.888     albertel 11425: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11426: 		$lonid_to_ip{$id} = $ip;
                   11427: 	    }
                   11428: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11429: 	}
1.869     albertel 11430: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11431: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11432: 				      48*60*60);
1.869     albertel 11433: 
1.847     albertel 11434: 	return %iphost;
1.598     albertel 11435:     }
                   11436: 
1.992     raeburn  11437:     #
                   11438:     #  Given a DNS returns the loncapa host name for that DNS 
                   11439:     # 
                   11440:     sub host_from_dns {
                   11441:         my ($dns) = @_;
                   11442:         my @hosts;
                   11443:         my $ip;
                   11444: 
1.993     raeburn  11445:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11446:             $ip = $name_to_ip{$dns};
                   11447:         }
                   11448:         if (!$ip) {
                   11449:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11450:             if (length($ip) == 4) { 
                   11451: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11452:             }
                   11453:         }
                   11454:         if ($ip) {
                   11455: 	    @hosts = get_hosts_from_ip($ip);
                   11456: 	    return $hosts[0];
                   11457:         }
                   11458:         return undef;
1.986     foxr     11459:     }
1.992     raeburn  11460: 
1.1074    raeburn  11461:     sub get_internet_names {
                   11462:         my ($lonid) = @_;
                   11463:         return if ($lonid eq '');
                   11464:         my ($idnref,$cached)=
                   11465:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11466:         if ($cached) {
                   11467:             return $idnref;
                   11468:         }
                   11469:         my $ip = &get_host_ip($lonid);
                   11470:         my @hosts = &get_hosts_from_ip($ip);
                   11471:         my %iphost = &get_iphost();
                   11472:         my (@idns,%seen);
                   11473:         foreach my $id (@hosts) {
                   11474:             my $dom = &host_domain($id);
                   11475:             my $prim_id = &domain($dom,'primary');
                   11476:             my $prim_ip = &get_host_ip($prim_id);
                   11477:             next if ($seen{$prim_ip});
                   11478:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11479:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11480:                     my $intdom = &internet_dom($id);
                   11481:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11482:                         push(@idns,$intdom);
                   11483:                     }
                   11484:                 }
                   11485:             }
                   11486:             $seen{$prim_ip} = 1;
                   11487:         }
                   11488:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11489:     }
                   11490: 
1.986     foxr     11491: }
                   11492: 
1.1079    raeburn  11493: sub all_loncaparevs {
                   11494:     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);
                   11495: }
                   11496: 
1.862     albertel 11497: BEGIN {
                   11498: 
                   11499: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11500:     unless ($readit) {
                   11501: {
                   11502:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11503:     %perlvar = (%perlvar,%{$configvars});
                   11504: }
                   11505: 
                   11506: 
1.1       albertel 11507: # ------------------------------------------------------ Read spare server file
                   11508: {
1.448     albertel 11509:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11510: 
                   11511:     while (my $configline=<$config>) {
                   11512:        chomp($configline);
1.284     matthew  11513:        if ($configline) {
1.784     albertel 11514: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11515: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11516: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11517:        }
                   11518:     }
1.448     albertel 11519:     close($config);
1.1       albertel 11520: }
1.11      www      11521: # ------------------------------------------------------------ Read permissions
                   11522: {
1.448     albertel 11523:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11524: 
                   11525:     while (my $configline=<$config>) {
1.448     albertel 11526: 	chomp($configline);
                   11527: 	if ($configline) {
                   11528: 	    my ($role,$perm)=split(/ /,$configline);
                   11529: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11530: 	}
1.11      www      11531:     }
1.448     albertel 11532:     close($config);
1.11      www      11533: }
                   11534: 
                   11535: # -------------------------------------------- Read plain texts for permissions
                   11536: {
1.448     albertel 11537:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11538: 
                   11539:     while (my $configline=<$config>) {
1.448     albertel 11540: 	chomp($configline);
                   11541: 	if ($configline) {
1.742     raeburn  11542: 	    my ($short,@plain)=split(/:/,$configline);
                   11543:             %{$prp{$short}} = ();
                   11544: 	    if (@plain > 0) {
                   11545:                 $prp{$short}{'std'} = $plain[0];
                   11546:                 for (my $i=1; $i<@plain; $i++) {
                   11547:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11548:                 }
                   11549:             }
1.448     albertel 11550: 	}
1.135     www      11551:     }
1.448     albertel 11552:     close($config);
1.135     www      11553: }
                   11554: 
                   11555: # ---------------------------------------------------------- Read package table
                   11556: {
1.448     albertel 11557:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11558: 
                   11559:     while (my $configline=<$config>) {
1.483     albertel 11560: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11561: 	chomp($configline);
                   11562: 	my ($short,$plain)=split(/:/,$configline);
                   11563: 	my ($pack,$name)=split(/\&/,$short);
                   11564: 	if ($plain ne '') {
                   11565: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11566: 	    $packagetab{$short}=$plain; 
                   11567: 	}
1.11      www      11568:     }
1.448     albertel 11569:     close($config);
1.329     matthew  11570: }
                   11571: 
1.1073    raeburn  11572: # ---------------------------------------------------------- Read loncaparev table
                   11573: {
                   11574:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11575:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11576:             while (my $configline=<$config>) {
                   11577:                 chomp($configline);
                   11578:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11579:                 $loncaparevs{$hostid}=$loncaparev;
                   11580:             }
                   11581:             close($config);
                   11582:         }
                   11583:     }
                   11584: }
                   11585: 
1.1074    raeburn  11586: # ---------------------------------------------------------- Read serverhostID table
                   11587: {
                   11588:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11589:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11590:             while (my $configline=<$config>) {
                   11591:                 chomp($configline);
                   11592:                 my ($name,$id)=split(/:/,$configline);
                   11593:                 $serverhomeIDs{$name}=$id;
                   11594:             }
                   11595:             close($config);
                   11596:         }
                   11597:     }
                   11598: }
                   11599: 
1.1079    raeburn  11600: {
                   11601:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11602:     if (-e $file) {
                   11603:         my $parser = HTML::LCParser->new($file);
                   11604:         while (my $token = $parser->get_token()) {
                   11605:             if ($token->[0] eq 'S') {
                   11606:                 my $item = $token->[1];
                   11607:                 my $name = $token->[2]{'name'};
                   11608:                 my $value = $token->[2]{'value'};
                   11609:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11610:                     my $release = $parser->get_text();
                   11611:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11612:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11613:                 }
                   11614:             }
                   11615:         }
                   11616:     }
1.1073    raeburn  11617: }
                   11618: 
1.1138    raeburn  11619: # ---------------------------------------------------------- Read managers table
                   11620: {
                   11621:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11622:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11623:             while (my $configline=<$config>) {
                   11624:                 chomp($configline);
                   11625:                 next if ($configline =~ /^\#/);
                   11626:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11627:                     $managerstab{$configline} = 1;
                   11628:                 }
                   11629:             }
                   11630:             close($config);
                   11631:         }
                   11632:     }
                   11633: }
                   11634: 
1.329     matthew  11635: # ------------- set up temporary directory
                   11636: {
1.1117    foxr     11637:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11638: 
1.11      www      11639: }
                   11640: 
1.794     albertel 11641: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11642: 				'compress_threshold'=> 20_000,
                   11643:  			        });
1.185     www      11644: 
1.281     www      11645: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11646: $dumpcount=0;
1.958     www      11647: $locknum=0;
1.22      www      11648: 
1.163     harris41 11649: &logtouch();
1.672     albertel 11650: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11651: $readit=1;
1.564     albertel 11652:     {
                   11653: 	use integer;
                   11654: 	my $test=(2**32)+1;
1.568     albertel 11655: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11656: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11657:     }
1.195     www      11658: }
1.1       albertel 11659: }
1.179     www      11660: 
1.1       albertel 11661: 1;
1.191     harris41 11662: __END__
                   11663: 
1.243     albertel 11664: =pod
                   11665: 
1.191     harris41 11666: =head1 NAME
                   11667: 
1.243     albertel 11668: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11669: 
                   11670: =head1 SYNOPSIS
                   11671: 
1.243     albertel 11672: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11673: 
                   11674:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11675: 
1.243     albertel 11676: Common parameters:
                   11677: 
                   11678: =over 4
                   11679: 
                   11680: =item *
                   11681: 
                   11682: $uname : an internal username (if $cname expecting a course Id specifically)
                   11683: 
                   11684: =item *
                   11685: 
                   11686: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11687: 
                   11688: =item *
                   11689: 
                   11690: $symb : a resource instance identifier
                   11691: 
                   11692: =item *
                   11693: 
                   11694: $namespace : the name of a .db file that contains the data needed or
                   11695: being set.
                   11696: 
                   11697: =back
                   11698: 
1.394     bowersj2 11699: =head1 OVERVIEW
1.191     harris41 11700: 
1.394     bowersj2 11701: lonnet provides subroutines which interact with the
                   11702: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11703: about classes, users, and resources.
1.243     albertel 11704: 
                   11705: For many of these objects you can also use this to store data about
                   11706: them or modify them in various ways.
1.191     harris41 11707: 
1.394     bowersj2 11708: =head2 Symbs
1.191     harris41 11709: 
1.394     bowersj2 11710: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11711: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11712: map, the resource number of the resource in the map, and the URL of
                   11713: the resource itself. The latter is somewhat redundant, but might help
                   11714: if maps change.
                   11715: 
                   11716: An example is
                   11717: 
                   11718:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11719: 
                   11720: The respective map entry is
                   11721: 
                   11722:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11723:   title="Problem 2">
                   11724:  </resource>
                   11725: 
                   11726: Symbs are used by the random number generator, as well as to store and
                   11727: restore data specific to a certain instance of for example a problem.
                   11728: 
                   11729: =head2 Storing And Retrieving Data
                   11730: 
                   11731: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11732: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11733: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11734: is is the non-critical message twin of cstore. These functions are for
                   11735: handlers to store a perl hash to a user's permanent data space in an
                   11736: easy manner, and to retrieve it again on another call. It is expected
                   11737: that a handler would use this once at the beginning to retrieve data,
                   11738: and then again once at the end to send only the new data back.
                   11739: 
                   11740: The data is stored in the user's data directory on the user's
                   11741: homeserver under the ID of the course.
                   11742: 
                   11743: The hash that is returned by restore will have all of the previous
                   11744: value for all of the elements of the hash.
                   11745: 
                   11746: Example:
                   11747: 
                   11748:  #creating a hash
                   11749:  my %hash;
                   11750:  $hash{'foo'}='bar';
                   11751: 
                   11752:  #storing it
                   11753:  &Apache::lonnet::cstore(\%hash);
                   11754: 
                   11755:  #changing a value
                   11756:  $hash{'foo'}='notbar';
                   11757: 
                   11758:  #adding a new value
                   11759:  $hash{'bar'}='foo';
                   11760:  &Apache::lonnet::cstore(\%hash);
                   11761: 
                   11762:  #retrieving the hash
                   11763:  my %history=&Apache::lonnet::restore();
                   11764: 
                   11765:  #print the hash
                   11766:  foreach my $key (sort(keys(%history))) {
                   11767:    print("\%history{$key} = $history{$key}");
                   11768:  }
                   11769: 
                   11770: Will print out:
1.191     harris41 11771: 
1.394     bowersj2 11772:  %history{1:foo} = bar
                   11773:  %history{1:keys} = foo:timestamp
                   11774:  %history{1:timestamp} = 990455579
                   11775:  %history{2:bar} = foo
                   11776:  %history{2:foo} = notbar
                   11777:  %history{2:keys} = foo:bar:timestamp
                   11778:  %history{2:timestamp} = 990455580
                   11779:  %history{bar} = foo
                   11780:  %history{foo} = notbar
                   11781:  %history{timestamp} = 990455580
                   11782:  %history{version} = 2
                   11783: 
                   11784: Note that the special hash entries C<keys>, C<version> and
                   11785: C<timestamp> were added to the hash. C<version> will be equal to the
                   11786: total number of versions of the data that have been stored. The
                   11787: C<timestamp> attribute will be the UNIX time the hash was
                   11788: stored. C<keys> is available in every historical section to list which
                   11789: keys were added or changed at a specific historical revision of a
                   11790: hash.
                   11791: 
                   11792: B<Warning>: do not store the hash that restore returns directly. This
                   11793: will cause a mess since it will restore the historical keys as if the
                   11794: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11795: 
1.394     bowersj2 11796: Calling convention:
1.191     harris41 11797: 
1.394     bowersj2 11798:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11799:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11800: 
1.394     bowersj2 11801: For more detailed information, see lonnet specific documentation.
1.191     harris41 11802: 
1.394     bowersj2 11803: =head1 RETURN MESSAGES
1.191     harris41 11804: 
1.394     bowersj2 11805: =over 4
1.191     harris41 11806: 
1.394     bowersj2 11807: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11808: 
1.394     bowersj2 11809: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11810: when the connection is brought back up
1.191     harris41 11811: 
1.394     bowersj2 11812: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11813: for later delivery
1.191     harris41 11814: 
1.967     bisitz   11815: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11816: 
1.394     bowersj2 11817: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11818: that was requested
1.191     harris41 11819: 
1.243     albertel 11820: =back
1.191     harris41 11821: 
1.243     albertel 11822: =head1 PUBLIC SUBROUTINES
1.191     harris41 11823: 
1.243     albertel 11824: =head2 Session Environment Functions
1.191     harris41 11825: 
1.243     albertel 11826: =over 4
1.191     harris41 11827: 
1.394     bowersj2 11828: =item * 
                   11829: X<appenv()>
1.949     raeburn  11830: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11831: the user envirnoment file, and will be restored for each access this
1.620     albertel 11832: user makes during this session, also modifies the %env for the current
1.949     raeburn  11833: process. Optional rolesarrayref - if defined contains a reference to an array
                   11834: of roles which are exempt from the restriction on modifying user.role entries 
                   11835: in the user's environment.db and in %env.    
1.191     harris41 11836: 
                   11837: =item *
1.394     bowersj2 11838: X<delenv()>
1.987     raeburn  11839: B<delenv($delthis,$regexp)>: removes all items from the session
                   11840: environment file that begin with $delthis. If the 
                   11841: optional second arg - $regexp - is true, $delthis is treated as a 
                   11842: regular expression, otherwise \Q$delthis\E is used. 
                   11843: The values are also deleted from the current processes %env.
1.191     harris41 11844: 
1.795     albertel 11845: =item * get_env_multiple($name) 
                   11846: 
                   11847: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11848: values may be defined and end up as an array ref.
                   11849: 
                   11850: returns an array of values
                   11851: 
1.243     albertel 11852: =back
                   11853: 
                   11854: =head2 User Information
1.191     harris41 11855: 
1.243     albertel 11856: =over 4
1.191     harris41 11857: 
                   11858: =item *
1.394     bowersj2 11859: X<queryauthenticate()>
                   11860: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11861: authentication scheme
                   11862: 
                   11863: =item *
1.394     bowersj2 11864: X<authenticate()>
1.1073    raeburn  11865: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11866: authenticate user from domain's lib servers (first use the current
                   11867: one). C<$upass> should be the users password.
1.1073    raeburn  11868: $checkdefauth is optional (value is 1 if a check should be made to
                   11869:    authenticate user using default authentication method, and allow
                   11870:    account creation if username does not have account in the domain).
                   11871: $clientcancheckhost is optional (value is 1 if checking whether the
                   11872:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11873: 
                   11874: =item *
1.394     bowersj2 11875: X<homeserver()>
                   11876: B<homeserver($uname,$udom)>: find the server which has
                   11877: the user's directory and files (there must be only one), this caches
                   11878: the answer, and also caches if there is a borken connection.
1.191     harris41 11879: 
                   11880: =item *
1.394     bowersj2 11881: X<idget()>
                   11882: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11883: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11884: username, and only 1 username per ID in a specific domain) (returns
                   11885: hash: id=>name,id=>name)
1.191     harris41 11886: 
                   11887: =item *
1.394     bowersj2 11888: X<idrget()>
                   11889: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11890: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11891: 
                   11892: =item *
1.394     bowersj2 11893: X<idput()>
                   11894: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11895: 
                   11896: =item *
1.394     bowersj2 11897: X<rolesinit()>
1.1169    droeschl 11898: B<rolesinit($udom,$username)>: get user privileges.
                   11899: returns user role, first access and timer interval hashes
1.243     albertel 11900: 
                   11901: =item *
1.1171    droeschl 11902: X<privileged()>
                   11903: B<privileged($username,$domain)>: returns a true if user has a
                   11904: privileged and active role (i.e. su or dc), false otherwise.
                   11905: 
                   11906: =item *
1.551     albertel 11907: X<getsection()>
                   11908: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11909: course $cname, return section name/number or '' for "not in course"
                   11910: and '-1' for "no section"
                   11911: 
                   11912: =item *
1.394     bowersj2 11913: X<userenvironment()>
                   11914: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11915: passed in @what from the requested user's environment, returns a hash
                   11916: 
1.858     raeburn  11917: =item * 
                   11918: X<userlog_query()>
1.859     albertel 11919: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11920: activity.log file. %filters defines filters applied when parsing the
                   11921: log file. These can be start or end timestamps, or the type of action
                   11922: - log to look for Login or Logout events, check for Checkin or
                   11923: Checkout, role for role selection. The response is in the form
                   11924: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11925: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11926: 
1.243     albertel 11927: =back
                   11928: 
                   11929: =head2 User Roles
                   11930: 
                   11931: =over 4
                   11932: 
                   11933: =item *
                   11934: 
1.810     raeburn  11935: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11936:  F: full access
                   11937:  U,I,K: authentication modes (cxx only)
                   11938:  '': forbidden
                   11939:  1: user needs to choose course
                   11940:  2: browse allowed
1.766     albertel 11941:  A: passphrase authentication needed
1.243     albertel 11942: 
                   11943: =item *
                   11944: 
                   11945: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11946: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11947: and course level
                   11948: 
                   11949: =item *
                   11950: 
1.988     raeburn  11951: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11952: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11953: $type is Course (default) or Community.
1.988     raeburn  11954: If $forcedefault evaluates to true, text returned will be default 
                   11955: text for $type. Otherwise, if this is a course, the text returned 
                   11956: will be a custom name for the role (if defined in the course's 
                   11957: environment).  If no custom name is defined the default is returned.
                   11958:    
1.832     raeburn  11959: =item *
                   11960: 
1.935     raeburn  11961: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11962: All arguments are optional. Returns a hash of a roles, either for
                   11963: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11964: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11965: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11966: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11967: For each key, value is set to colon-separated start and end times for
                   11968: the role.  If no username and domain are specified, will default to
1.934     raeburn  11969: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11970: of role statuses (active, future or previous), roles 
                   11971: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11972: to restrict the list of roles reported. If no array ref is 
                   11973: provided for types, will default to return only active roles.
1.834     albertel 11974: 
1.243     albertel 11975: =back
                   11976: 
                   11977: =head2 User Modification
                   11978: 
                   11979: =over 4
                   11980: 
                   11981: =item *
                   11982: 
1.957     raeburn  11983: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11984: user for the level given by URL.  Optional start and end dates (leave empty
                   11985: string or zero for "no date")
1.191     harris41 11986: 
                   11987: =item *
                   11988: 
1.243     albertel 11989: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11990: change a users, password, possible return values are: ok,
                   11991: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11992: refused
1.191     harris41 11993: 
                   11994: =item *
                   11995: 
1.243     albertel 11996: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11997: 
                   11998: =item *
                   11999: 
1.1058    raeburn  12000: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12001:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12002: 
                   12003: will update user information (firstname,middlename,lastname,generation,
                   12004: permanentemail), and if forceid is true, student/employee ID also.
                   12005: A user's institutional affiliation(s) can also be updated.
                   12006: User information fields will not be overwritten with empty entries 
                   12007: unless the field is included in the $candelete array reference.
                   12008: This array is included when a single user is modified via "Manage Users",
                   12009: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12010: 
                   12011: =item *
                   12012: 
1.286     matthew  12013: modifystudent
                   12014: 
1.957     raeburn  12015: modify a student's enrollment and identification information.
1.286     matthew  12016: The course id is resolved based on the current users environment.  
                   12017: This means the envoking user must be a course coordinator or otherwise
                   12018: associated with a course.
                   12019: 
1.297     matthew  12020: This call is essentially a wrapper for lonnet::modifyuser and
                   12021: lonnet::modify_student_enrollment
1.286     matthew  12022: 
                   12023: Inputs: 
                   12024: 
                   12025: =over 4
                   12026: 
1.957     raeburn  12027: =item B<$udom> Student's loncapa domain
1.286     matthew  12028: 
1.957     raeburn  12029: =item B<$uname> Student's loncapa login name
1.286     matthew  12030: 
1.964     bisitz   12031: =item B<$uid> Student/Employee ID
1.286     matthew  12032: 
1.957     raeburn  12033: =item B<$umode> Student's authentication mode
1.286     matthew  12034: 
1.957     raeburn  12035: =item B<$upass> Student's password
1.286     matthew  12036: 
1.957     raeburn  12037: =item B<$first> Student's first name
1.286     matthew  12038: 
1.957     raeburn  12039: =item B<$middle> Student's middle name
1.286     matthew  12040: 
1.957     raeburn  12041: =item B<$last> Student's last name
1.286     matthew  12042: 
1.957     raeburn  12043: =item B<$gene> Student's generation
1.286     matthew  12044: 
1.957     raeburn  12045: =item B<$usec> Student's section in course
1.286     matthew  12046: 
                   12047: =item B<$end> Unix time of the roles expiration
                   12048: 
                   12049: =item B<$start> Unix time of the roles start date
                   12050: 
                   12051: =item B<$forceid> If defined, allow $uid to be changed
                   12052: 
                   12053: =item B<$desiredhome> server to use as home server for student
                   12054: 
1.957     raeburn  12055: =item B<$email> Student's permanent e-mail address
                   12056: 
                   12057: =item B<$type> Type of enrollment (auto or manual)
                   12058: 
1.963     raeburn  12059: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12060: 
                   12061: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12062: 
1.963     raeburn  12063: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12064: 
1.963     raeburn  12065: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12066: 
1.963     raeburn  12067: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  12068: 
1.286     matthew  12069: =back
1.297     matthew  12070: 
                   12071: =item *
                   12072: 
                   12073: modify_student_enrollment
                   12074: 
                   12075: Change a students enrollment status in a class.  The environment variable
                   12076: 'role.request.course' must be defined for this function to proceed.
                   12077: 
                   12078: Inputs:
                   12079: 
                   12080: =over 4
                   12081: 
                   12082: =item $udom, students domain
                   12083: 
                   12084: =item $uname, students name
                   12085: 
                   12086: =item $uid, students user id
                   12087: 
                   12088: =item $first, students first name
                   12089: 
                   12090: =item $middle
                   12091: 
                   12092: =item $last
                   12093: 
                   12094: =item $gene
                   12095: 
                   12096: =item $usec
                   12097: 
                   12098: =item $end
                   12099: 
                   12100: =item $start
                   12101: 
1.957     raeburn  12102: =item $type
                   12103: 
                   12104: =item $locktype
                   12105: 
                   12106: =item $cid
                   12107: 
                   12108: =item $selfenroll
                   12109: 
                   12110: =item $context
                   12111: 
1.297     matthew  12112: =back
                   12113: 
1.191     harris41 12114: 
                   12115: =item *
                   12116: 
1.243     albertel 12117: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12118: custom role; give a custom role to a user for the level given by URL.  Specify
                   12119: name and domain of role author, and role name
1.191     harris41 12120: 
                   12121: =item *
                   12122: 
1.243     albertel 12123: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12124: 
                   12125: =item *
                   12126: 
1.243     albertel 12127: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12128: 
                   12129: =back
                   12130: 
                   12131: =head2 Course Infomation
                   12132: 
                   12133: =over 4
1.191     harris41 12134: 
                   12135: =item *
                   12136: 
1.1118    foxr     12137: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12138: specified course id, including all environment settings for the
                   12139: course, the description of the course will be in the hash under the
                   12140: key 'description'
1.191     harris41 12141: 
1.1118    foxr     12142: $options is an optional parameter that if supplied is a hash reference that controls
                   12143: what how this function works.  It has the following key/values:
                   12144: 
                   12145: =over 4
                   12146: 
                   12147: =item freshen_cache
                   12148: 
                   12149: If defined, and the environment cache for the course is valid, it is 
                   12150: returned in the returned hash.
                   12151: 
                   12152: =item one_time
                   12153: 
                   12154: If defined, the last cache time is set to _now_
                   12155: 
                   12156: =item user
                   12157: 
                   12158: If defined, the supplied username is used instead of the current user.
                   12159: 
                   12160: 
                   12161: =back
                   12162: 
1.191     harris41 12163: =item *
                   12164: 
1.624     albertel 12165: resdata($name,$domain,$type,@which) : request for current parameter
                   12166: setting for a specific $type, where $type is either 'course' or 'user',
                   12167: @what should be a list of parameters to ask about. This routine caches
                   12168: answers for 5 minutes.
1.243     albertel 12169: 
1.877     foxr     12170: =item *
                   12171: 
                   12172: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12173: data base, returning a hash that is keyed by the resource name and has
                   12174: values that are the resource value.  I believe that the timestamps and
                   12175: versions are also returned.
                   12176: 
                   12177: 
1.243     albertel 12178: =back
                   12179: 
                   12180: =head2 Course Modification
                   12181: 
                   12182: =over 4
1.191     harris41 12183: 
                   12184: =item *
                   12185: 
1.243     albertel 12186: writecoursepref($courseid,%prefs) : write preferences (environment
                   12187: database) for a course
1.191     harris41 12188: 
                   12189: =item *
                   12190: 
1.1011    raeburn  12191: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12192: 
                   12193: =item *
                   12194: 
1.1038    raeburn  12195: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12196: 
1.1167    droeschl 12197: =item *
                   12198: 
                   12199: is_course($courseid), is_course($cdom, $cnum)
                   12200: 
                   12201: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12202: two component version $cdom, $cnum. It checks if the specified course exists.
                   12203: 
                   12204: Returns:
                   12205:     undef if the course doesn't exist, otherwise
                   12206:     in scalar context the combined courseid.
                   12207:     in list context the two components of the course identifier, domain and 
                   12208:     courseid.    
                   12209: 
1.243     albertel 12210: =back
                   12211: 
                   12212: =head2 Resource Subroutines
                   12213: 
                   12214: =over 4
1.191     harris41 12215: 
                   12216: =item *
                   12217: 
1.243     albertel 12218: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12219: 
                   12220: =item *
                   12221: 
1.243     albertel 12222: repcopy($filename) : subscribes to the requested file, and attempts to
                   12223: replicate from the owning library server, Might return
1.607     raeburn  12224: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12225: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12226: resource. Expects the local filesystem pathname
                   12227: (/home/httpd/html/res/....)
                   12228: 
                   12229: =back
                   12230: 
                   12231: =head2 Resource Information
                   12232: 
                   12233: =over 4
1.191     harris41 12234: 
                   12235: =item *
                   12236: 
1.243     albertel 12237: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12238: a vairety of different possible values, $varname should be a request
                   12239: string, and the other parameters can be used to specify who and what
                   12240: one is asking about.
                   12241: 
                   12242: Possible values for $varname are environment.lastname (or other item
                   12243: from the envirnment hash), user.name (or someother aspect about the
                   12244: user), resource.0.maxtries (or some other part and parameter of a
                   12245: resource)
1.204     albertel 12246: 
                   12247: =item *
                   12248: 
1.243     albertel 12249: directcondval($number) : get current value of a condition; reads from a state
                   12250: string
1.204     albertel 12251: 
                   12252: =item *
                   12253: 
1.243     albertel 12254: condval($condidx) : value of condition index based on state
1.204     albertel 12255: 
                   12256: =item *
                   12257: 
1.243     albertel 12258: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12259: resource's metadata, $what should be either a specific key, or either
                   12260: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12261: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12262: 
                   12263: this function automatically caches all requests
1.191     harris41 12264: 
                   12265: =item *
                   12266: 
1.243     albertel 12267: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12268: network of library servers; returns file handle of where SQL and regex results
                   12269: will be stored for query
1.191     harris41 12270: 
                   12271: =item *
                   12272: 
1.243     albertel 12273: symbread($filename) : return symbolic list entry (filename argument optional);
                   12274: returns the data handle
1.191     harris41 12275: 
                   12276: =item *
                   12277: 
1.1190    raeburn  12278: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12279: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12280: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12281: on failure, user must be in a course, as it assumes the existence of
                   12282: the course initial hash, and uses $env('request.course.id'}.  The third
                   12283: arg is an optional reference to a scalar.  If this arg is passed in the 
                   12284: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12285: encrypted; otherwise it will be null.  
1.191     harris41 12286: 
                   12287: =item *
                   12288: 
1.243     albertel 12289: symbclean($symb) : removes versions numbers from a symb, returns the
                   12290: cleaned symb
1.191     harris41 12291: 
                   12292: =item *
                   12293: 
1.243     albertel 12294: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12295: course map, user must be in a course for it to work.
1.191     harris41 12296: 
                   12297: =item *
                   12298: 
1.243     albertel 12299: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12300: 
                   12301: =item *
                   12302: 
1.243     albertel 12303: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12304: a random seed, all arguments are optional, if they aren't sent it uses the
                   12305: environment to derive them. Note: if symb isn't sent and it can't get one
                   12306: from &symbread it will use the current time as its return value
1.191     harris41 12307: 
                   12308: =item *
                   12309: 
1.243     albertel 12310: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12311: unfakeable, receipt
1.191     harris41 12312: 
                   12313: =item *
                   12314: 
1.620     albertel 12315: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12316: 
                   12317: =item *
                   12318: 
1.243     albertel 12319: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12320: 
                   12321: =item *
                   12322: 
1.243     albertel 12323: 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 12324: 
                   12325: =item *
                   12326: 
1.243     albertel 12327: 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 12328: 
                   12329: =item *
                   12330: 
1.243     albertel 12331: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12332: 
                   12333: =item *
                   12334: 
1.243     albertel 12335: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12336: forcing spreadsheet to reevaluate the resource scores next time.
                   12337: 
                   12338: =back
                   12339: 
                   12340: =head2 Storing/Retreiving Data
                   12341: 
                   12342: =over 4
1.191     harris41 12343: 
                   12344: =item *
                   12345: 
1.243     albertel 12346: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12347: for this url; hashref needs to be given and should be a \%hashname; the
                   12348: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12349: be derived from the env
1.191     harris41 12350: 
                   12351: =item *
                   12352: 
1.243     albertel 12353: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12354: uses critical subroutine
1.191     harris41 12355: 
                   12356: =item *
                   12357: 
1.243     albertel 12358: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12359: all args are optional
1.191     harris41 12360: 
                   12361: =item *
                   12362: 
1.717     albertel 12363: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12364: dumps the complete (or key matching regexp) namespace into a hash
                   12365: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12366: normally &store()ed into
                   12367: 
                   12368: $range should be either an integer '100' (give me the first 100
                   12369:                                            matching records)
                   12370:               or be  two integers sperated by a - with no spaces
                   12371:                  '30-50' (give me the 30th through the 50th matching
                   12372:                           records)
                   12373: 
                   12374: 
                   12375: =item *
                   12376: 
                   12377: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12378: replaces a &store() version of data with a replacement set of data
                   12379: for a particular resource in a namespace passed in the $storehash hash 
                   12380: reference
                   12381: 
                   12382: =item *
                   12383: 
1.243     albertel 12384: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12385: works very similar to store/cstore, but all data is stored in a
                   12386: temporary location and can be reset using tmpreset, $storehash should
                   12387: be a hash reference, returns nothing on success
1.191     harris41 12388: 
                   12389: =item *
                   12390: 
1.243     albertel 12391: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12392: similar to restore, but all data is stored in a temporary location and
                   12393: can be reset using tmpreset. Returns a hash of values on success,
                   12394: error string otherwise.
1.191     harris41 12395: 
                   12396: =item *
                   12397: 
1.243     albertel 12398: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12399: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12400: 
                   12401: =item *
                   12402: 
1.243     albertel 12403: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12404: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12405: 
                   12406: =item *
                   12407: 
1.243     albertel 12408: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12409: namesp ($udom and $uname are optional)
1.191     harris41 12410: 
                   12411: =item *
                   12412: 
1.702     albertel 12413: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12414: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12415: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12416: 
1.702     albertel 12417: $range should be either an integer '100' (give me the first 100
                   12418:                                            matching records)
                   12419:               or be  two integers sperated by a - with no spaces
                   12420:                  '30-50' (give me the 30th through the 50th matching
                   12421:                           records)
1.449     matthew  12422: =item *
                   12423: 
                   12424: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12425: $store can be a scalar, an array reference, or if the amount to be 
                   12426: incremented is > 1, a hash reference.
                   12427: 
                   12428: ($udom and $uname are optional)
1.191     harris41 12429: 
                   12430: =item *
                   12431: 
1.243     albertel 12432: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12433: ($udom and $uname are optional)
1.191     harris41 12434: 
                   12435: =item *
                   12436: 
1.243     albertel 12437: cput($namespace,$storehash,$udom,$uname) : critical put
                   12438: ($udom and $uname are optional)
1.191     harris41 12439: 
                   12440: =item *
                   12441: 
1.748     albertel 12442: newput($namespace,$storehash,$udom,$uname) :
                   12443: 
                   12444: Attempts to store the items in the $storehash, but only if they don't
                   12445: currently exist, if this succeeds you can be certain that you have 
                   12446: successfully created a new key value pair in the $namespace db.
                   12447: 
                   12448: 
                   12449: Args:
                   12450:  $namespace: name of database to store values to
                   12451:  $storehash: hashref to store to the db
                   12452:  $udom: (optional) domain of user containing the db
                   12453:  $uname: (optional) name of user caontaining the db
                   12454: 
                   12455: Returns:
                   12456:  'ok' -> succeeded in storing all keys of $storehash
                   12457:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12458:                         least <key> already existed in the db (other
                   12459:                         requested keys may also already exist)
1.967     bisitz   12460:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12461:  'con_lost' -> unable to contact request server
                   12462:  'refused' -> action was not allowed by remote machine
                   12463: 
                   12464: 
                   12465: =item *
                   12466: 
1.243     albertel 12467: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12468: reference filled in from namesp (encrypts the return communication)
                   12469: ($udom and $uname are optional)
1.191     harris41 12470: 
                   12471: =item *
                   12472: 
1.243     albertel 12473: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12474: critical subroutine
                   12475: 
1.806     raeburn  12476: =item *
                   12477: 
1.860     raeburn  12478: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12479: array reference filled in from namespace found in domain level on either
                   12480: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12481: 
                   12482: =item *
                   12483: 
1.860     raeburn  12484: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12485: domain level either on specified domain server ($uhome) or primary domain 
                   12486: server ($udom and $uhome are optional)
1.806     raeburn  12487: 
1.943     raeburn  12488: =item * 
                   12489: 
                   12490: get_domain_defaults($target_domain) : returns hash with defaults for
                   12491: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12492: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12493: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12494: Values are retrieved from cache (if current), or from domain's configuration.db
                   12495: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12496: or lonTabs/domain.tab. 
                   12497: 
                   12498: %domdefaults = &get_auth_defaults($target_domain);
                   12499: 
1.243     albertel 12500: =back
                   12501: 
                   12502: =head2 Network Status Functions
                   12503: 
                   12504: =over 4
1.191     harris41 12505: 
                   12506: =item *
                   12507: 
1.1137    raeburn  12508: dirlist() : return directory list based on URI (first arg).
                   12509: 
                   12510: Inputs: 1 required, 5 optional.
                   12511: 
                   12512: =over
                   12513: 
                   12514: =item 
                   12515: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12516: 
                   12517: =item
                   12518: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12519: 
                   12520: =item
                   12521: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12522: 
                   12523: =item
                   12524: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12525: 
                   12526: =item
                   12527: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12528: 
                   12529: =item 
                   12530: $alternateRoot - path to prepend in place of path from $uri.
                   12531: 
                   12532: =back
                   12533: 
                   12534: Returns: Array of up to two items.
                   12535: 
                   12536: =over
                   12537: 
                   12538: a reference to an array of files/subdirectories
                   12539: 
                   12540: =over
                   12541: 
                   12542: Each element in the array of files/subdirectories is a & separated list of
                   12543: item name and the result of running stat on the item.  If dirlist was requested
                   12544: for a file instead of a directory, the item name will be ''. For a directory 
                   12545: listing, if the item is a metadata file, the element will end &N&M 
                   12546: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12547: default copyright set (1).  
                   12548: 
                   12549: =back
                   12550: 
                   12551: a scalar containing error condition (if encountered).
                   12552: 
                   12553: =over
                   12554: 
                   12555: =item 
                   12556: no_host (no homeserver identified for $username:$domain).
                   12557: 
                   12558: =item 
                   12559: no_such_host (server contacted for listing not identified as valid host).
                   12560: 
                   12561: =item 
                   12562: con_lost (connection to remote server failed).
                   12563: 
                   12564: =item 
                   12565: refused (invalid $username:$domain received on lond side).
                   12566: 
                   12567: =item 
                   12568: no_such_dir (directory at specified path on lond side does not exist). 
                   12569: 
                   12570: =item 
                   12571: empty (directory at specified path on lond side is empty).
                   12572: 
                   12573: =over
                   12574: 
                   12575: This is currently not encountered because the &ls3, &ls2, 
                   12576: &ls (_handler) routines on the lond side do not filter out
                   12577: . and .. from a directory listing. 
                   12578: 
                   12579: =back
                   12580: 
                   12581: =back
                   12582: 
                   12583: =back
1.191     harris41 12584: 
                   12585: =item *
                   12586: 
1.243     albertel 12587: spareserver() : find server with least workload from spare.tab
                   12588: 
1.986     foxr     12589: 
                   12590: =item *
                   12591: 
                   12592: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12593: if there is no corresponding loncapa host.
                   12594: 
1.243     albertel 12595: =back
                   12596: 
1.986     foxr     12597: 
1.243     albertel 12598: =head2 Apache Request
                   12599: 
                   12600: =over 4
1.191     harris41 12601: 
                   12602: =item *
                   12603: 
1.243     albertel 12604: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12605: localhost, posts hash
                   12606: 
                   12607: =back
                   12608: 
                   12609: =head2 Data to String to Data
                   12610: 
                   12611: =over 4
1.191     harris41 12612: 
                   12613: =item *
                   12614: 
1.243     albertel 12615: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12616: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12617: 
                   12618: =item *
                   12619: 
1.243     albertel 12620: hashref2str($hashref) : convert a hashref into a string complete with
                   12621: escaping and '=' and '&' separators, supports elements that are
                   12622: arrayrefs and hashrefs
1.191     harris41 12623: 
                   12624: =item *
                   12625: 
1.243     albertel 12626: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12627: with escaping and '&' separators, supports elements that are arrayrefs
                   12628: and hashrefs
1.191     harris41 12629: 
                   12630: =item *
                   12631: 
1.243     albertel 12632: str2hash($string) : convert string to hash using unescaping and
                   12633: splitting on '=' and '&', supports elements that are arrayrefs and
                   12634: hashrefs
1.191     harris41 12635: 
                   12636: =item *
                   12637: 
1.243     albertel 12638: str2array($string) : convert string to hash using unescaping and
                   12639: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12640: 
                   12641: =back
                   12642: 
                   12643: =head2 Logging Routines
                   12644: 
                   12645: 
                   12646: These routines allow one to make log messages in the lonnet.log and
                   12647: lonnet.perm logfiles.
1.191     harris41 12648: 
1.1119    foxr     12649: =over 4
                   12650: 
1.191     harris41 12651: =item *
                   12652: 
1.243     albertel 12653: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12654: 
                   12655: =item *
                   12656: 
1.243     albertel 12657: logthis() : append message to the normal lonnet.log file, it gets
                   12658: preiodically rolled over and deleted.
1.191     harris41 12659: 
                   12660: =item *
                   12661: 
1.243     albertel 12662: logperm() : append a permanent message to lonnet.perm.log, this log
                   12663: file never gets deleted by any automated portion of the system, only
                   12664: messages of critical importance should go in here.
                   12665: 
1.1119    foxr     12666: 
1.243     albertel 12667: =back
                   12668: 
                   12669: =head2 General File Helper Routines
                   12670: 
                   12671: =over 4
1.191     harris41 12672: 
                   12673: =item *
                   12674: 
1.481     raeburn  12675: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12676: (a) files in /uploaded
                   12677:   (i) If a local copy of the file exists - 
                   12678:       compares modification date of local copy with last-modified date for 
                   12679:       definitive version stored on home server for course. If local copy is 
                   12680:       stale, requests a new version from the home server and stores it. 
                   12681:       If the original has been removed from the home server, then local copy 
                   12682:       is unlinked.
                   12683:   (ii) If local copy does not exist -
                   12684:       requests the file from the home server and stores it. 
                   12685:   
                   12686:   If $caller is 'uploadrep':  
                   12687:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12688:     for request for files originally uploaded via DOCS. 
                   12689:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12690:   
                   12691:   Otherwise:
                   12692:      This indicates a call from the content generation phase of the request.
                   12693:      -  returns the entire contents of the file or -1.
                   12694:      
                   12695: (b) files in /res
                   12696:    - returns the entire contents of a file or -1; 
                   12697:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12698: 
1.712     albertel 12699: 
                   12700: =item *
                   12701: 
                   12702: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12703:                   reference
                   12704: 
                   12705: returns either a stat() list of data about the file or an empty list
                   12706: if the file doesn't exist or couldn't find out about it (connection
                   12707: problems or user unknown)
                   12708: 
1.191     harris41 12709: =item *
                   12710: 
1.243     albertel 12711: filelocation($dir,$file) : returns file system location of a file
                   12712: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12713: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12714: and a file of ../bob will become /a/bob)
1.191     harris41 12715: 
                   12716: =item *
                   12717: 
                   12718: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12719: filelocation except for hrefs
                   12720: 
                   12721: =item *
                   12722: 
                   12723: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12724: 
1.243     albertel 12725: =back
                   12726: 
1.608     albertel 12727: =head2 Usererfile file routines (/uploaded*)
                   12728: 
                   12729: =over 4
                   12730: 
                   12731: =item *
                   12732: 
                   12733: userfileupload(): main rotine for putting a file in a user or course's
                   12734:                   filespace, arguments are,
                   12735: 
1.620     albertel 12736:  formname - required - this is the name of the element in $env where the
1.608     albertel 12737:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12738:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12739:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12740:  context - if coursedoc, store the file in the course of the active role
                   12741:              of the current user; 
                   12742:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12743:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12744:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12745:          if undefined, it will be placed in "unknown"
                   12746: 
                   12747:  (This routine calls clean_filename() to remove any dangerous
                   12748:  characters from the filename, and then calls finuserfileupload() to
                   12749:  complete the transaction)
                   12750: 
                   12751:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12752:  and /adm/notfound.html if unsuccessful
                   12753: 
                   12754: =item *
                   12755: 
                   12756: clean_filename(): routine for cleaing a filename up for storage in
                   12757:                  userfile space, argument is:
                   12758: 
                   12759:  filename - proposed filename
                   12760: 
                   12761: returns: the new clean filename
                   12762: 
                   12763: =item *
                   12764: 
1.1090    raeburn  12765: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12766: userspace, probably shouldn't be called directly
                   12767: 
                   12768:   docuname: username or courseid of destination for the file
                   12769:   docudom: domain of user/course of destination for the file
                   12770:   formname: same as for userfileupload()
1.1090    raeburn  12771:   fname: filename (including subdirectories) for the file
                   12772:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12773:   allfiles: reference to hash used to store objects found by parser
                   12774:   codebase: reference to hash used for codebases of java objects found by parser
                   12775:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12776:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12777:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12778:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12779:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12780:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12781:   mimetype: reference to scalar to accommodate mime type determined
                   12782:             from File::MMagic if $parser = parse.
1.608     albertel 12783: 
                   12784:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12785:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12786:  was 'overwrite').
                   12787:  
1.608     albertel 12788: 
                   12789: =item *
                   12790: 
                   12791: renameuserfile(): renames an existing userfile to a new name
                   12792: 
                   12793:   Args:
                   12794:    docuname: username or courseid of destination for the file
                   12795:    docudom: domain of user/course of destination for the file
                   12796:    old: current file name (including any subdirs under userfiles)
                   12797:    new: desired file name (including any subdirs under userfiles)
                   12798: 
                   12799: =item *
                   12800: 
                   12801: mkdiruserfile(): creates a directory is a userfiles dir
                   12802: 
                   12803:   Args:
                   12804:    docuname: username or courseid of destination for the file
                   12805:    docudom: domain of user/course of destination for the file
                   12806:    dir: dir to create (including any subdirs under userfiles)
                   12807: 
                   12808: =item *
                   12809: 
                   12810: removeuserfile(): removes a file that exists in userfiles
                   12811: 
                   12812:   Args:
                   12813:    docuname: username or courseid of destination for the file
                   12814:    docudom: domain of user/course of destination for the file
                   12815:    fname: filname to delete (including any subdirs under userfiles)
                   12816: 
                   12817: =item *
                   12818: 
                   12819: removeuploadedurl(): convience function for removeuserfile()
                   12820: 
                   12821:   Args:
                   12822:    url:  a full /uploaded/... url to delete
                   12823: 
1.747     albertel 12824: =item * 
                   12825: 
                   12826: get_portfile_permissions():
                   12827:   Args:
                   12828:     domain: domain of user or course contain the portfolio files
                   12829:     user: name of user or num of course contain the portfolio files
                   12830:   Returns:
                   12831:     hashref of a dump of the proper file_permissions.db
                   12832:    
                   12833: 
                   12834: =item * 
                   12835: 
                   12836: get_access_controls():
                   12837: 
                   12838: Args:
                   12839:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12840:   group: (optional) the group you want the files associated with
                   12841:   file: (optional) the file you want access info on
                   12842: 
                   12843: Returns:
1.749     raeburn  12844:     a hash (keys are file names) of hashes containing
                   12845:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12846:         values are XML containing access control settings (see below) 
1.747     albertel 12847: 
                   12848: Internal notes:
                   12849: 
1.749     raeburn  12850:  access controls are stored in file_permissions.db as key=value pairs.
                   12851:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12852:         where scope -> public,guest,course,group,domains or users.
                   12853:               end -> UNIX time for end of access (0 -> no end date)
                   12854:               start -> UNIX time for start of access
                   12855: 
                   12856:     value -> XML description of access control
                   12857:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12858:             <start></start>
                   12859:             <end></end>
                   12860: 
                   12861:             <password></password>  for scope type = guest
                   12862: 
                   12863:             <domain></domain>     for scope type = course or group
                   12864:             <number></number>
                   12865:             <roles id="">
                   12866:              <role></role>
                   12867:              <access></access>
                   12868:              <section></section>
                   12869:              <group></group>
                   12870:             </roles>
                   12871: 
                   12872:             <dom></dom>         for scope type = domains
                   12873: 
                   12874:             <users>             for scope type = users
                   12875:              <user>
                   12876:               <uname></uname>
                   12877:               <udom></udom>
                   12878:              </user>
                   12879:             </users>
                   12880:            </scope> 
                   12881:               
                   12882:  Access data is also aggregated for each file in an additional key=value pair:
                   12883:  key -> path to file/file_name\0accesscontrol 
                   12884:  value -> reference to hash
                   12885:           hash contains key = value pairs
                   12886:           where key = uniqueID:scope_end_start
                   12887:                 value = UNIX time record was last updated
                   12888: 
                   12889:           Used to improve speed of look-ups of access controls for each file.  
                   12890:  
                   12891:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12892: 
                   12893: modify_access_controls():
                   12894: 
                   12895: Modifies access controls for a portfolio file
                   12896: Args
                   12897: 1. file name
                   12898: 2. reference to hash of required changes,
                   12899: 3. domain
                   12900: 4. username
                   12901:   where domain,username are the domain of the portfolio owner 
                   12902:   (either a user or a course) 
                   12903: 
                   12904: Returns:
                   12905: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12906: 2. result of deletions ('ok' or 'error', with error message).
                   12907: 3. reference to hash of any new or updated access controls.
                   12908: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12909:    key = integer (inbound ID)
                   12910:    value = uniqueID  
1.747     albertel 12911: 
1.608     albertel 12912: =back
                   12913: 
1.243     albertel 12914: =head2 HTTP Helper Routines
                   12915: 
                   12916: =over 4
                   12917: 
1.191     harris41 12918: =item *
                   12919: 
                   12920: escape() : unpack non-word characters into CGI-compatible hex codes
                   12921: 
                   12922: =item *
                   12923: 
                   12924: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12925: 
1.243     albertel 12926: =back
                   12927: 
                   12928: =head1 PRIVATE SUBROUTINES
                   12929: 
                   12930: =head2 Underlying communication routines (Shouldn't call)
                   12931: 
                   12932: =over 4
                   12933: 
                   12934: =item *
                   12935: 
                   12936: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12937: 
                   12938: =item *
                   12939: 
                   12940: reply() : uses subreply to send a message to remote machine, logs all failures
                   12941: 
                   12942: =item *
                   12943: 
                   12944: critical() : passes a critical message to another server; if cannot
                   12945: get through then place message in connection buffer directory and
                   12946: returns con_delayed, if incapable of saving message, returns
                   12947: con_failed
                   12948: 
                   12949: =item *
                   12950: 
                   12951: reconlonc() : tries to reconnect lonc client processes.
                   12952: 
                   12953: =back
                   12954: 
                   12955: =head2 Resource Access Logging
                   12956: 
                   12957: =over 4
                   12958: 
                   12959: =item *
                   12960: 
                   12961: flushcourselogs() : flush (save) buffer logs and access logs
                   12962: 
                   12963: =item *
                   12964: 
                   12965: courselog($what) : save message for course in hash
                   12966: 
                   12967: =item *
                   12968: 
                   12969: courseacclog($what) : save message for course using &courselog().  Perform
                   12970: special processing for specific resource types (problems, exams, quizzes, etc).
                   12971: 
1.191     harris41 12972: =item *
                   12973: 
                   12974: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12975: as a PerlChildExitHandler
1.243     albertel 12976: 
                   12977: =back
                   12978: 
                   12979: =head2 Other
                   12980: 
                   12981: =over 4
                   12982: 
                   12983: =item *
                   12984: 
                   12985: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12986: 
                   12987: =back
                   12988: 
                   12989: =cut
1.877     foxr     12990: 

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