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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1194  ! raeburn     4: # $Id: lonnet.pm,v 1.1193 2012/10/31 12:54:23 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.1193    raeburn  2648: #
                   2649: # Determine if the current user should be able to edit a particular resource,
                   2650: # when viewing in course context.
                   2651: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2652: #     Functions.
                   2653: # (b) When displaying folder contents in course editor, used to determine if
                   2654: #     "Edit" link will be displayed alongside resource.
                   2655: #
                   2656: #  input: 3 args -- filename (decluttered), course number and course domain.
                   2657: #  output: array of four scalars -- 
                   2658: #          $cfile -- url for file editing if editable on current server
                   2659: #          $home -- homeserver of resource (i.e., for author if published,
                   2660: #                                           or course if uploaded.).
                   2661: #          $switchserver --  1 if server switch will be needed.
                   2662: #          $uploaded -- 1 if resource is a file uploaded to a course.
                   2663: #
                   2664: 
                   2665: sub can_edit_resource {
1.1194  ! raeburn  2666:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
        !          2667:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
        !          2668: #
        !          2669: # For aboutme pages user can only edit his/her own.
        !          2670: #
        !          2671:     if ($resurl =~ m{^/adm/($match_domain)/($match_username)/aboutme$}) {
        !          2672:         my ($sdom,$sname) = ($1,$2);
        !          2673:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
        !          2674:             $home = $env{'user.home'};
        !          2675:             $cfile = $resurl;
        !          2676:             if ($env{'form.forceedit'}) {
        !          2677:                 $forceview = 1;
        !          2678:             } else {
        !          2679:                 $forceedit = 1;
        !          2680:             }
        !          2681:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
        !          2682:         } else {
        !          2683:             return;
        !          2684:         }
        !          2685:     }
        !          2686: 
        !          2687:     if ($env{'request.course.id'}) {
        !          2688:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
        !          2689:         if ($group ne '') {
        !          2690: # if this is a group homepage or group bulletin board, check group privs
        !          2691:             my $allowed = 0;
        !          2692:             if ($resurl =~ m{^/adm/$cdom/$cnum/$group/smppg$}) {
        !          2693:                 if ((&Apache::lonnet::allowed('mdg',$env{'request.course.id'}.
        !          2694:                             ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
        !          2695:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
        !          2696:                     $allowed = 1;
        !          2697:                 }
        !          2698:             } elsif ($resurl =~ m{^/adm/$cdom/$cnum/\d+/bulletinboard$}) {
        !          2699:                 unless ((&allowed(&Apache::lonnet::allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) ||
        !          2700:                         (&allowed('cgb',$env{'request.course.id'}.$group)) || $crsedit) {
        !          2701:                     $allowed = 1;
        !          2702:                 }
        !          2703:             }
        !          2704:             if ($allowed) {
        !          2705:                 $home=&homeserver($cnum,$cdom);
        !          2706:                 if ($env{'form.forceedit'}) {
        !          2707:                     $forceview = 1;
        !          2708:                 } else {
        !          2709:                     $forceedit = 1;
        !          2710:                 }
        !          2711:                 $cfile = $resurl;
        !          2712:             } else {
        !          2713:                 return;
        !          2714:             }
        !          2715:         } else {
        !          2716: #
        !          2717: # No edit allowed where CC has switched to student role.
        !          2718: #
        !          2719:             unless ($crsedit) {
        !          2720:                 return;
        !          2721:             }
        !          2722:         }
        !          2723:     }
        !          2724: 
1.1193    raeburn  2725:     if ($file ne '') {
                   2726:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194  ! raeburn  2727:             if (&is_course_upload($file,$cnum,$cdom)) {
        !          2728:                 $uploaded = 1;
        !          2729:                 $incourse = 1;
1.1193    raeburn  2730:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2731:                     $cfile = &hreflocation('',$file);
1.1194  ! raeburn  2732:                     $forceedit = 1;
        !          2733:                 }
        !          2734:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
        !          2735:                 $incourse = 1;
        !          2736:                 if ($env{'form.forceedit'}) {
        !          2737:                     $forceview = 1;
        !          2738:                 } else {
        !          2739:                     $forceedit = 1;
        !          2740:                 }
        !          2741:                 $cfile = $resurl;
        !          2742:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
        !          2743:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
        !          2744:                     $incourse = 1;
        !          2745:                     if ($env{'form.forceedit'}) {
        !          2746:                         $forceview = 1;
        !          2747:                     } else {
        !          2748:                         $forceedit = 1;
        !          2749:                     }
        !          2750:                     $cfile = $resurl;
        !          2751:                 } elsif (($resurl eq '/res/lib/templates/simpleproblem.problem')) {
        !          2752:                     $incourse = 1;
        !          2753:                     $cfile = $resurl.'/smpedit';
        !          2754:                 } elsif ($resurl =~ /ext/) {
        !          2755:                     $incourse = 1;
        !          2756:                     # is external
        !          2757:                 }
        !          2758:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
        !          2759:                 my $template = '/res/lib/templates/simpleproblem.problem';
        !          2760:                 if (&is_on_map($template)) { 
        !          2761:                     $incourse = 1;
        !          2762:                     $forceview = 1;
        !          2763:                     $cfile = $template;
1.1193    raeburn  2764:                 }
                   2765:             }
                   2766:         }
1.1194  ! raeburn  2767:         if ($uploaded || $incourse) {
        !          2768:             $home=&homeserver($cnum,$cdom);
        !          2769:         } else {
1.1193    raeburn  2770:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2771:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2772:             # Check that the user has permission to edit this resource
                   2773:             my $setpriv = 1;
                   2774:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2775:             if (defined($cfudom)) {
                   2776:                 $home=&homeserver($cfuname,$cfudom);
                   2777:                 $cfile=$file;
                   2778:             }
                   2779:         }
1.1194  ! raeburn  2780:         if (($cfile ne '') && (!$incourse || $uploaded) && 
        !          2781:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2782:             my @ids=&current_machine_ids();
                   2783:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2784:                 $switchserver=1;
                   2785:             }
                   2786:         }
                   2787:     }
1.1194  ! raeburn  2788:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2789: }
                   2790: 
                   2791: sub is_course_upload {
                   2792:     my ($file,$cnum,$cdom) = @_;
                   2793:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2794:     $uploadpath =~ s{^\/}{};
                   2795:     if (($file =~ m{^\Q$uploadpath\E/userfiles/docs/}) ||
                   2796:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/docs/})) {
                   2797:         return 1;
                   2798:     }
                   2799:     return;
                   2800: }
                   2801: 
1.1194  ! raeburn  2802: sub in_course {
        !          2803:     my ($udom,$uname,$cdom,$cnum,$type) = @_;
        !          2804:     $type ||= 'any';
        !          2805:     if (!defined($cdom) || !defined($cnum)) {
        !          2806:         my $cid  = $env{'request.course.id'};
        !          2807:         $cdom = $env{'course.'.$cid.'.domain'};
        !          2808:         $cnum = $env{'course.'.$cid.'.num'};
        !          2809:     }
        !          2810:     my $typesref;
        !          2811:     if ($type eq 'all') {
        !          2812:         $typesref = ['active','previous','future'];
        !          2813:     } elsif ($type eq 'previous' || $type eq 'future') {
        !          2814:         $typesref = [$type];
        !          2815:     }
        !          2816:     my %roles = &get_my_roles($uname,$udom,'userroles',
        !          2817:                               $typesref,undef,[$cdom]);
        !          2818:     my ($tmp) = keys(%roles);
        !          2819:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
        !          2820:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
        !          2821:     if (@course_roles > 0) {
        !          2822:         return 1;
        !          2823:     }
        !          2824:     return 0;
        !          2825: }
        !          2826: 
1.478     albertel 2827: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2828: # input: action, courseID, current domain, intended
1.637     raeburn  2829: #        path to file, source of file, instruction to parse file for objects,
                   2830: #        ref to hash for embedded objects,
                   2831: #        ref to hash for codebase of java objects.
1.1095    raeburn  2832: #        reference to scalar to accommodate mime type determined
                   2833: #          from File::MMagic if $parser = parse.
1.637     raeburn  2834: #
1.485     raeburn  2835: # output: url to file (if action was uploaddoc), 
                   2836: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2837: #
1.478     albertel 2838: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2839: # course.
1.477     raeburn  2840: #
1.478     albertel 2841: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2842: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2843: #          course's home server.
1.477     raeburn  2844: #
1.478     albertel 2845: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2846: #          be copied from $source (current location) to 
                   2847: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2848: #         and will then be copied to
                   2849: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2850: #         course's home server.
1.485     raeburn  2851: #
1.481     raeburn  2852: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2853: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2854: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2855: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2856: #         in course's home server.
1.637     raeburn  2857: #
1.477     raeburn  2858: 
                   2859: sub process_coursefile {
1.1095    raeburn  2860:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2861:         $mimetype)=@_;
1.477     raeburn  2862:     my $fetchresult;
1.638     albertel 2863:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2864:     if ($action eq 'propagate') {
1.638     albertel 2865:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2866: 			     $home);
1.481     raeburn  2867:     } else {
1.477     raeburn  2868:         my $fpath = '';
                   2869:         my $fname = $file;
1.478     albertel 2870:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2871:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2872:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2873:         if ($action eq 'copy') {
                   2874:             if ($source eq '') {
                   2875:                 $fetchresult = 'no source file';
                   2876:                 return $fetchresult;
                   2877:             } else {
                   2878:                 my $destination = $filepath.'/'.$fname;
                   2879:                 rename($source,$destination);
                   2880:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2881:                                  $home);
1.481     raeburn  2882:             }
                   2883:         } elsif ($action eq 'uploaddoc') {
                   2884:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2885:             print $fh $env{'form.'.$source};
1.481     raeburn  2886:             close($fh);
1.637     raeburn  2887:             if ($parser eq 'parse') {
1.1024    raeburn  2888:                 my $mm = new File::MMagic;
1.1095    raeburn  2889:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2890:                 if ($type eq 'text/html') {
1.1024    raeburn  2891:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2892:                     unless ($parse_result eq 'ok') {
                   2893:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2894:                     }
1.637     raeburn  2895:                 }
1.1095    raeburn  2896:                 if (ref($mimetype)) {
                   2897:                     $$mimetype = $type;
                   2898:                 } 
1.637     raeburn  2899:             }
1.477     raeburn  2900:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2901:                                  $home);
1.481     raeburn  2902:             if ($fetchresult eq 'ok') {
                   2903:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2904:             } else {
                   2905:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2906:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2907:                 return '/adm/notfound.html';
                   2908:             }
1.477     raeburn  2909:         }
                   2910:     }
1.485     raeburn  2911:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2912:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2913:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2914:     }
                   2915:     return $fetchresult;
                   2916: }
                   2917: 
1.637     raeburn  2918: sub build_filepath {
                   2919:     my ($fpath) = @_;
                   2920:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2921:     unless ($fpath eq '') {
                   2922:         my @parts=split('/',$fpath);
                   2923:         foreach my $part (@parts) {
                   2924:             $filepath.= '/'.$part;
                   2925:             if ((-e $filepath)!=1) {
                   2926:                 mkdir($filepath,0777);
                   2927:             }
                   2928:         }
                   2929:     }
                   2930:     return $filepath;
                   2931: }
                   2932: 
                   2933: sub store_edited_file {
1.638     albertel 2934:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2935:     my $file = $primary_url;
                   2936:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2937:     my $fpath = '';
                   2938:     my $fname = $file;
                   2939:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2940:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2941:     my $filepath = &build_filepath($fpath);
                   2942:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2943:     print $fh $content;
                   2944:     close($fh);
1.638     albertel 2945:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2946:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2947: 			  $home);
1.637     raeburn  2948:     if ($$fetchresult eq 'ok') {
                   2949:         return '/uploaded/'.$fpath.'/'.$fname;
                   2950:     } else {
1.638     albertel 2951:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2952: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2953:         return '/adm/notfound.html';
                   2954:     }
                   2955: }
                   2956: 
1.531     albertel 2957: sub clean_filename {
1.831     albertel 2958:     my ($fname,$args)=@_;
1.315     www      2959: # Replace Windows backslashes by forward slashes
1.257     www      2960:     $fname=~s/\\/\//g;
1.831     albertel 2961:     if (!$args->{'keep_path'}) {
                   2962:         # Get rid of everything but the actual filename
                   2963: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2964:     }
1.315     www      2965: # Replace spaces by underscores
                   2966:     $fname=~s/\s+/\_/g;
                   2967: # Replace all other weird characters by nothing
1.831     albertel 2968:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2969: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2970: # numbers
                   2971:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2972:     return $fname;
                   2973: }
1.1051    raeburn  2974: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2975: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2976: # image with the same aspect ratio as the original, but with dimensions which do 
                   2977: # not exceed $resizewidth and $resizeheight.
                   2978:  
1.984     neumanie 2979: sub resizeImage {
1.1051    raeburn  2980:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2981:     my $ima = Image::Magick->new;
                   2982:     my $resized;
                   2983:     if (-e $img_path) {
                   2984:         $ima->Read($img_path);
                   2985:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2986:             my $width = $ima->Get('width');
                   2987:             my $height = $ima->Get('height');
                   2988:             if ($width > $resizewidth) {
                   2989: 	        my $factor = $width/$resizewidth;
                   2990:                 my $newheight = $height/$factor;
                   2991:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2992:                 $resized = 1;
                   2993:             }
                   2994:         }
                   2995:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2996:             my $width = $ima->Get('width');
                   2997:             my $height = $ima->Get('height');
                   2998:             if ($height > $resizeheight) {
                   2999:                 my $factor = $height/$resizeheight;
                   3000:                 my $newwidth = $width/$factor;
                   3001:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3002:                 $resized = 1;
                   3003:             }
                   3004:         }
                   3005:         if ($resized) {
                   3006:             $ima->Write($img_path);
                   3007:         }
                   3008:     }
                   3009:     return;
1.977     amueller 3010: }
                   3011: 
1.608     albertel 3012: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3013: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3014: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3015: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3016: #                                    canceloverwrite, or ''. 
                   3017: #                   if 'coursedoc': upload to the current course
                   3018: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3019: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3020: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3021: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3022: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3023: #        $allfiles - reference to hash for embedded objects
                   3024: #        $codebase - reference to hash for codebase of java objects
                   3025: #        $desuname - username for permanent storage of uploaded file
                   3026: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3027: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3028: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3029: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3030: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3031: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3032: #                    from File::MMagic.
1.858     raeburn  3033: # 
1.686     albertel 3034: # output: url of file in userspace, or error: <message> 
                   3035: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3036: 
1.531     albertel 3037: sub userfileupload {
1.1090    raeburn  3038:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3039:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3040:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3041:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3042:     $fname=&clean_filename($fname);
1.1090    raeburn  3043:     # See if there is anything left
1.257     www      3044:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3045:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3046:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3047:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3048:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3049:         my $now = time;
1.1090    raeburn  3050:         my $filepath;
1.1095    raeburn  3051:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3052:              $filepath = 'tmp/helprequests/'.$now;
                   3053:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3054:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3055:                          '_'.$env{'user.domain'}.'/pending';
                   3056:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3057:             my ($docuname,$docudom);
                   3058:             if ($destudom) {
                   3059:                 $docudom = $destudom;
                   3060:             } else {
                   3061:                 $docudom = $env{'user.domain'};
                   3062:             }
                   3063:             if ($destuname) {
                   3064:                 $docuname = $destuname;
                   3065:             } else {
                   3066:                 $docuname = $env{'user.name'};
                   3067:             }
                   3068:             if (exists($env{'form.group'})) {
                   3069:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3070:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3071:             }
                   3072:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3073:             if ($context eq 'canceloverwrite') {
                   3074:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3075:                 if (-e  $tempfile) {
                   3076:                     my @info = stat($tempfile);
                   3077:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3078:                         unlink($tempfile);
                   3079:                     }
                   3080:                 }
                   3081:                 return;
1.523     raeburn  3082:             }
                   3083:         }
1.1090    raeburn  3084:         # Create the directory if not present
1.741     raeburn  3085:         my @parts=split(/\//,$filepath);
                   3086:         my $fullpath = $perlvar{'lonDaemons'};
                   3087:         for (my $i=0;$i<@parts;$i++) {
                   3088:             $fullpath .= '/'.$parts[$i];
                   3089:             if ((-e $fullpath)!=1) {
                   3090:                 mkdir($fullpath,0777);
                   3091:             }
                   3092:         }
                   3093:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3094:         print $fh $env{'form.'.$formname};
                   3095:         close($fh);
1.1090    raeburn  3096:         if ($context eq 'existingfile') {
                   3097:             my @info = stat($fullpath.'/'.$fname);
                   3098:             return ($fullpath.'/'.$fname,$info[9]);
                   3099:         } else {
                   3100:             return $fullpath.'/'.$fname;
                   3101:         }
1.523     raeburn  3102:     }
1.995     raeburn  3103:     if ($subdir eq 'scantron') {
                   3104:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3105:     } else {
1.995     raeburn  3106:         $fname="$subdir/$fname";
                   3107:     }
1.1090    raeburn  3108:     if ($context eq 'coursedoc') {
1.638     albertel 3109: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3110: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3111:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3112:             return &finishuserfileupload($docuname,$docudom,
                   3113: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3114: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3115:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3116:         } else {
1.620     albertel 3117:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 3118:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3119: 				       $fname,$formname,$parser,
1.1095    raeburn  3120: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3121:         }
1.719     banghart 3122:     } elsif (defined($destuname)) {
                   3123:         my $docuname=$destuname;
                   3124:         my $docudom=$destudom;
1.860     raeburn  3125: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3126: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3127:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3128:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3129:     } else {
1.638     albertel 3130:         my $docuname=$env{'user.name'};
                   3131:         my $docudom=$env{'user.domain'};
1.714     raeburn  3132:         if (exists($env{'form.group'})) {
                   3133:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3134:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3135:         }
1.860     raeburn  3136: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3137: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3138:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3139:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3140:     }
1.271     www      3141: }
                   3142: 
                   3143: sub finishuserfileupload {
1.860     raeburn  3144:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3145:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3146:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3147:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3148:   
1.860     raeburn  3149:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3150:     $file=$fname;
                   3151:     if ($fname=~m|/|) {
                   3152:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3153: 	$path.=$fnamepath.'/';
                   3154:     }
1.259     www      3155:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3156:     my $count;
                   3157:     for ($count=4;$count<=$#parts;$count++) {
                   3158:         $filepath.="/$parts[$count]";
                   3159:         if ((-e $filepath)!=1) {
                   3160: 	    mkdir($filepath,0777);
                   3161:         }
                   3162:     }
1.984     neumanie 3163: 
1.258     www      3164: # Save the file
                   3165:     {
1.701     albertel 3166: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3167: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3168: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3169: 	    return '/adm/notfound.html';
                   3170: 	}
1.1090    raeburn  3171:         if ($context eq 'overwrite') {
1.1117    foxr     3172:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3173:             my $target = $filepath.'/'.$file;
                   3174:             if (-e $source) {
                   3175:                 my @info = stat($source);
                   3176:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3177:                     unless (&File::Copy::move($source,$target)) {
                   3178:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3179:                         return "Moving from $source failed";
                   3180:                     }
                   3181:                 } else {
                   3182:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3183:                 }
                   3184:             } else {
                   3185:                 return "Temporary file: $source missing";
                   3186:             }
                   3187:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3188: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3189: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3190: 	    return '/adm/notfound.html';
                   3191: 	}
1.570     albertel 3192: 	close(FH);
1.1051    raeburn  3193:         if ($resizewidth && $resizeheight) {
                   3194:             my $mm = new File::MMagic;
                   3195:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3196:             if ($mime_type =~ m{^image/}) {
                   3197: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3198:             }  
1.977     amueller 3199: 	}
1.258     www      3200:     }
1.1152    raeburn  3201:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3202:         if (ref($mimetype)) {
                   3203:             if ($$mimetype eq '') {
                   3204:                 my $mm = new File::MMagic;
                   3205:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3206:                 $$mimetype = $type;
                   3207:             }
                   3208:         }
                   3209:     }
1.637     raeburn  3210:     if ($parser eq 'parse') {
1.1152    raeburn  3211:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3212:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3213:                                                        $allfiles,$codebase);
                   3214:             unless ($parse_result eq 'ok') {
                   3215:                 &logthis('Failed to parse '.$filepath.$file.
                   3216: 	   	         ' for embedded media: '.$parse_result); 
                   3217:             }
1.637     raeburn  3218:         }
                   3219:     }
1.860     raeburn  3220:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3221:         my $input = $filepath.'/'.$file;
                   3222:         my $output = $filepath.'/'.'tn-'.$file;
                   3223:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3224:         system("convert -sample $thumbsize $input $output");
                   3225:         if (-e $filepath.'/'.'tn-'.$file) {
                   3226:             $fetchthumb  = 1; 
                   3227:         }
                   3228:     }
1.858     raeburn  3229:  
1.259     www      3230: # Notify homeserver to grep it
                   3231: #
1.984     neumanie 3232:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3233:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3234:     if ($fetchresult eq 'ok') {
1.860     raeburn  3235:         if ($fetchthumb) {
                   3236:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3237:             if ($thumbresult ne 'ok') {
                   3238:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3239:                          $docuhome.': '.$thumbresult);
                   3240:             }
                   3241:         }
1.259     www      3242: #
1.258     www      3243: # Return the URL to it
1.494     albertel 3244:         return '/uploaded/'.$path.$file;
1.263     www      3245:     } else {
1.494     albertel 3246:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3247: 		 ': '.$fetchresult);
1.263     www      3248:         return '/adm/notfound.html';
1.858     raeburn  3249:     }
1.493     albertel 3250: }
                   3251: 
1.637     raeburn  3252: sub extract_embedded_items {
1.961     raeburn  3253:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3254:     my @state = ();
1.1164    raeburn  3255:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3256:     my %javafiles = (
                   3257:                       codebase => '',
                   3258:                       code => '',
                   3259:                       archive => ''
                   3260:                     );
                   3261:     my %mediafiles = (
                   3262:                       src => '',
                   3263:                       movie => '',
                   3264:                      );
1.648     raeburn  3265:     my $p;
                   3266:     if ($content) {
                   3267:         $p = HTML::LCParser->new($content);
                   3268:     } else {
1.961     raeburn  3269:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3270:     }
1.641     albertel 3271:     while (my $t=$p->get_token()) {
1.640     albertel 3272: 	if ($t->[0] eq 'S') {
                   3273: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3274: 	    push(@state, $tagname);
1.648     raeburn  3275:             if (lc($tagname) eq 'allow') {
                   3276:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3277:             }
1.640     albertel 3278: 	    if (lc($tagname) eq 'img') {
                   3279: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3280: 	    }
1.886     albertel 3281: 	    if (lc($tagname) eq 'a') {
                   3282: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3283: 	    }
1.645     raeburn  3284:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3285:                 my $src;
1.645     raeburn  3286:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3287:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3288:                 } else {
1.1164    raeburn  3289:                     if ($attr->{'src'} ne '') {
                   3290:                         $src = $attr->{'src'};
                   3291:                         &add_filetype($allfiles,$src,'src');
                   3292:                     }
                   3293:                 }
                   3294:                 my $text = $p->get_trimmed_text();
                   3295:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3296:                     my @swfargs = split(/,/,$1);
                   3297:                     foreach my $item (@swfargs) {
                   3298:                         $item =~ s/["']//g;
                   3299:                         $item =~ s/^\s+//;
                   3300:                         $item =~ s/\s+$//;
                   3301:                     }
                   3302:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3303:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3304:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3305:                         } else {
                   3306:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3307:                         }
                   3308:                     }
1.645     raeburn  3309:                 }
                   3310:             }
                   3311:             if (lc($tagname) eq 'link') {
                   3312:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3313:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3314:                 }
                   3315:             }
1.640     albertel 3316: 	    if (lc($tagname) eq 'object' ||
                   3317: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3318: 		foreach my $item (keys(%javafiles)) {
                   3319: 		    $javafiles{$item} = '';
                   3320: 		}
1.1164    raeburn  3321:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3322:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3323:                 }
1.640     albertel 3324: 	    }
                   3325: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3326: 		my $name = lc($attr->{'name'});
                   3327: 		foreach my $item (keys(%javafiles)) {
                   3328: 		    if ($name eq $item) {
                   3329: 			$javafiles{$item} = $attr->{'value'};
                   3330: 			last;
                   3331: 		    }
                   3332: 		}
1.1164    raeburn  3333:                 my $pathfrom;
1.640     albertel 3334: 		foreach my $item (keys(%mediafiles)) {
                   3335: 		    if ($name eq $item) {
1.1164    raeburn  3336:                         $pathfrom = $attr->{'value'};
                   3337:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3338: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3339: 			last;
                   3340: 		    }
                   3341: 		}
1.1164    raeburn  3342:                 if ($name eq 'flashvars') {
                   3343:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3344:                 }
                   3345:                 if ($pathfrom ne '') {
                   3346:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3347:                                          $pathfrom);
                   3348:                 }
1.640     albertel 3349: 	    }
                   3350: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3351: 		foreach my $item (keys(%javafiles)) {
                   3352: 		    if ($attr->{$item}) {
                   3353: 			$javafiles{$item} = $attr->{$item};
                   3354: 			last;
                   3355: 		    }
                   3356: 		}
                   3357: 		foreach my $item (keys(%mediafiles)) {
                   3358: 		    if ($attr->{$item}) {
                   3359: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3360: 			last;
                   3361: 		    }
                   3362: 		}
1.1164    raeburn  3363:                 if (lc($tagname) eq 'embed') {
                   3364:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3365:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3366:                                              $attr->{'src'});
                   3367:                     }
                   3368:                 }
1.640     albertel 3369: 	    }
1.1164    raeburn  3370:             if ($t->[4] =~ m{/>$}) {
                   3371:                 pop(@state);  
                   3372:             }
1.640     albertel 3373: 	} elsif ($t->[0] eq 'E') {
                   3374: 	    my ($tagname) = ($t->[1]);
                   3375: 	    if ($javafiles{'codebase'} ne '') {
                   3376: 		$javafiles{'codebase'} .= '/';
                   3377: 	    }  
                   3378: 	    if (lc($tagname) eq 'applet' ||
                   3379: 		lc($tagname) eq 'object' ||
                   3380: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3381: 		) {
                   3382: 		foreach my $item (keys(%javafiles)) {
                   3383: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3384: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3385: 			&add_filetype($allfiles,$file,$item);
                   3386: 		    }
                   3387: 		}
                   3388: 	    } 
                   3389: 	    pop @state;
                   3390: 	}
                   3391:     }
1.1164    raeburn  3392:     foreach my $id (sort(keys(%flashvars))) {
                   3393:         if ($shockwave{$id} ne '') {
                   3394:             my @pairs = split(/\&/,$flashvars{$id});
                   3395:             foreach my $pair (@pairs) {
                   3396:                 my ($key,$value) = split(/\=/,$pair);
                   3397:                 if ($key eq 'thumb') {
                   3398:                     &add_filetype($allfiles,$value,$key);
                   3399:                 } elsif ($key eq 'content') {
                   3400:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3401:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3402:                     if ($ext ne '') {
                   3403:                         &add_filetype($allfiles,$path.$value,$ext);
                   3404:                     }
                   3405:                 }
                   3406:             }
                   3407:         }
                   3408:     }
1.637     raeburn  3409:     return 'ok';
                   3410: }
                   3411: 
1.639     albertel 3412: sub add_filetype {
                   3413:     my ($allfiles,$file,$type)=@_;
                   3414:     if (exists($allfiles->{$file})) {
                   3415: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3416: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3417: 	}
                   3418:     } else {
                   3419: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3420:     }
                   3421: }
                   3422: 
1.1164    raeburn  3423: sub embedded_dependency {
                   3424:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3425:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3426:         if (($identifier ne '') &&
                   3427:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3428:             ($pathfrom ne '')) {
                   3429:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3430:             foreach my $dep (@{$related->{$identifier}}) {
                   3431:                 &add_filetype($allfiles,$path.$dep,'object');
                   3432:             }
                   3433:         }
                   3434:     }
                   3435:     return;
                   3436: }
                   3437: 
1.493     albertel 3438: sub removeuploadedurl {
1.984     neumanie 3439:     my ($url)=@_;	
                   3440:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3441:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3442: }
                   3443: 
                   3444: sub removeuserfile {
                   3445:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3446:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3447:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3448:     if ($result eq 'ok') {	
1.798     raeburn  3449:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3450:             my $metafile = $fname.'.meta';
                   3451:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3452: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3453:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3454:             my $sqlresult = 
1.823     albertel 3455:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3456:                                         'portfolio_metadata',$group,
                   3457:                                         'delete');
1.798     raeburn  3458:         }
                   3459:     }
                   3460:     return $result;
1.257     www      3461: }
1.15      www      3462: 
1.530     albertel 3463: sub mkdiruserfile {
                   3464:     my ($docuname,$docudom,$dir)=@_;
                   3465:     my $home=&homeserver($docuname,$docudom);
                   3466:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3467: }
                   3468: 
1.531     albertel 3469: sub renameuserfile {
                   3470:     my ($docuname,$docudom,$old,$new)=@_;
                   3471:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3472:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3473:                         &escape("$old").':'.&escape("$new"),$home);
                   3474:     if ($result eq 'ok') {
                   3475:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3476:             my $oldmeta = $old.'.meta';
                   3477:             my $newmeta = $new.'.meta';
                   3478:             my $metaresult = 
                   3479:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3480: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3481:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3482:             my $sqlresult = 
1.823     albertel 3483:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3484:                                         'portfolio_metadata',$group,
                   3485:                                         'delete');
1.798     raeburn  3486:         }
                   3487:     }
                   3488:     return $result;
1.531     albertel 3489: }
                   3490: 
1.14      www      3491: # ------------------------------------------------------------------------- Log
                   3492: 
                   3493: sub log {
                   3494:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3495:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3496: }
                   3497: 
                   3498: # ------------------------------------------------------------------ Course Log
1.352     www      3499: #
                   3500: # This routine flushes several buffers of non-mission-critical nature
                   3501: #
1.157     www      3502: 
                   3503: sub flushcourselogs {
1.352     www      3504:     &logthis('Flushing log buffers');
                   3505: #
                   3506: # course logs
                   3507: # This is a log of all transactions in a course, which can be used
                   3508: # for data mining purposes
                   3509: #
                   3510: # It also collects the courseid database, which lists last transaction
                   3511: # times and course titles for all courseids
                   3512: #
                   3513:     my %courseidbuffer=();
1.921     raeburn  3514:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3515:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3516: 		          &escape($courselogs{$crsid}),
                   3517: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3518: 	    delete $courselogs{$crsid};
                   3519:         } else {
                   3520:             &logthis('Failed to flush log buffer for '.$crsid);
                   3521:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3522:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3523:                         " exceeded maximum size, deleting.</font>");
                   3524:                delete $courselogs{$crsid};
                   3525:             }
1.352     www      3526:         }
1.920     raeburn  3527:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3528:             'description' => $coursedescrbuf{$crsid},
                   3529:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3530:             'type'        => $coursetypebuf{$crsid},
                   3531:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3532:         };
1.191     harris41 3533:     }
1.352     www      3534: #
                   3535: # Write course id database (reverse lookup) to homeserver of courses 
                   3536: # Is used in pickcourse
                   3537: #
1.840     albertel 3538:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3539:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3540:                                     $courseidbuffer{$crs_home},
                   3541:                                     $crs_home,'timeonly');
1.352     www      3542:     }
                   3543: #
                   3544: # File accesses
                   3545: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3546: #
1.449     matthew  3547:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3548:         if ($entry =~ /___count$/) {
                   3549:             my ($dom,$name);
1.807     albertel 3550:             ($dom,$name,undef)=
1.811     albertel 3551: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3552:             if (! defined($dom) || $dom eq '' || 
                   3553:                 ! defined($name) || $name eq '') {
1.620     albertel 3554:                 my $cid = $env{'request.course.id'};
                   3555:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3556:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3557:             }
1.450     matthew  3558:             my $value = $accesshash{$entry};
                   3559:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3560:             my %temphash=($url => $value);
1.449     matthew  3561:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3562:             if ($result eq 'ok') {
                   3563:                 delete $accesshash{$entry};
                   3564:             }
                   3565:         } else {
1.811     albertel 3566:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3567:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3568:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3569:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3570:                 delete $accesshash{$entry};
                   3571:             }
1.185     www      3572:         }
1.191     harris41 3573:     }
1.352     www      3574: #
                   3575: # Roles
                   3576: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3577: #
1.800     albertel 3578:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3579:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3580: 	    split(/\:/,$entry);
                   3581:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3582:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3583:                 $rudom,$runame) eq 'ok') {
                   3584: 	    delete $userrolehash{$entry};
                   3585:         }
                   3586:     }
1.662     raeburn  3587: #
                   3588: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3589: #
                   3590:     my %domrolebuffer = ();
1.1000    raeburn  3591:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3592:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3593:         if ($domrolebuffer{$rudom}) {
                   3594:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3595:                       '='.&escape($domainrolehash{$entry});
                   3596:         } else {
                   3597:             $domrolebuffer{$rudom}.=&escape($entry).
                   3598:                       '='.&escape($domainrolehash{$entry});
                   3599:         }
                   3600:         delete $domainrolehash{$entry};
                   3601:     }
                   3602:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3603: 	my %servers = &get_servers($dom,'library');
                   3604: 	foreach my $tryserver (keys(%servers)) {
                   3605: 	    unless (&reply('domroleput:'.$dom.':'.
                   3606: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3607: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3608: 	    }
1.662     raeburn  3609:         }
                   3610:     }
1.186     www      3611:     $dumpcount++;
1.157     www      3612: }
                   3613: 
                   3614: sub courselog {
                   3615:     my $what=shift;
1.158     www      3616:     $what=time.':'.$what;
1.620     albertel 3617:     unless ($env{'request.course.id'}) { return ''; }
                   3618:     $coursedombuf{$env{'request.course.id'}}=
                   3619:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3620:     $coursenumbuf{$env{'request.course.id'}}=
                   3621:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3622:     $coursehombuf{$env{'request.course.id'}}=
                   3623:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3624:     $coursedescrbuf{$env{'request.course.id'}}=
                   3625:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3626:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3627:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3628:     $courseownerbuf{$env{'request.course.id'}}=
                   3629:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3630:     $coursetypebuf{$env{'request.course.id'}}=
                   3631:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3632:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3633: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3634:     } else {
1.620     albertel 3635: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3636:     }
1.620     albertel 3637:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3638: 	&flushcourselogs();
                   3639:     }
1.158     www      3640: }
                   3641: 
                   3642: sub courseacclog {
                   3643:     my $fnsymb=shift;
1.620     albertel 3644:     unless ($env{'request.course.id'}) { return ''; }
                   3645:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3646:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3647:         $what.=':POST';
1.583     matthew  3648:         # FIXME: Probably ought to escape things....
1.800     albertel 3649: 	foreach my $key (keys(%env)) {
                   3650:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3651:                 my $formitem = $1;
                   3652:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3653:                     $what.=':'.$formitem.'='.$env{$key};
                   3654:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3655:                     $what.=':'.$formitem.'='.$env{$key};
                   3656:                 }
1.158     www      3657:             }
1.191     harris41 3658:         }
1.583     matthew  3659:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3660:         # FIXME: We should not be depending on a form parameter that someone
                   3661:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3662:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3663:             $what.= ':POST';
                   3664:             # FIXME: Probably ought to escape things....
                   3665:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3666:                                  'crsdiscuss') {
1.620     albertel 3667:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3668:             }
                   3669:         }
1.158     www      3670:     }
                   3671:     &courselog($what);
1.149     www      3672: }
                   3673: 
1.185     www      3674: sub countacc {
                   3675:     my $url=&declutter(shift);
1.458     matthew  3676:     return if (! defined($url) || $url eq '');
1.620     albertel 3677:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3678: #
                   3679: # Mark that this url was used in this course
                   3680: #
1.620     albertel 3681:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3682: #
                   3683: # Increase the access count for this resource in this child process
                   3684: #
1.281     www      3685:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3686:     $accesshash{$key}++;
1.185     www      3687: }
1.349     www      3688: 
1.361     www      3689: sub linklog {
                   3690:     my ($from,$to)=@_;
                   3691:     $from=&declutter($from);
                   3692:     $to=&declutter($to);
                   3693:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3694:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3695: }
1.1160    www      3696: 
                   3697: sub statslog {
                   3698:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3699:     if ($users<2) { return; }
                   3700:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3701:             'course'       => $env{'request.course.id'},
                   3702:             'sections'     => '"all"',
                   3703:             'num_students' => $users,
                   3704:             'part'         => $part,
                   3705:             'symb'         => $symb,
                   3706:             'mean_tries'   => $av_attempts,
                   3707:             'deg_of_diff'  => $degdiff});
                   3708:     foreach my $key (keys(%dynstore)) {
                   3709:         $accesshash{$key}=$dynstore{$key};
                   3710:     }
                   3711: }
1.361     www      3712:   
1.349     www      3713: sub userrolelog {
                   3714:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3715:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3716:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3717:        $userrolehash
                   3718:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3719:                     =$tend.':'.$tstart;
1.662     raeburn  3720:     }
1.1169    droeschl 3721:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3722:        $userrolehash
                   3723:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3724:                     =$tend.':'.$tstart;
                   3725:     }
1.1169    droeschl 3726:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3727:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3728:        $domainrolehash
                   3729:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3730:                     = $tend.':'.$tstart;
                   3731:     }
1.351     www      3732: }
                   3733: 
1.957     raeburn  3734: sub courserolelog {
                   3735:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3736:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3737:         my $cdom = $1;
                   3738:         my $cnum = $2;
                   3739:         my $sec = $3;
                   3740:         my $namespace = 'rolelog';
                   3741:         my %storehash = (
                   3742:                            role    => $trole,
                   3743:                            start   => $tstart,
                   3744:                            end     => $tend,
                   3745:                            selfenroll => $selfenroll,
                   3746:                            context    => $context,
                   3747:                         );
                   3748:         if ($trole eq 'gr') {
                   3749:             $namespace = 'groupslog';
                   3750:             $storehash{'group'} = $sec;
                   3751:         } else {
                   3752:             $storehash{'section'} = $sec;
                   3753:         }
1.1188    raeburn  3754:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3755:                    $domain,$cnum,$cdom);
1.1184    raeburn  3756:         if (($trole ne 'st') || ($sec ne '')) {
                   3757:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3758:         }
                   3759:     }
                   3760:     return;
                   3761: }
                   3762: 
1.1184    raeburn  3763: sub domainrolelog {
                   3764:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3765:     if ($area =~ m{^/($match_domain)/$}) {
                   3766:         my $cdom = $1;
                   3767:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3768:         my $namespace = 'rolelog';
                   3769:         my %storehash = (
                   3770:                            role    => $trole,
                   3771:                            start   => $tstart,
                   3772:                            end     => $tend,
                   3773:                            context => $context,
                   3774:                         );
1.1188    raeburn  3775:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3776:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3777:     }
                   3778:     return;
                   3779: 
                   3780: }
                   3781: 
                   3782: sub coauthorrolelog {
                   3783:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3784:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3785:         my $audom = $1;
                   3786:         my $auname = $2;
                   3787:         my $namespace = 'rolelog';
                   3788:         my %storehash = (
                   3789:                            role    => $trole,
                   3790:                            start   => $tstart,
                   3791:                            end     => $tend,
                   3792:                            context => $context,
                   3793:                         );
1.1188    raeburn  3794:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3795:                    $domain,$auname,$audom);
1.1184    raeburn  3796:     }
                   3797:     return;
                   3798: }
                   3799: 
1.351     www      3800: sub get_course_adv_roles {
1.948     raeburn  3801:     my ($cid,$codes) = @_;
1.620     albertel 3802:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3803:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3804:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3805:     my %nothide=();
1.800     albertel 3806:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3807:         if ($user !~ /:/) {
                   3808: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3809:         } else {
                   3810:             $nothide{$user}=1;
                   3811:         }
1.470     www      3812:     }
1.351     www      3813:     my %returnhash=();
                   3814:     my %dumphash=
                   3815:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3816:     my $now=time;
1.997     raeburn  3817:     my %privileged;
1.1000    raeburn  3818:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3819: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3820:         if (($tstart) && ($tstart<0)) { next; }
                   3821:         if (($tend) && ($tend<$now)) { next; }
                   3822:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3823:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3824: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3825:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3826:             my %dompersonnel =
1.998     raeburn  3827:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3828:             $privileged{$domain} = {};
                   3829:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3830:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3831:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3832:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3833:                         $privileged{$udom}{$uname} = 1;
                   3834:                     }
                   3835:                 }
                   3836:             }
                   3837:         }
                   3838:         if ((exists($privileged{$domain}{$username})) && 
                   3839:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3840: 	if ($role eq 'cr') { next; }
1.948     raeburn  3841:         if ($codes) {
                   3842:             if ($section) { $role .= ':'.$section; }
                   3843:             if ($returnhash{$role}) {
                   3844:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3845:             } else {
                   3846:                 $returnhash{$role}=$username.':'.$domain;
                   3847:             }
1.351     www      3848:         } else {
1.988     raeburn  3849:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3850:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3851:             if ($returnhash{$key}) {
                   3852: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3853:             } else {
                   3854:                 $returnhash{$key}=$username.':'.$domain;
                   3855:             }
1.351     www      3856:         }
1.948     raeburn  3857:     }
1.400     www      3858:     return %returnhash;
                   3859: }
                   3860: 
                   3861: sub get_my_roles {
1.937     raeburn  3862:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3863:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3864:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3865:     my (%dumphash,%nothide);
1.1086    raeburn  3866:     if ($context eq 'userroles') {
1.1166    raeburn  3867:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3868:     } else {
                   3869:         %dumphash=
1.400     www      3870:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3871:         if ($hidepriv) {
                   3872:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3873:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3874:                 if ($user !~ /:/) {
                   3875:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3876:                 } else {
                   3877:                     $nothide{$user} = 1;
                   3878:                 }
                   3879:             }
                   3880:         }
1.858     raeburn  3881:     }
1.400     www      3882:     my %returnhash=();
                   3883:     my $now=time;
1.999     raeburn  3884:     my %privileged;
1.800     albertel 3885:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3886:         my ($role,$tend,$tstart);
                   3887:         if ($context eq 'userroles') {
1.1149    raeburn  3888:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3889: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3890:         } else {
                   3891:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3892:         }
1.400     www      3893:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3894:         my $status = 'active';
1.939     raeburn  3895:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3896:             $status = 'previous';
                   3897:         } 
                   3898:         if (($tstart) && ($now<$tstart)) {
                   3899:             $status = 'future';
                   3900:         }
                   3901:         if (ref($types) eq 'ARRAY') {
                   3902:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3903:                 next;
                   3904:             } 
                   3905:         } else {
                   3906:             if ($status ne 'active') {
                   3907:                 next;
                   3908:             }
                   3909:         }
1.867     raeburn  3910:         my ($rolecode,$username,$domain,$section,$area);
                   3911:         if ($context eq 'userroles') {
1.1186    raeburn  3912:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3913:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3914:         } else {
                   3915:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3916:         }
1.832     raeburn  3917:         if (ref($roledoms) eq 'ARRAY') {
                   3918:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3919:                 next;
                   3920:             }
                   3921:         }
                   3922:         if (ref($roles) eq 'ARRAY') {
                   3923:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3924:                 if ($role =~ /^cr\//) {
                   3925:                     if (!grep(/^cr$/,@{$roles})) {
                   3926:                         next;
                   3927:                     }
1.1104    raeburn  3928:                 } elsif ($role =~ /^gr\//) {
                   3929:                     if (!grep(/^gr$/,@{$roles})) {
                   3930:                         next;
                   3931:                     }
1.922     raeburn  3932:                 } else {
                   3933:                     next;
                   3934:                 }
1.832     raeburn  3935:             }
1.867     raeburn  3936:         }
1.937     raeburn  3937:         if ($hidepriv) {
1.999     raeburn  3938:             if ($context eq 'userroles') {
                   3939:                 if ((&privileged($username,$domain)) &&
                   3940:                     (!$nothide{$username.':'.$domain})) {
                   3941:                     next;
                   3942:                 }
                   3943:             } else {
                   3944:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3945:                     my %dompersonnel =
                   3946:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3947:                     $privileged{$domain} = {};
                   3948:                     if (keys(%dompersonnel)) {
                   3949:                         foreach my $server (keys(%dompersonnel)) {
                   3950:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3951:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3952:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3953:                                     $privileged{$udom}{$uname} = $trole;
                   3954:                                 }
                   3955:                             }
                   3956:                         }
                   3957:                     }
                   3958:                 }
                   3959:                 if (exists($privileged{$domain}{$username})) {
                   3960:                     if (!$nothide{$username.':'.$domain}) {
                   3961:                         next;
                   3962:                     }
                   3963:                 }
1.937     raeburn  3964:             }
                   3965:         }
1.933     raeburn  3966:         if ($withsec) {
                   3967:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3968:                 $tstart.':'.$tend;
                   3969:         } else {
                   3970:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3971:         }
1.832     raeburn  3972:     }
1.373     www      3973:     return %returnhash;
1.399     www      3974: }
                   3975: 
                   3976: # ----------------------------------------------------- Frontpage Announcements
                   3977: #
                   3978: #
                   3979: 
                   3980: sub postannounce {
                   3981:     my ($server,$text)=@_;
1.844     albertel 3982:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3983:     unless ($text=~/\w/) { $text=''; }
                   3984:     return &reply('setannounce:'.&escape($text),$server);
                   3985: }
                   3986: 
                   3987: sub getannounce {
1.448     albertel 3988: 
                   3989:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3990: 	my $announcement='';
1.800     albertel 3991: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3992: 	close($fh);
1.399     www      3993: 	if ($announcement=~/\w/) { 
                   3994: 	    return 
                   3995:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3996:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3997: 	} else {
                   3998: 	    return '';
                   3999: 	}
                   4000:     } else {
                   4001: 	return '';
                   4002:     }
1.351     www      4003: }
1.353     www      4004: 
                   4005: # ---------------------------------------------------------- Course ID routines
                   4006: # Deal with domain's nohist_courseid.db files
                   4007: #
                   4008: 
                   4009: sub courseidput {
1.921     raeburn  4010:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4011:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4012:     my $outcome;
                   4013:     if ($caller eq 'timeonly') {
                   4014:         my $cids = '';
                   4015:         foreach my $item (keys(%$storehash)) {
                   4016:             $cids.=&escape($item).'&';
                   4017:         }
                   4018:         $cids=~s/\&$//;
                   4019:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4020:                           $coursehome);       
                   4021:     } else {
                   4022:         my $items = '';
                   4023:         foreach my $item (keys(%$storehash)) {
                   4024:             $items.= &escape($item).'='.
                   4025:                      &freeze_escape($$storehash{$item}).'&';
                   4026:         }
                   4027:         $items=~s/\&$//;
                   4028:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4029:                           $coursehome);
1.918     raeburn  4030:     }
                   4031:     if ($outcome eq 'unknown_cmd') {
                   4032:         my $what;
                   4033:         foreach my $cid (keys(%$storehash)) {
                   4034:             $what .= &escape($cid).'=';
1.921     raeburn  4035:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4036:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4037:             }
                   4038:             $what =~ s/\:$/&/;
                   4039:         }
                   4040:         $what =~ s/\&$//;  
                   4041:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4042:     } else {
                   4043:         return $outcome;
                   4044:     }
1.353     www      4045: }
                   4046: 
                   4047: sub courseiddump {
1.921     raeburn  4048:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4049:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4050:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4051:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4052:     my $as_hash = 1;
                   4053:     my %returnhash;
                   4054:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4055:     my %libserv = &all_library();
                   4056:     foreach my $tryserver (keys(%libserv)) {
                   4057:         if ( (  $hostidflag == 1 
                   4058: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4059: 	     || (!defined($hostidflag)) ) {
                   4060: 
1.918     raeburn  4061: 	    if (($domfilter eq '') ||
                   4062: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4063:                 my $rep;
                   4064:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4065:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4066:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4067:                                 &escape($descfilter), &escape($instcodefilter), 
                   4068:                                 &escape($ownerfilter), &escape($coursefilter),
                   4069:                                 &escape($typefilter), &escape($regexp_ok), 
                   4070:                                 $as_hash, &escape($selfenrollonly), 
                   4071:                                 &escape($catfilter), $showhidden, $caller, 
                   4072:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4073:                                 &escape($createdbefore), &escape($createdafter), 
                   4074:                                 &escape($creationcontext), $domcloner)));
                   4075:                 } else {
                   4076:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4077:                              $sincefilter.':'.&escape($descfilter).':'.
                   4078:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4079:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4080:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4081:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4082:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4083:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4084:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4085:                              &escape($creationcontext).':'.$domcloner,
                   4086:                              $tryserver);
                   4087:                 }
                   4088:                      
1.918     raeburn  4089:                 my @pairs=split(/\&/,$rep);
                   4090:                 foreach my $item (@pairs) {
                   4091:                     my ($key,$value)=split(/\=/,$item,2);
                   4092:                     $key = &unescape($key);
                   4093:                     next if ($key =~ /^error: 2 /);
                   4094:                     my $result = &thaw_unescape($value);
                   4095:                     if (ref($result) eq 'HASH') {
                   4096:                         $returnhash{$key}=$result;
                   4097:                     } else {
1.921     raeburn  4098:                         my @responses = split(/:/,$value);
                   4099:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4100:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4101:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4102:                         }
1.1008    raeburn  4103:                     }
1.353     www      4104:                 }
                   4105:             }
                   4106:         }
                   4107:     }
                   4108:     return %returnhash;
                   4109: }
                   4110: 
1.1055    raeburn  4111: sub courselastaccess {
                   4112:     my ($cdom,$cnum,$hostidref) = @_;
                   4113:     my %returnhash;
                   4114:     if ($cdom && $cnum) {
                   4115:         my $chome = &homeserver($cnum,$cdom);
                   4116:         if ($chome ne 'no_host') {
                   4117:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4118:             &extract_lastaccess(\%returnhash,$rep);
                   4119:         }
                   4120:     } else {
                   4121:         if (!$cdom) { $cdom=''; }
                   4122:         my %libserv = &all_library();
                   4123:         foreach my $tryserver (keys(%libserv)) {
                   4124:             if (ref($hostidref) eq 'ARRAY') {
                   4125:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4126:             } 
                   4127:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4128:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4129:                 &extract_lastaccess(\%returnhash,$rep);
                   4130:             }
                   4131:         }
                   4132:     }
                   4133:     return %returnhash;
                   4134: }
                   4135: 
                   4136: sub extract_lastaccess {
                   4137:     my ($returnhash,$rep) = @_;
                   4138:     if (ref($returnhash) eq 'HASH') {
                   4139:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4140:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4141:                  $rep eq '') {
                   4142:             my @pairs=split(/\&/,$rep);
                   4143:             foreach my $item (@pairs) {
                   4144:                 my ($key,$value)=split(/\=/,$item,2);
                   4145:                 $key = &unescape($key);
                   4146:                 next if ($key =~ /^error: 2 /);
                   4147:                 $returnhash->{$key} = &thaw_unescape($value);
                   4148:             }
                   4149:         }
                   4150:     }
                   4151:     return;
                   4152: }
                   4153: 
1.658     raeburn  4154: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4155: 
                   4156: sub dcmailput {
1.685     raeburn  4157:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4158:     my $status = &Apache::lonnet::critical(
1.740     www      4159:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4160:        &escape($message),$server);
1.662     raeburn  4161:     return $status;
                   4162: }
                   4163: 
1.658     raeburn  4164: sub dcmaildump {
                   4165:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4166:     my %returnhash=();
1.846     albertel 4167: 
                   4168:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4169:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4170:                                                          &escape($enddate).':';
                   4171: 	my @esc_senders=map { &escape($_)} @$senders;
                   4172: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4173: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4174:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4175:             if (($key) && ($value)) {
                   4176:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4177:             }
                   4178:         }
                   4179:     }
                   4180:     return %returnhash;
                   4181: }
1.662     raeburn  4182: # ---------------------------------------------------------- Domain roles
                   4183: 
                   4184: sub get_domain_roles {
                   4185:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4186:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4187:         $startdate = '.';
                   4188:     }
1.1018    raeburn  4189:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4190:         $enddate = '.';
                   4191:     }
1.922     raeburn  4192:     my $rolelist;
                   4193:     if (ref($roles) eq 'ARRAY') {
                   4194:         $rolelist = join(':',@{$roles});
                   4195:     }
1.662     raeburn  4196:     my %personnel = ();
1.841     albertel 4197: 
                   4198:     my %servers = &get_servers($dom,'library');
                   4199:     foreach my $tryserver (keys(%servers)) {
                   4200: 	%{$personnel{$tryserver}}=();
                   4201: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4202: 					    &escape($startdate).':'.
                   4203: 					    &escape($enddate).':'.
                   4204: 					    &escape($rolelist), $tryserver))) {
                   4205: 	    my ($key,$value) = split(/\=/,$line,2);
                   4206: 	    if (($key) && ($value)) {
                   4207: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4208: 	    }
                   4209: 	}
1.662     raeburn  4210:     }
                   4211:     return %personnel;
                   4212: }
1.658     raeburn  4213: 
1.1057    www      4214: # ----------------------------------------------------------- Interval timing 
1.149     www      4215: 
1.1153    www      4216: {
                   4217: # Caches needed for speedup of navmaps
                   4218: # We don't want to cache this for very long at all (5 seconds at most)
                   4219: # 
                   4220: # The user for whom we cache
                   4221: my $cachedkey='';
                   4222: # The cached times for this user
                   4223: my %cachedtimes=();
                   4224: # When this was last done
                   4225: my $cachedtime=();
                   4226: 
                   4227: sub load_all_first_access {
1.1154    raeburn  4228:     my ($uname,$udom)=@_;
1.1156    www      4229:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4230:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4231:         return;
                   4232:     }
                   4233:     $cachedtime=time;
                   4234:     $cachedkey=$uname.':'.$udom;
                   4235:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4236: }
                   4237: 
1.504     albertel 4238: sub get_first_access {
1.1162    raeburn  4239:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4240:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4241:     if ($argsymb) { $symb=$argsymb; }
                   4242:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4243:     if ($argmap) { $map = $argmap; }
1.926     albertel 4244:     if ($type eq 'course') {
                   4245: 	$res='course';
                   4246:     } elsif ($type eq 'map') {
1.588     albertel 4247: 	$res=&symbread($map);
                   4248:     } else {
                   4249: 	$res=$symb;
                   4250:     }
1.1153    www      4251:     &load_all_first_access($uname,$udom);
                   4252:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4253: }
                   4254: 
                   4255: sub set_first_access {
1.1162    raeburn  4256:     my ($type,$interval)=@_;
1.790     albertel 4257:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4258:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4259:     if ($type eq 'course') {
                   4260: 	$res='course';
                   4261:     } elsif ($type eq 'map') {
1.588     albertel 4262: 	$res=&symbread($map);
                   4263:     } else {
                   4264: 	$res=$symb;
                   4265:     }
1.1153    www      4266:     $cachedkey='';
1.1162    raeburn  4267:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4268:     if (!$firstaccess) {
1.1162    raeburn  4269:         my $start = time;
                   4270: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4271:                           $udom,$uname);
                   4272:         if ($putres eq 'ok') {
                   4273:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4274:                  $udom,$uname); 
                   4275:             &appenv(
                   4276:                      {
                   4277:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4278:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4279:                      }
                   4280:                   );
                   4281:         }
                   4282:         return $putres;
1.505     albertel 4283:     }
                   4284:     return 'already_set';
1.504     albertel 4285: }
1.1153    www      4286: }
1.110     www      4287: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4288: 
                   4289: sub expirespread {
                   4290:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4291:     my $cid=$env{'request.course.id'}; 
1.110     www      4292:     if ($cid) {
                   4293:        my $now=time;
                   4294:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4295:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4296:                             $env{'course.'.$cid.'.num'}.
1.110     www      4297: 	        	    ':nohist_expirationdates:'.
                   4298:                             &escape($key).'='.$now,
1.620     albertel 4299:                             $env{'course.'.$cid.'.home'})
1.110     www      4300:     }
                   4301:     return 'ok';
1.14      www      4302: }
                   4303: 
1.109     www      4304: # ----------------------------------------------------- Devalidate Spreadsheets
                   4305: 
                   4306: sub devalidate {
1.325     www      4307:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4308:     my $cid=$env{'request.course.id'}; 
1.109     www      4309:     if ($cid) {
1.391     matthew  4310:         # delete the stored spreadsheets for
                   4311:         # - the student level sheet of this user in course's homespace
                   4312:         # - the assessment level sheet for this resource 
                   4313:         #   for this user in user's homespace
1.553     albertel 4314: 	# - current conditional state info
1.325     www      4315: 	my $key=$uname.':'.$udom.':';
1.109     www      4316:         my $status=
1.299     matthew  4317: 	    &del('nohist_calculatedsheets',
1.391     matthew  4318: 		 [$key.'studentcalc:'],
1.620     albertel 4319: 		 $env{'course.'.$cid.'.domain'},
                   4320: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4321: 		.' '.
                   4322: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4323: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4324:         unless ($status eq 'ok ok') {
                   4325:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4326:                     $uname.' at '.$udom.' for '.
1.109     www      4327: 		    $symb.': '.$status);
1.133     albertel 4328:         }
1.553     albertel 4329: 	&delenv('user.state.'.$cid);
1.109     www      4330:     }
                   4331: }
                   4332: 
1.265     albertel 4333: sub get_scalar {
                   4334:     my ($string,$end) = @_;
                   4335:     my $value;
                   4336:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4337: 	$value = $1;
                   4338:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4339: 	$value = $1;
                   4340:     }
                   4341:     return &unescape($value);
                   4342: }
                   4343: 
                   4344: sub array2str {
                   4345:   my (@array) = @_;
                   4346:   my $result=&arrayref2str(\@array);
                   4347:   $result=~s/^__ARRAY_REF__//;
                   4348:   $result=~s/__END_ARRAY_REF__$//;
                   4349:   return $result;
                   4350: }
                   4351: 
1.204     albertel 4352: sub arrayref2str {
                   4353:   my ($arrayref) = @_;
1.265     albertel 4354:   my $result='__ARRAY_REF__';
1.204     albertel 4355:   foreach my $elem (@$arrayref) {
1.265     albertel 4356:     if(ref($elem) eq 'ARRAY') {
                   4357:       $result.=&arrayref2str($elem).'&';
                   4358:     } elsif(ref($elem) eq 'HASH') {
                   4359:       $result.=&hashref2str($elem).'&';
                   4360:     } elsif(ref($elem)) {
                   4361:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4362:     } else {
                   4363:       $result.=&escape($elem).'&';
                   4364:     }
                   4365:   }
                   4366:   $result=~s/\&$//;
1.265     albertel 4367:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4368:   return $result;
                   4369: }
                   4370: 
1.168     albertel 4371: sub hash2str {
1.204     albertel 4372:   my (%hash) = @_;
                   4373:   my $result=&hashref2str(\%hash);
1.265     albertel 4374:   $result=~s/^__HASH_REF__//;
                   4375:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4376:   return $result;
                   4377: }
                   4378: 
                   4379: sub hashref2str {
                   4380:   my ($hashref)=@_;
1.265     albertel 4381:   my $result='__HASH_REF__';
1.800     albertel 4382:   foreach my $key (sort(keys(%$hashref))) {
                   4383:     if (ref($key) eq 'ARRAY') {
                   4384:       $result.=&arrayref2str($key).'=';
                   4385:     } elsif (ref($key) eq 'HASH') {
                   4386:       $result.=&hashref2str($key).'=';
                   4387:     } elsif (ref($key)) {
1.265     albertel 4388:       $result.='=';
1.800     albertel 4389:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4390:     } else {
1.1132    raeburn  4391: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4392:     }
                   4393: 
1.800     albertel 4394:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4395:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4396:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4397:       $result.=&hashref2str($hashref->{$key}).'&';
                   4398:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4399:        $result.='&';
1.800     albertel 4400:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4401:     } else {
1.800     albertel 4402:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4403:     }
                   4404:   }
1.168     albertel 4405:   $result=~s/\&$//;
1.265     albertel 4406:   $result .= '__END_HASH_REF__';
1.168     albertel 4407:   return $result;
                   4408: }
                   4409: 
                   4410: sub str2hash {
1.265     albertel 4411:     my ($string)=@_;
                   4412:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4413:     return %$hash;
                   4414: }
                   4415: 
                   4416: sub str2hashref {
1.168     albertel 4417:   my ($string) = @_;
1.265     albertel 4418: 
                   4419:   my %hash;
                   4420: 
                   4421:   if($string !~ /^__HASH_REF__/) {
                   4422:       if (! ($string eq '' || !defined($string))) {
                   4423: 	  $hash{'error'}='Not hash reference';
                   4424:       }
                   4425:       return (\%hash, $string);
                   4426:   }
                   4427: 
                   4428:   $string =~ s/^__HASH_REF__//;
                   4429: 
                   4430:   while($string !~ /^__END_HASH_REF__/) {
                   4431:       #key
                   4432:       my $key='';
                   4433:       if($string =~ /^__HASH_REF__/) {
                   4434:           ($key, $string)=&str2hashref($string);
                   4435:           if(defined($key->{'error'})) {
                   4436:               $hash{'error'}='Bad data';
                   4437:               return (\%hash, $string);
                   4438:           }
                   4439:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4440:           ($key, $string)=&str2arrayref($string);
                   4441:           if($key->[0] eq 'Array reference error') {
                   4442:               $hash{'error'}='Bad data';
                   4443:               return (\%hash, $string);
                   4444:           }
                   4445:       } else {
                   4446:           $string =~ s/^(.*?)=//;
1.267     albertel 4447: 	  $key=&unescape($1);
1.265     albertel 4448:       }
                   4449:       $string =~ s/^=//;
                   4450: 
                   4451:       #value
                   4452:       my $value='';
                   4453:       if($string =~ /^__HASH_REF__/) {
                   4454:           ($value, $string)=&str2hashref($string);
                   4455:           if(defined($value->{'error'})) {
                   4456:               $hash{'error'}='Bad data';
                   4457:               return (\%hash, $string);
                   4458:           }
                   4459:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4460:           ($value, $string)=&str2arrayref($string);
                   4461:           if($value->[0] eq 'Array reference error') {
                   4462:               $hash{'error'}='Bad data';
                   4463:               return (\%hash, $string);
                   4464:           }
                   4465:       } else {
                   4466: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4467:       }
                   4468:       $string =~ s/^&//;
                   4469: 
                   4470:       $hash{$key}=$value;
1.204     albertel 4471:   }
1.265     albertel 4472: 
                   4473:   $string =~ s/^__END_HASH_REF__//;
                   4474: 
                   4475:   return (\%hash, $string);
1.204     albertel 4476: }
                   4477: 
                   4478: sub str2array {
1.265     albertel 4479:     my ($string)=@_;
                   4480:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4481:     return @$array;
                   4482: }
                   4483: 
                   4484: sub str2arrayref {
1.204     albertel 4485:   my ($string) = @_;
1.265     albertel 4486:   my @array;
                   4487: 
                   4488:   if($string !~ /^__ARRAY_REF__/) {
                   4489:       if (! ($string eq '' || !defined($string))) {
                   4490: 	  $array[0]='Array reference error';
                   4491:       }
                   4492:       return (\@array, $string);
                   4493:   }
                   4494: 
                   4495:   $string =~ s/^__ARRAY_REF__//;
                   4496: 
                   4497:   while($string !~ /^__END_ARRAY_REF__/) {
                   4498:       my $value='';
                   4499:       if($string =~ /^__HASH_REF__/) {
                   4500:           ($value, $string)=&str2hashref($string);
                   4501:           if(defined($value->{'error'})) {
                   4502:               $array[0] ='Array reference error';
                   4503:               return (\@array, $string);
                   4504:           }
                   4505:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4506:           ($value, $string)=&str2arrayref($string);
                   4507:           if($value->[0] eq 'Array reference error') {
                   4508:               $array[0] ='Array reference error';
                   4509:               return (\@array, $string);
                   4510:           }
                   4511:       } else {
                   4512: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4513:       }
                   4514:       $string =~ s/^&//;
                   4515: 
                   4516:       push(@array, $value);
1.191     harris41 4517:   }
1.265     albertel 4518: 
                   4519:   $string =~ s/^__END_ARRAY_REF__//;
                   4520: 
                   4521:   return (\@array, $string);
1.168     albertel 4522: }
                   4523: 
1.167     albertel 4524: # -------------------------------------------------------------------Temp Store
                   4525: 
1.168     albertel 4526: sub tmpreset {
                   4527:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4528:   if (!$symb) {
                   4529:     $symb=&symbread();
1.620     albertel 4530:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4531:   }
                   4532:   $symb=escape($symb);
                   4533: 
1.620     albertel 4534:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4535:   $namespace=~s/\//\_/g;
                   4536:   $namespace=~s/\W//g;
                   4537: 
1.620     albertel 4538:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4539:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4540:   if ($domain eq 'public' && $stuname eq 'public') {
                   4541:       $stuname=$ENV{'REMOTE_ADDR'};
                   4542:   }
1.1117    foxr     4543:   my $path=LONCAPA::tempdir();
1.168     albertel 4544:   my %hash;
                   4545:   if (tie(%hash,'GDBM_File',
                   4546: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4547: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4548:     foreach my $key (keys(%hash)) {
1.180     albertel 4549:       if ($key=~ /:$symb/) {
1.168     albertel 4550: 	delete($hash{$key});
                   4551:       }
                   4552:     }
                   4553:   }
                   4554: }
                   4555: 
1.167     albertel 4556: sub tmpstore {
1.168     albertel 4557:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4558: 
                   4559:   if (!$symb) {
                   4560:     $symb=&symbread();
1.620     albertel 4561:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4562:   }
                   4563:   $symb=escape($symb);
                   4564: 
                   4565:   if (!$namespace) {
                   4566:     # I don't think we would ever want to store this for a course.
                   4567:     # it seems this will only be used if we don't have a course.
1.620     albertel 4568:     #$namespace=$env{'request.course.id'};
1.168     albertel 4569:     #if (!$namespace) {
1.620     albertel 4570:       $namespace=$env{'request.state'};
1.168     albertel 4571:     #}
                   4572:   }
                   4573:   $namespace=~s/\//\_/g;
                   4574:   $namespace=~s/\W//g;
1.620     albertel 4575:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4576:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4577:   if ($domain eq 'public' && $stuname eq 'public') {
                   4578:       $stuname=$ENV{'REMOTE_ADDR'};
                   4579:   }
1.168     albertel 4580:   my $now=time;
                   4581:   my %hash;
1.1117    foxr     4582:   my $path=LONCAPA::tempdir();
1.168     albertel 4583:   if (tie(%hash,'GDBM_File',
                   4584: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4585: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4586:     $hash{"version:$symb"}++;
                   4587:     my $version=$hash{"version:$symb"};
                   4588:     my $allkeys=''; 
                   4589:     foreach my $key (keys(%$storehash)) {
                   4590:       $allkeys.=$key.':';
1.591     albertel 4591:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4592:     }
                   4593:     $hash{"$version:$symb:timestamp"}=$now;
                   4594:     $allkeys.='timestamp';
                   4595:     $hash{"$version:keys:$symb"}=$allkeys;
                   4596:     if (untie(%hash)) {
                   4597:       return 'ok';
                   4598:     } else {
                   4599:       return "error:$!";
                   4600:     }
                   4601:   } else {
                   4602:     return "error:$!";
                   4603:   }
                   4604: }
1.167     albertel 4605: 
1.168     albertel 4606: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4607: 
1.168     albertel 4608: sub tmprestore {
                   4609:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4610: 
1.168     albertel 4611:   if (!$symb) {
                   4612:     $symb=&symbread();
1.620     albertel 4613:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4614:   }
                   4615:   $symb=escape($symb);
                   4616: 
1.620     albertel 4617:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4618: 
1.620     albertel 4619:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4620:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4621:   if ($domain eq 'public' && $stuname eq 'public') {
                   4622:       $stuname=$ENV{'REMOTE_ADDR'};
                   4623:   }
1.168     albertel 4624:   my %returnhash;
                   4625:   $namespace=~s/\//\_/g;
                   4626:   $namespace=~s/\W//g;
                   4627:   my %hash;
1.1117    foxr     4628:   my $path=LONCAPA::tempdir();
1.168     albertel 4629:   if (tie(%hash,'GDBM_File',
                   4630: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4631: 	  &GDBM_READER(),0640)) {
1.168     albertel 4632:     my $version=$hash{"version:$symb"};
                   4633:     $returnhash{'version'}=$version;
                   4634:     my $scope;
                   4635:     for ($scope=1;$scope<=$version;$scope++) {
                   4636:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4637:       my @keys=split(/:/,$vkeys);
                   4638:       my $key;
                   4639:       $returnhash{"$scope:keys"}=$vkeys;
                   4640:       foreach $key (@keys) {
1.591     albertel 4641: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4642: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4643:       }
                   4644:     }
1.168     albertel 4645:     if (!(untie(%hash))) {
                   4646:       return "error:$!";
                   4647:     }
                   4648:   } else {
                   4649:     return "error:$!";
                   4650:   }
                   4651:   return %returnhash;
1.167     albertel 4652: }
                   4653: 
1.9       www      4654: # ----------------------------------------------------------------------- Store
                   4655: 
                   4656: sub store {
1.124     www      4657:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4658:     my $home='';
                   4659: 
1.168     albertel 4660:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4661: 
1.213     www      4662:     $symb=&symbclean($symb);
1.122     albertel 4663:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4664: 
1.620     albertel 4665:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4666:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4667: 
                   4668:     &devalidate($symb,$stuname,$domain);
1.109     www      4669: 
                   4670:     $symb=escape($symb);
1.187     www      4671:     if (!$namespace) { 
1.620     albertel 4672:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4673:           return ''; 
                   4674:        } 
                   4675:     }
1.620     albertel 4676:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4677: 
                   4678:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4679:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4680: 
1.12      www      4681:     my $namevalue='';
1.800     albertel 4682:     foreach my $key (keys(%$storehash)) {
                   4683:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4684:     }
1.12      www      4685:     $namevalue=~s/\&$//;
1.187     www      4686:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4687:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4688: }
                   4689: 
1.47      www      4690: # -------------------------------------------------------------- Critical Store
                   4691: 
                   4692: sub cstore {
1.124     www      4693:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4694:     my $home='';
                   4695: 
1.168     albertel 4696:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4697: 
1.213     www      4698:     $symb=&symbclean($symb);
1.122     albertel 4699:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4700: 
1.620     albertel 4701:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4702:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4703: 
                   4704:     &devalidate($symb,$stuname,$domain);
1.109     www      4705: 
                   4706:     $symb=escape($symb);
1.187     www      4707:     if (!$namespace) { 
1.620     albertel 4708:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4709:           return ''; 
                   4710:        } 
                   4711:     }
1.620     albertel 4712:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4713: 
                   4714:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4715:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4716: 
1.47      www      4717:     my $namevalue='';
1.800     albertel 4718:     foreach my $key (keys(%$storehash)) {
                   4719:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4720:     }
1.47      www      4721:     $namevalue=~s/\&$//;
1.187     www      4722:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4723:     return critical
                   4724:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4725: }
                   4726: 
1.9       www      4727: # --------------------------------------------------------------------- Restore
                   4728: 
                   4729: sub restore {
1.124     www      4730:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4731:     my $home='';
                   4732: 
1.168     albertel 4733:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4734: 
1.122     albertel 4735:     if (!$symb) {
                   4736:       unless ($symb=escape(&symbread())) { return ''; }
                   4737:     } else {
1.213     www      4738:       $symb=&escape(&symbclean($symb));
1.122     albertel 4739:     }
1.188     www      4740:     if (!$namespace) { 
1.620     albertel 4741:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4742:           return ''; 
                   4743:        } 
                   4744:     }
1.620     albertel 4745:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4746:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4747:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4748:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4749: 
1.12      www      4750:     my %returnhash=();
1.800     albertel 4751:     foreach my $line (split(/\&/,$answer)) {
                   4752: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4753:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4754:     }
1.75      www      4755:     my $version;
                   4756:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4757:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4758:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4759:        }
1.75      www      4760:     }
1.13      www      4761:     return %returnhash;
1.34      www      4762: }
                   4763: 
                   4764: # ---------------------------------------------------------- Course Description
1.1118    foxr     4765: #
                   4766: #  
1.34      www      4767: 
                   4768: sub coursedescription {
1.731     albertel 4769:     my ($courseid,$args)=@_;
1.34      www      4770:     $courseid=~s/^\///;
1.49      www      4771:     $courseid=~s/\_/\//g;
1.34      www      4772:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4773:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4774:     my $normalid=$cdomain.'_'.$cnum;
                   4775:     # need to always cache even if we get errors otherwise we keep 
                   4776:     # trying and trying and trying to get the course description.
                   4777:     my %envhash=();
                   4778:     my %returnhash=();
1.731     albertel 4779:     
                   4780:     my $expiretime=600;
                   4781:     if ($env{'request.course.id'} eq $normalid) {
                   4782: 	$expiretime=120;
                   4783:     }
                   4784: 
                   4785:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4786:     if (!$args->{'freshen_cache'}
                   4787: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4788: 	foreach my $key (keys(%env)) {
                   4789: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4790: 	    my ($setting) = $1;
                   4791: 	    $returnhash{$setting} = $env{$key};
                   4792: 	}
                   4793: 	return %returnhash;
                   4794:     }
                   4795: 
1.1118    foxr     4796:     # get the data again
                   4797: 
1.731     albertel 4798:     if (!$args->{'one_time'}) {
                   4799: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4800:     }
1.811     albertel 4801: 
1.34      www      4802:     if ($chome ne 'no_host') {
1.302     albertel 4803:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4804:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4805: 	   my $username = $env{'user.name'}; # Defult username
                   4806: 	   if(defined $args->{'user'}) {
                   4807: 	       $username = $args->{'user'};
                   4808: 	   }
1.129     albertel 4809:            $returnhash{'home'}= $chome;
                   4810: 	   $returnhash{'domain'} = $cdomain;
                   4811: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4812:            if (!defined($returnhash{'type'})) {
                   4813:                $returnhash{'type'} = 'Course';
                   4814:            }
1.130     albertel 4815:            while (my ($name,$value) = each %returnhash) {
1.53      www      4816:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4817:            }
1.270     www      4818:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4819:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4820: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4821:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4822:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4823:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4824:        }
                   4825:     }
1.731     albertel 4826:     if (!$args->{'one_time'}) {
1.949     raeburn  4827: 	&appenv(\%envhash);
1.731     albertel 4828:     }
1.302     albertel 4829:     return %returnhash;
1.461     www      4830: }
                   4831: 
1.1080    raeburn  4832: sub update_released_required {
                   4833:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4834:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4835:         $cid = $env{'request.course.id'};
                   4836:         $cdom = $env{'course.'.$cid.'.domain'};
                   4837:         $cnum = $env{'course.'.$cid.'.num'};
                   4838:         $chome = $env{'course.'.$cid.'.home'};
                   4839:     }
                   4840:     if ($needsrelease) {
                   4841:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4842:         my $needsupdate;
                   4843:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4844:             $needsupdate = 1;
                   4845:         } else {
                   4846:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4847:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4848:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4849:                 $needsupdate = 1;
                   4850:             }
                   4851:         }
                   4852:         if ($needsupdate) {
                   4853:             my %needshash = (
                   4854:                              'internal.releaserequired' => $needsrelease,
                   4855:                             );
                   4856:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4857:             if ($putresult eq 'ok') {
                   4858:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4859:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4860:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4861:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4862:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4863:                 }
                   4864:             }
                   4865:         }
                   4866:     }
                   4867:     return;
                   4868: }
                   4869: 
1.461     www      4870: # -------------------------------------------------See if a user is privileged
                   4871: 
                   4872: sub privileged {
                   4873:     my ($username,$domain)=@_;
1.1170    droeschl 4874: 
                   4875:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4876:     my $now = time;
                   4877: 
                   4878:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4879:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4880:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4881:                 return 1 unless ($tend && $tend < $now) 
                   4882:                     or ($tstart && $tstart > $now);
                   4883:             }
1.461     www      4884: 	}
1.1170    droeschl 4885: 
1.461     www      4886:     return 0;
1.9       www      4887: }
1.1       albertel 4888: 
1.103     harris41 4889: # -------------------------------------------------------- Get user privileges
1.11      www      4890: 
                   4891: sub rolesinit {
1.1169    droeschl 4892:     my ($domain, $username) = @_;
                   4893:     my %userroles = ('user.login.time' => time);
                   4894:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4895: 
                   4896:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4897:     # also, blocking can be triggered by an activating timer
                   4898:     # it's saved in the user's %env.
                   4899:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4900:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4901:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4902:         %timerintchk, %timerintenv);
                   4903: 
1.1162    raeburn  4904:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4905:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4906:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4907:     }
1.1169    droeschl 4908: 
1.1162    raeburn  4909:     foreach my $key (keys(%timerinterval)) {
                   4910:         my ($cid,$rest) = split(/\0/,$key);
                   4911:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4912:     }
1.1169    droeschl 4913: 
1.11      www      4914:     my %allroles=();
1.1162    raeburn  4915:     my %allgroups=();
1.11      www      4916: 
1.1169    droeschl 4917:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4918:         my $role = $rolesdump{$area};
                   4919:         $area =~ s/\_\w\w$//;
                   4920: 
                   4921:         my ($trole, $tend, $tstart, $group_privs);
                   4922: 
                   4923:         if ($role =~ /^cr/) {
                   4924:         # Custom role, defined by a user 
                   4925:         # e.g., user.role.cr/msu/smith/mynewrole
                   4926:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4927:                 $trole = $1;
                   4928:                 ($tend, $tstart) = split('_', $2);
                   4929:             } else {
                   4930:                 $trole = $role;
                   4931:             }
                   4932:         } elsif ($role =~ m|^gr/|) {
                   4933:         # Role of member in a group, defined within a course/community
                   4934:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4935:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4936:             next if $tstart eq '-1';
                   4937:             ($trole, $group_privs) = split(/\//, $trole);
                   4938:             $group_privs = &unescape($group_privs);
                   4939:         } else {
                   4940:         # Just a normal role, defined in roles.tab
                   4941:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4942:         }
                   4943: 
                   4944:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4945:                  $username);
                   4946:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4947: 
                   4948:         # role expired or not available yet?
                   4949:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4950:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4951: 
                   4952:         next if $area eq '' or $trole eq '';
                   4953: 
                   4954:         my $spec = "$trole.$area";
                   4955:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4956: 
                   4957:         if ($trole =~ /^cr\//) {
                   4958:         # Custom role, defined by a user
                   4959:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4960:         } elsif ($trole eq 'gr') {
                   4961:         # Role of a member in a group, defined within a course/community
                   4962:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4963:             next;
                   4964:         } else {
                   4965:         # Normal role, defined in roles.tab
                   4966:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4967:         }
                   4968: 
                   4969:         my $cid = $tdomain.'_'.$trest;
                   4970:         unless ($firstaccchk{$cid}) {
                   4971:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4972:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4973:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4974:                         $coursetimerstarts{$cid}{$item}; 
                   4975:                 }
                   4976:             }
                   4977:             $firstaccchk{$cid} = 1;
                   4978:         }
                   4979:         unless ($timerintchk{$cid}) {
                   4980:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4981:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4982:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4983:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4984:                 }
1.12      www      4985:             }
1.1169    droeschl 4986:             $timerintchk{$cid} = 1;
1.191     harris41 4987:         }
1.11      www      4988:     }
1.1169    droeschl 4989: 
                   4990:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4991:         \%allroles, \%allgroups);
                   4992:     $env{'user.adv'} = $userroles{'user.adv'};
                   4993: 
1.1162    raeburn  4994:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4995: }
                   4996: 
1.567     raeburn  4997: sub set_arearole {
                   4998:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4999: # log the associated role with the area
                   5000:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 5001:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5002: }
                   5003: 
                   5004: sub custom_roleprivs {
                   5005:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5006:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5007:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5008:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5009:         my ($rdummy,$roledef)=
                   5010:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5011:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5012:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5013:             if (defined($syspriv)) {
1.1043    raeburn  5014:                 if ($trest =~ /^$match_community$/) {
                   5015:                     $syspriv =~ s/bre\&S//; 
                   5016:                 }
1.567     raeburn  5017:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5018:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5019:             }
                   5020:             if ($tdomain ne '') {
                   5021:                 if (defined($dompriv)) {
                   5022:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5023:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5024:                 }
                   5025:                 if (($trest ne '') && (defined($coursepriv))) {
                   5026:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5027:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5028:                 }
                   5029:             }
                   5030:         }
                   5031:     }
                   5032: }
                   5033: 
1.678     raeburn  5034: sub group_roleprivs {
                   5035:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5036:     my $access = 1;
                   5037:     my $now = time;
                   5038:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5039:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5040:     if ($access) {
1.811     albertel 5041:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5042:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5043:     }
                   5044: }
1.567     raeburn  5045: 
                   5046: sub standard_roleprivs {
                   5047:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5048:     if (defined($pr{$trole.':s'})) {
                   5049:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5050:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5051:     }
                   5052:     if ($tdomain ne '') {
                   5053:         if (defined($pr{$trole.':d'})) {
                   5054:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5055:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5056:         }
                   5057:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5058:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5059:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5060:         }
                   5061:     }
                   5062: }
                   5063: 
                   5064: sub set_userprivs {
1.1064    raeburn  5065:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5066:     my $author=0;
                   5067:     my $adv=0;
1.678     raeburn  5068:     my %grouproles = ();
                   5069:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5070:         my @groupkeys; 
1.1000    raeburn  5071:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5072:             push(@groupkeys,$role);
                   5073:         }
                   5074:         if (ref($groups_roles) eq 'HASH') {
                   5075:             foreach my $key (keys(%{$groups_roles})) {
                   5076:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5077:                     push(@groupkeys,$key);
                   5078:                 }
                   5079:             }
                   5080:         }
                   5081:         if (@groupkeys > 0) {
                   5082:             foreach my $role (@groupkeys) {
                   5083:                 my ($trole,$area,$sec,$extendedarea);
                   5084:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5085:                     $trole = $1;
                   5086:                     $area = $2;
                   5087:                     $sec = $3;
                   5088:                     $extendedarea = $area.$sec;
                   5089:                     if (exists($$allgroups{$area})) {
                   5090:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5091:                             my $spec = $trole.'.'.$extendedarea;
                   5092:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5093:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5094:                         }
1.678     raeburn  5095:                     }
                   5096:                 }
                   5097:             }
                   5098:         }
                   5099:     }
1.800     albertel 5100:     foreach my $group (keys(%grouproles)) {
                   5101:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5102:     }
1.800     albertel 5103:     foreach my $role (keys(%{$allroles})) {
                   5104:         my %thesepriv;
1.941     raeburn  5105:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5106:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5107:             if ($item ne '') {
                   5108:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5109:                 if ($restrictions eq '') {
                   5110:                     $thesepriv{$privilege}='F';
                   5111:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5112:                     $thesepriv{$privilege}.=$restrictions;
                   5113:                 }
                   5114:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5115:             }
                   5116:         }
                   5117:         my $thesestr='';
1.1104    raeburn  5118:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5119: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5120: 	}
                   5121:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5122:     }
                   5123:     return ($author,$adv);
                   5124: }
                   5125: 
1.994     raeburn  5126: sub role_status {
1.1104    raeburn  5127:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5128:     my @pwhere = ();
                   5129:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5130:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5131:         unless (!defined($$role) || $$role eq '') {
                   5132:             $$where=join('.',@pwhere);
                   5133:             $$trolecode=$$role.'.'.$$where;
                   5134:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5135:             $$tstatus='is';
1.1104    raeburn  5136:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5137:                 $$tstatus='future';
1.1034    raeburn  5138:                 if ($$tstart<$now) {
                   5139:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5140:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5141:                             my (%allroles,%allgroups,$group_privs,
                   5142:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5143:                             my %userroles = (
                   5144:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5145:                             );
1.1064    raeburn  5146:                             @rolecodes = ('cm'); 
1.1002    raeburn  5147:                             my $spec=$$role.'.'.$$where;
                   5148:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5149:                             if ($$role =~ /^cr\//) {
                   5150:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5151:                                 push(@rolecodes,'cr');
1.1002    raeburn  5152:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5153:                                 push(@rolecodes,$$role);
1.1002    raeburn  5154:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5155:                                                     $env{'user.name'});
1.1064    raeburn  5156:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5157:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5158:                                 $group_privs = &unescape($group_privs);
                   5159:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5160:                                 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  5161:                                 &get_groups_roles($tdomain,$trest,
                   5162:                                                   \%course_roles,\@rolecodes,
                   5163:                                                   \%groups_roles);
1.1002    raeburn  5164:                             } else {
1.1064    raeburn  5165:                                 push(@rolecodes,$$role);
1.1002    raeburn  5166:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5167:                             }
1.1064    raeburn  5168:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5169:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5170:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5171:                         }
                   5172:                     }
1.1034    raeburn  5173:                     $$tstatus = 'is';
1.1002    raeburn  5174:                 }
1.994     raeburn  5175:             }
                   5176:             if ($$tend) {
1.1104    raeburn  5177:                 if ($$tend<$update) {
1.994     raeburn  5178:                     $$tstatus='expired';
                   5179:                 } elsif ($$tend<$now) {
                   5180:                     $$tstatus='will_not';
                   5181:                 }
                   5182:             }
                   5183:         }
                   5184:     }
                   5185: }
                   5186: 
1.1104    raeburn  5187: sub get_groups_roles {
                   5188:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5189:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5190:                   (ref($rolecodes) eq 'ARRAY') && 
                   5191:                   (ref($groups_roles) eq 'HASH')); 
                   5192:     if (keys(%{$cdom_courseroles}) > 0) {
                   5193:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5194:         if ($cdom ne '' && $cnum ne '') {
                   5195:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5196:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5197:                     my $crsrole = $1;
                   5198:                     my $crssec = $2;
                   5199:                     if ($crsrole =~ /^cr/) {
                   5200:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5201:                             push(@{$rolecodes},'cr');
                   5202:                         }
                   5203:                     } else {
                   5204:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5205:                             push(@{$rolecodes},$crsrole);
                   5206:                         }
                   5207:                     }
                   5208:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5209:                     if ($crssec ne '') {
                   5210:                         $rolekey .= "/$crssec";
                   5211:                     }
                   5212:                     $rolekey .= './';
                   5213:                     $groups_roles->{$rolekey} = $rolecodes;
                   5214:                 }
                   5215:             }
                   5216:         }
                   5217:     }
                   5218:     return;
                   5219: }
                   5220: 
                   5221: sub delete_env_groupprivs {
                   5222:     my ($where,$courseroles,$possroles) = @_;
                   5223:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5224:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5225:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5226:         %{$courseroles->{$udom}} =
                   5227:             &get_my_roles('','','userroles',['active'],
                   5228:                           $possroles,[$udom],1);
                   5229:     }
                   5230:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5231:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5232:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5233:             my $area = '/'.$cdom.'/'.$cnum;
                   5234:             my $privkey = "user.priv.$crsrole.$area";
                   5235:             if ($crssec ne '') {
                   5236:                 $privkey .= '/'.$crssec;
                   5237:             }
                   5238:             $privkey .= ".$area/$group";
                   5239:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5240:         }
                   5241:     }
                   5242:     return;
                   5243: }
                   5244: 
1.994     raeburn  5245: sub check_adhoc_privs {
1.1104    raeburn  5246:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5247:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5248:     my $setprivs;
1.994     raeburn  5249:     if ($env{$cckey}) {
                   5250:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5251:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5252:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5253:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5254:             $setprivs = 1;
1.994     raeburn  5255:         }
                   5256:     } else {
1.1088    raeburn  5257:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5258:         $setprivs = 1;
1.994     raeburn  5259:     }
1.1185    raeburn  5260:     return $setprivs;
1.994     raeburn  5261: }
                   5262: 
                   5263: sub set_adhoc_privileges {
                   5264: # role can be cc or ca
1.1088    raeburn  5265:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5266:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5267:     my $spec = $role.'.'.$area;
                   5268:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5269:                                   $env{'user.name'});
                   5270:     my %ccrole = ();
                   5271:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5272:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5273:     &appenv(\%userroles,[$role,'cm']);
                   5274:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5275:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5276:         &appenv( {'request.role'        => $spec,
                   5277:                   'request.role.domain' => $dcdom,
                   5278:                   'request.course.sec'  => ''
                   5279:                  }
                   5280:                );
                   5281:         my $tadv=0;
                   5282:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5283:         &appenv({'request.role.adv'    => $tadv});
                   5284:     }
1.994     raeburn  5285: }
                   5286: 
1.12      www      5287: # --------------------------------------------------------------- get interface
                   5288: 
                   5289: sub get {
1.131     albertel 5290:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5291:    my $items='';
1.800     albertel 5292:    foreach my $item (@$storearr) {
                   5293:        $items.=&escape($item).'&';
1.191     harris41 5294:    }
1.12      www      5295:    $items=~s/\&$//;
1.620     albertel 5296:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5297:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5298:    my $uhome=&homeserver($uname,$udomain);
                   5299: 
1.133     albertel 5300:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5301:    my @pairs=split(/\&/,$rep);
1.273     albertel 5302:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5303:      return @pairs;
                   5304:    }
1.15      www      5305:    my %returnhash=();
1.42      www      5306:    my $i=0;
1.800     albertel 5307:    foreach my $item (@$storearr) {
                   5308:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5309:       $i++;
1.191     harris41 5310:    }
1.15      www      5311:    return %returnhash;
1.27      www      5312: }
                   5313: 
                   5314: # --------------------------------------------------------------- del interface
                   5315: 
                   5316: sub del {
1.133     albertel 5317:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5318:    my $items='';
1.800     albertel 5319:    foreach my $item (@$storearr) {
                   5320:        $items.=&escape($item).'&';
1.191     harris41 5321:    }
1.984     neumanie 5322: 
1.27      www      5323:    $items=~s/\&$//;
1.620     albertel 5324:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5325:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5326:    my $uhome=&homeserver($uname,$udomain);
                   5327:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5328: }
                   5329: 
                   5330: # -------------------------------------------------------------- dump interface
                   5331: 
1.1180    droeschl 5332: sub unserialize {
                   5333:     my ($rep, $escapedkeys) = @_;
                   5334: 
                   5335:     return {} if $rep =~ /^error/;
                   5336: 
                   5337:     my %returnhash=();
                   5338: 	foreach my $item (split /\&/, $rep) {
                   5339: 	    my ($key, $value) = split(/=/, $item, 2);
                   5340: 	    $key = unescape($key) unless $escapedkeys;
                   5341: 	    next if $key =~ /^error: 2 /;
                   5342: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5343: 	}
                   5344:     #return %returnhash;
                   5345:     return \%returnhash;
                   5346: }        
                   5347: 
                   5348: # see Lond::dump_with_regexp
                   5349: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5350: sub dump {
1.1180    droeschl 5351:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5352:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5353:     if (!$uname) { $uname=$env{'user.name'}; }
                   5354:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5355: 
1.1180    droeschl 5356:     my $reply;
                   5357:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5358:         # user is hosted on this machine
                   5359:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
                   5360:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5361:         return %{unserialize($reply, $escapedkeys)};
                   5362:     }
1.755     albertel 5363:     if ($regexp) {
                   5364: 	$regexp=&escape($regexp);
                   5365:     } else {
                   5366: 	$regexp='.';
                   5367:     }
1.1166    raeburn  5368:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5369:     my @pairs=split(/\&/,$rep);
                   5370:     my %returnhash=();
1.1098    foxr     5371:     if (!($rep =~ /^error/ )) {
                   5372: 	foreach my $item (@pairs) {
                   5373: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5374:         $key = unescape($key) unless $escapedkeys;
                   5375:         #$key = &unescape($key);
1.1098    foxr     5376: 	    next if ($key =~ /^error: 2 /);
                   5377: 	    $returnhash{$key}=&thaw_unescape($value);
                   5378: 	}
1.755     albertel 5379:     }
                   5380:     return %returnhash;
1.407     www      5381: }
                   5382: 
1.1098    foxr     5383: 
1.717     albertel 5384: # --------------------------------------------------------- dumpstore interface
                   5385: 
                   5386: sub dumpstore {
                   5387:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5388:    # same as dump but keys must be escaped. They may contain colon separated
                   5389:    # lists of values that may themself contain colons (e.g. symbs).
                   5390:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5391: }
                   5392: 
1.407     www      5393: # -------------------------------------------------------------- keys interface
                   5394: 
                   5395: sub getkeys {
                   5396:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5397:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5398:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5399:    my $uhome=&homeserver($uname,$udomain);
                   5400:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5401:    my @keyarray=();
1.800     albertel 5402:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5403:       next if ($key =~ /^error: 2 /);
1.800     albertel 5404:       push(@keyarray,&unescape($key));
1.407     www      5405:    }
                   5406:    return @keyarray;
1.318     matthew  5407: }
                   5408: 
1.319     matthew  5409: # --------------------------------------------------------------- currentdump
                   5410: sub currentdump {
1.328     matthew  5411:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5412:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5413:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5414:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5415:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5416:    my $rep;
                   5417: 
                   5418:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5419:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5420:                    $courseid)));
                   5421:    } else {
                   5422:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5423:    }
                   5424: 
1.318     matthew  5425:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5426:    #
1.318     matthew  5427:    my %returnhash=();
1.319     matthew  5428:    #
                   5429:    if ($rep eq "unknown_cmd") { 
                   5430:        # an old lond will not know currentdump
                   5431:        # Do a dump and make it look like a currentdump
1.822     albertel 5432:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5433:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5434:        my %hash = @tmp;
                   5435:        @tmp=();
1.424     matthew  5436:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5437:    } else {
                   5438:        my @pairs=split(/\&/,$rep);
1.800     albertel 5439:        foreach my $pair (@pairs) {
                   5440:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5441:            my ($symb,$param) = split(/:/,$key);
                   5442:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5443:                                                         &thaw_unescape($value);
1.319     matthew  5444:        }
1.191     harris41 5445:    }
1.12      www      5446:    return %returnhash;
1.424     matthew  5447: }
                   5448: 
                   5449: sub convert_dump_to_currentdump{
                   5450:     my %hash = %{shift()};
                   5451:     my %returnhash;
                   5452:     # Code ripped from lond, essentially.  The only difference
                   5453:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5454:     # we might run in to problems with parameter names =~ /^v\./
                   5455:     while (my ($key,$value) = each(%hash)) {
                   5456:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5457: 	$symb  = &unescape($symb);
                   5458: 	$param = &unescape($param);
1.424     matthew  5459:         next if ($v eq 'version' || $symb eq 'keys');
                   5460:         next if (exists($returnhash{$symb}) &&
                   5461:                  exists($returnhash{$symb}->{$param}) &&
                   5462:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5463:         $returnhash{$symb}->{$param}=$value;
                   5464:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5465:     }
                   5466:     #
                   5467:     # Remove all of the keys in the hashes which keep track of
                   5468:     # the version of the parameter.
                   5469:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5470:         # use a foreach because we are going to delete from the hash.
                   5471:         foreach my $key (keys(%$param_hash)) {
                   5472:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5473:         }
                   5474:     }
                   5475:     return \%returnhash;
1.12      www      5476: }
                   5477: 
1.627     albertel 5478: # ------------------------------------------------------ critical inc interface
                   5479: 
                   5480: sub cinc {
                   5481:     return &inc(@_,'critical');
                   5482: }
                   5483: 
1.449     matthew  5484: # --------------------------------------------------------------- inc interface
                   5485: 
                   5486: sub inc {
1.627     albertel 5487:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5488:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5489:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5490:     my $uhome=&homeserver($uname,$udomain);
                   5491:     my $items='';
                   5492:     if (! ref($store)) {
                   5493:         # got a single value, so use that instead
                   5494:         $items = &escape($store).'=&';
                   5495:     } elsif (ref($store) eq 'SCALAR') {
                   5496:         $items = &escape($$store).'=&';        
                   5497:     } elsif (ref($store) eq 'ARRAY') {
                   5498:         $items = join('=&',map {&escape($_);} @{$store});
                   5499:     } elsif (ref($store) eq 'HASH') {
                   5500:         while (my($key,$value) = each(%{$store})) {
                   5501:             $items.= &escape($key).'='.&escape($value).'&';
                   5502:         }
                   5503:     }
                   5504:     $items=~s/\&$//;
1.627     albertel 5505:     if ($critical) {
                   5506: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5507:     } else {
                   5508: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5509:     }
1.449     matthew  5510: }
                   5511: 
1.12      www      5512: # --------------------------------------------------------------- put interface
                   5513: 
                   5514: sub put {
1.134     albertel 5515:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5516:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5517:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5518:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5519:    my $items='';
1.800     albertel 5520:    foreach my $item (keys(%$storehash)) {
                   5521:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5522:    }
1.12      www      5523:    $items=~s/\&$//;
1.134     albertel 5524:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5525: }
                   5526: 
1.631     albertel 5527: # ------------------------------------------------------------ newput interface
                   5528: 
                   5529: sub newput {
                   5530:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5531:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5532:    if (!$uname) { $uname=$env{'user.name'}; }
                   5533:    my $uhome=&homeserver($uname,$udomain);
                   5534:    my $items='';
                   5535:    foreach my $key (keys(%$storehash)) {
                   5536:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5537:    }
                   5538:    $items=~s/\&$//;
                   5539:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5540: }
                   5541: 
                   5542: # ---------------------------------------------------------  putstore interface
                   5543: 
1.524     raeburn  5544: sub putstore {
1.715     albertel 5545:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5546:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5547:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5548:    my $uhome=&homeserver($uname,$udomain);
                   5549:    my $items='';
1.715     albertel 5550:    foreach my $key (keys(%$storehash)) {
                   5551:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5552:    }
1.715     albertel 5553:    $items=~s/\&$//;
1.716     albertel 5554:    my $esc_symb=&escape($symb);
                   5555:    my $esc_v=&escape($version);
1.715     albertel 5556:    my $reply =
1.716     albertel 5557:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5558: 	      $uhome);
                   5559:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5560:        # gfall back to way things use to be done
1.715     albertel 5561:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5562: 			    $uname);
1.524     raeburn  5563:    }
1.715     albertel 5564:    return $reply;
                   5565: }
                   5566: 
                   5567: sub old_putstore {
1.716     albertel 5568:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5569:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5570:     if (!$uname) { $uname=$env{'user.name'}; }
                   5571:     my $uhome=&homeserver($uname,$udomain);
                   5572:     my %newstorehash;
1.800     albertel 5573:     foreach my $item (keys(%$storehash)) {
                   5574: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5575: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5576:     }
                   5577:     my $items='';
                   5578:     my %allitems = ();
1.800     albertel 5579:     foreach my $item (keys(%newstorehash)) {
                   5580: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5581: 	    my $key = $1.':keys:'.$2;
                   5582: 	    $allitems{$key} .= $3.':';
                   5583: 	}
1.800     albertel 5584: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5585:     }
1.800     albertel 5586:     foreach my $item (keys(%allitems)) {
                   5587: 	$allitems{$item} =~ s/\:$//;
                   5588: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5589:     }
                   5590:     $items=~s/\&$//;
                   5591:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5592: }
                   5593: 
1.47      www      5594: # ------------------------------------------------------ critical put interface
                   5595: 
                   5596: sub cput {
1.134     albertel 5597:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5598:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5599:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5600:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5601:    my $items='';
1.800     albertel 5602:    foreach my $item (keys(%$storehash)) {
                   5603:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5604:    }
1.47      www      5605:    $items=~s/\&$//;
1.134     albertel 5606:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5607: }
                   5608: 
                   5609: # -------------------------------------------------------------- eget interface
                   5610: 
                   5611: sub eget {
1.133     albertel 5612:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5613:    my $items='';
1.800     albertel 5614:    foreach my $item (@$storearr) {
                   5615:        $items.=&escape($item).'&';
1.191     harris41 5616:    }
1.12      www      5617:    $items=~s/\&$//;
1.620     albertel 5618:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5619:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5620:    my $uhome=&homeserver($uname,$udomain);
                   5621:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5622:    my @pairs=split(/\&/,$rep);
                   5623:    my %returnhash=();
1.42      www      5624:    my $i=0;
1.800     albertel 5625:    foreach my $item (@$storearr) {
                   5626:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5627:       $i++;
1.191     harris41 5628:    }
1.12      www      5629:    return %returnhash;
                   5630: }
                   5631: 
1.667     albertel 5632: # ------------------------------------------------------------ tmpput interface
                   5633: sub tmpput {
1.802     raeburn  5634:     my ($storehash,$server,$context)=@_;
1.667     albertel 5635:     my $items='';
1.800     albertel 5636:     foreach my $item (keys(%$storehash)) {
                   5637: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5638:     }
                   5639:     $items=~s/\&$//;
1.802     raeburn  5640:     if (defined($context)) {
                   5641:         $items .= ':'.&escape($context);
                   5642:     }
1.667     albertel 5643:     return &reply("tmpput:$items",$server);
                   5644: }
                   5645: 
                   5646: # ------------------------------------------------------------ tmpget interface
                   5647: sub tmpget {
1.688     albertel 5648:     my ($token,$server)=@_;
                   5649:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5650:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5651:     my %returnhash;
                   5652:     foreach my $item (split(/\&/,$rep)) {
                   5653: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5654:         next if ($key =~ /^error: 2 /);
1.667     albertel 5655: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5656:     }
                   5657:     return %returnhash;
                   5658: }
                   5659: 
1.1113    raeburn  5660: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5661: sub tmpdel {
                   5662:     my ($token,$server)=@_;
                   5663:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5664:     return &reply("tmpdel:$token",$server);
                   5665: }
                   5666: 
1.765     albertel 5667: # -------------------------------------------------- portfolio access checking
                   5668: 
                   5669: sub portfolio_access {
1.766     albertel 5670:     my ($requrl) = @_;
1.765     albertel 5671:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5672:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5673:     if ($result) {
                   5674:         my %setters;
                   5675:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5676:             my ($startblock,$endblock) =
                   5677:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5678:             if ($startblock && $endblock) {
                   5679:                 return 'B';
                   5680:             }
                   5681:         } else {
                   5682:             my ($startblock,$endblock) =
                   5683:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5684:             if ($startblock && $endblock) {
                   5685:                 return 'B';
                   5686:             }
                   5687:         }
                   5688:     }
1.765     albertel 5689:     if ($result eq 'ok') {
1.766     albertel 5690:        return 'F';
1.765     albertel 5691:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5692:        return 'A';
1.765     albertel 5693:     }
1.766     albertel 5694:     return '';
1.765     albertel 5695: }
                   5696: 
                   5697: sub get_portfolio_access {
1.767     albertel 5698:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5699: 
                   5700:     if (!ref($access_hash)) {
                   5701: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5702: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5703: 						   $file_name);
                   5704: 	$access_hash = $access_controls{$file_name};
                   5705:     }
                   5706: 
1.765     albertel 5707:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5708:     my $now = time;
                   5709:     if (ref($access_hash) eq 'HASH') {
                   5710:         foreach my $key (keys(%{$access_hash})) {
                   5711:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5712:             if ($start > $now) {
                   5713:                 next;
                   5714:             }
                   5715:             if ($end && $end<$now) {
                   5716:                 next;
                   5717:             }
                   5718:             if ($scope eq 'public') {
                   5719:                 $public = $key;
                   5720:                 last;
                   5721:             } elsif ($scope eq 'guest') {
                   5722:                 $guest = $key;
                   5723:             } elsif ($scope eq 'domains') {
                   5724:                 push(@domains,$key);
                   5725:             } elsif ($scope eq 'users') {
                   5726:                 push(@users,$key);
                   5727:             } elsif ($scope eq 'course') {
                   5728:                 push(@courses,$key);
                   5729:             } elsif ($scope eq 'group') {
                   5730:                 push(@groups,$key);
                   5731:             }
                   5732:         }
                   5733:         if ($public) {
                   5734:             return 'ok';
                   5735:         }
                   5736:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5737:             if ($guest) {
                   5738:                 return $guest;
                   5739:             }
                   5740:         } else {
                   5741:             if (@domains > 0) {
                   5742:                 foreach my $domkey (@domains) {
                   5743:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5744:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5745:                             return 'ok';
                   5746:                         }
                   5747:                     }
                   5748:                 }
                   5749:             }
                   5750:             if (@users > 0) {
                   5751:                 foreach my $userkey (@users) {
1.865     raeburn  5752:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5753:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5754:                             if (ref($item) eq 'HASH') {
                   5755:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5756:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5757:                                     return 'ok';
                   5758:                                 }
                   5759:                             }
                   5760:                         }
                   5761:                     } 
1.765     albertel 5762:                 }
                   5763:             }
                   5764:             my %roleshash;
                   5765:             my @courses_and_groups = @courses;
                   5766:             push(@courses_and_groups,@groups); 
                   5767:             if (@courses_and_groups > 0) {
                   5768:                 my (%allgroups,%allroles); 
                   5769:                 my ($start,$end,$role,$sec,$group);
                   5770:                 foreach my $envkey (%env) {
1.1060    raeburn  5771:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5772:                         my $cid = $2.'_'.$3; 
                   5773:                         if ($1 eq 'gr') {
                   5774:                             $group = $4;
                   5775:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5776:                         } else {
                   5777:                             if ($4 eq '') {
                   5778:                                 $sec = 'none';
                   5779:                             } else {
                   5780:                                 $sec = $4;
                   5781:                             }
                   5782:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5783:                         }
1.811     albertel 5784:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5785:                         my $cid = $2.'_'.$3;
                   5786:                         if ($4 eq '') {
                   5787:                             $sec = 'none';
                   5788:                         } else {
                   5789:                             $sec = $4;
                   5790:                         }
                   5791:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5792:                     }
                   5793:                 }
                   5794:                 if (keys(%allroles) == 0) {
                   5795:                     return;
                   5796:                 }
                   5797:                 foreach my $key (@courses_and_groups) {
                   5798:                     my %content = %{$$access_hash{$key}};
                   5799:                     my $cnum = $content{'number'};
                   5800:                     my $cdom = $content{'domain'};
                   5801:                     my $cid = $cdom.'_'.$cnum;
                   5802:                     if (!exists($allroles{$cid})) {
                   5803:                         next;
                   5804:                     }    
                   5805:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5806:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5807:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5808:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5809:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5810:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5811:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5812:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5813:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5814:                                         if (grep/^all$/,@sections) {
                   5815:                                             return 'ok';
                   5816:                                         } else {
                   5817:                                             if (grep/^$sec$/,@sections) {
                   5818:                                                 return 'ok';
                   5819:                                             }
                   5820:                                         }
                   5821:                                     }
                   5822:                                 }
                   5823:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5824:                                     if (grep/^none$/,@groups) {
                   5825:                                         return 'ok';
                   5826:                                     }
                   5827:                                 } else {
                   5828:                                     if (grep/^all$/,@groups) {
                   5829:                                         return 'ok';
                   5830:                                     } 
                   5831:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5832:                                         if (grep/^$group$/,@groups) {
                   5833:                                             return 'ok';
                   5834:                                         }
                   5835:                                     }
                   5836:                                 } 
                   5837:                             }
                   5838:                         }
                   5839:                     }
                   5840:                 }
                   5841:             }
                   5842:             if ($guest) {
                   5843:                 return $guest;
                   5844:             }
                   5845:         }
                   5846:     }
                   5847:     return;
                   5848: }
                   5849: 
                   5850: sub course_group_datechecker {
                   5851:     my ($dates,$now,$status) = @_;
                   5852:     my ($start,$end) = split(/\./,$dates);
                   5853:     if (!$start && !$end) {
                   5854:         return 'ok';
                   5855:     }
                   5856:     if (grep/^active$/,@{$status}) {
                   5857:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5858:             return 'ok';
                   5859:         }
                   5860:     }
                   5861:     if (grep/^previous$/,@{$status}) {
                   5862:         if ($end > $now ) {
                   5863:             return 'ok';
                   5864:         }
                   5865:     }
                   5866:     if (grep/^future$/,@{$status}) {
                   5867:         if ($start > $now) {
                   5868:             return 'ok';
                   5869:         }
                   5870:     }
                   5871:     return; 
                   5872: }
                   5873: 
                   5874: sub parse_portfolio_url {
                   5875:     my ($url) = @_;
                   5876: 
                   5877:     my ($type,$udom,$unum,$group,$file_name);
                   5878:     
1.823     albertel 5879:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5880: 	$type = 1;
                   5881:         $udom = $1;
                   5882:         $unum = $2;
                   5883:         $file_name = $3;
1.823     albertel 5884:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5885: 	$type = 2;
                   5886:         $udom = $1;
                   5887:         $unum = $2;
                   5888:         $group = $3;
                   5889:         $file_name = $3.'/'.$4;
                   5890:     }
                   5891:     if (wantarray) {
                   5892: 	return ($type,$udom,$unum,$file_name,$group);
                   5893:     }
                   5894:     return $type;
                   5895: }
                   5896: 
                   5897: sub is_portfolio_url {
                   5898:     my ($url) = @_;
                   5899:     return scalar(&parse_portfolio_url($url));
                   5900: }
                   5901: 
1.798     raeburn  5902: sub is_portfolio_file {
                   5903:     my ($file) = @_;
1.820     raeburn  5904:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5905:         return 1;
                   5906:     }
                   5907:     return;
                   5908: }
                   5909: 
1.976     raeburn  5910: sub usertools_access {
1.1084    raeburn  5911:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5912:     my ($access,%tools);
                   5913:     if ($context eq '') {
                   5914:         $context = 'tools';
                   5915:     }
                   5916:     if ($context eq 'requestcourses') {
                   5917:         %tools = (
                   5918:                       official   => 1,
                   5919:                       unofficial => 1,
1.1006    raeburn  5920:                       community  => 1,
1.985     raeburn  5921:                  );
1.1183    raeburn  5922:     } elsif ($context eq 'requestauthor') {
                   5923:         %tools = (
                   5924:                       requestauthor => 1,
                   5925:                  );
1.985     raeburn  5926:     } else {
                   5927:         %tools = (
                   5928:                       aboutme   => 1,
                   5929:                       blog      => 1,
1.1177    raeburn  5930:                       webdav    => 1,
1.985     raeburn  5931:                       portfolio => 1,
                   5932:                  );
                   5933:     }
1.976     raeburn  5934:     return if (!defined($tools{$tool}));
                   5935: 
                   5936:     if ((!defined($udom)) || (!defined($uname))) {
                   5937:         $udom = $env{'user.domain'};
                   5938:         $uname = $env{'user.name'};
                   5939:     }
                   5940: 
1.978     raeburn  5941:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5942:         if ($action ne 'reload') {
1.985     raeburn  5943:             if ($context eq 'requestcourses') {
                   5944:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  5945:             } elsif ($context eq 'requestauthor') {
                   5946:                 return $env{'environment.canrequest.author'};
1.985     raeburn  5947:             } else {
                   5948:                 return $env{'environment.availabletools.'.$tool};
                   5949:             }
                   5950:         }
1.976     raeburn  5951:     }
                   5952: 
1.1183    raeburn  5953:     my ($toolstatus,$inststatus,$envkey);
                   5954:     if ($context eq 'requestauthor') {
                   5955:         $envkey = $context; 
                   5956:     } else {
                   5957:         $envkey = $context.'.'.$tool;
                   5958:     }
1.976     raeburn  5959: 
1.985     raeburn  5960:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5961:          ($action ne 'reload')) {
1.1183    raeburn  5962:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  5963:         $inststatus = $env{'environment.inststatus'};
                   5964:     } else {
1.1084    raeburn  5965:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  5966:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  5967:             $inststatus = $userenvref->{'inststatus'};
                   5968:         } else {
1.1183    raeburn  5969:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   5970:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  5971:             $inststatus = $userenv{'inststatus'};
                   5972:         }
1.976     raeburn  5973:     }
                   5974: 
                   5975:     if ($toolstatus ne '') {
                   5976:         if ($toolstatus) {
                   5977:             $access = 1;
                   5978:         } else {
                   5979:             $access = 0;
                   5980:         }
                   5981:         return $access;
                   5982:     }
                   5983: 
1.1084    raeburn  5984:     my ($is_adv,%domdef);
                   5985:     if (ref($is_advref) eq 'HASH') {
                   5986:         $is_adv = $is_advref->{'is_adv'};
                   5987:     } else {
                   5988:         $is_adv = &is_advanced_user($udom,$uname);
                   5989:     }
                   5990:     if (ref($domdefref) eq 'HASH') {
                   5991:         %domdef = %{$domdefref};
                   5992:     } else {
                   5993:         %domdef = &get_domain_defaults($udom);
                   5994:     }
1.976     raeburn  5995:     if (ref($domdef{$tool}) eq 'HASH') {
                   5996:         if ($is_adv) {
                   5997:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5998:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5999:                     $access = 1;
                   6000:                 } else {
                   6001:                     $access = 0;
                   6002:                 }
                   6003:                 return $access;
                   6004:             }
                   6005:         }
                   6006:         if ($inststatus ne '') {
                   6007:             my ($hasaccess,$hasnoaccess);
                   6008:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6009:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6010:                     if ($domdef{$tool}{$affiliation}) {
                   6011:                         $hasaccess = 1;
                   6012:                     } else {
                   6013:                         $hasnoaccess = 1;
                   6014:                     }
                   6015:                 }
                   6016:             }
                   6017:             if ($hasaccess || $hasnoaccess) {
                   6018:                 if ($hasaccess) {
                   6019:                     $access = 1;
                   6020:                 } elsif ($hasnoaccess) {
                   6021:                     $access = 0; 
                   6022:                 }
                   6023:                 return $access;
                   6024:             }
                   6025:         } else {
                   6026:             if ($domdef{$tool}{'default'} ne '') {
                   6027:                 if ($domdef{$tool}{'default'}) {
                   6028:                     $access = 1;
                   6029:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6030:                     $access = 0;
                   6031:                 }
                   6032:                 return $access;
                   6033:             }
                   6034:         }
                   6035:     } else {
1.1177    raeburn  6036:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6037:             $access = 1;
                   6038:         } else {
                   6039:             $access = 0;
                   6040:         }
1.976     raeburn  6041:         return $access;
                   6042:     }
                   6043: }
                   6044: 
1.1050    raeburn  6045: sub is_course_owner {
                   6046:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6047:     if (($udom eq '') || ($uname eq '')) {
                   6048:         $udom = $env{'user.domain'};
                   6049:         $uname = $env{'user.name'};
                   6050:     }
                   6051:     unless (($udom eq '') || ($uname eq '')) {
                   6052:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6053:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6054:                 return 1;
                   6055:             } else {
                   6056:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6057:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6058:                     return 1;
                   6059:                 }
                   6060:             }
                   6061:         }
                   6062:     }
                   6063:     return;
                   6064: }
                   6065: 
1.976     raeburn  6066: sub is_advanced_user {
                   6067:     my ($udom,$uname) = @_;
1.1085    raeburn  6068:     if ($udom ne '' && $uname ne '') {
                   6069:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6070:             if (wantarray) {
                   6071:                 return ($env{'user.adv'},$env{'user.author'});
                   6072:             } else {
                   6073:                 return $env{'user.adv'};
                   6074:             }
1.1085    raeburn  6075:         }
                   6076:     }
1.976     raeburn  6077:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6078:     my %allroles;
1.1128    raeburn  6079:     my ($is_adv,$is_author);
1.976     raeburn  6080:     foreach my $role (keys(%roleshash)) {
                   6081:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6082:         my $area = '/'.$tdomain.'/'.$trest;
                   6083:         if ($sec ne '') {
                   6084:             $area .= '/'.$sec;
                   6085:         }
                   6086:         if (($area ne '') && ($trole ne '')) {
                   6087:             my $spec=$trole.'.'.$area;
                   6088:             if ($trole =~ /^cr\//) {
                   6089:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6090:             } elsif ($trole ne 'gr') {
                   6091:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6092:             }
1.1128    raeburn  6093:             if ($trole eq 'au') {
                   6094:                 $is_author = 1;
                   6095:             }
1.976     raeburn  6096:         }
                   6097:     }
                   6098:     foreach my $role (keys(%allroles)) {
                   6099:         last if ($is_adv);
                   6100:         foreach my $item (split(/:/,$allroles{$role})) {
                   6101:             if ($item ne '') {
                   6102:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6103:                 if ($privilege eq 'adv') {
                   6104:                     $is_adv = 1;
                   6105:                     last;
                   6106:                 }
                   6107:             }
                   6108:         }
                   6109:     }
1.1128    raeburn  6110:     if (wantarray) {
                   6111:         return ($is_adv,$is_author);
                   6112:     }
1.976     raeburn  6113:     return $is_adv;
                   6114: }
1.798     raeburn  6115: 
1.1035    raeburn  6116: sub check_can_request {
1.1036    raeburn  6117:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6118:     my $canreq = 0;
                   6119:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6120:     my @options = ('approval','validate','autolimit');
                   6121:     my $optregex = join('|',@options);
                   6122:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6123:         foreach my $type (@{$types}) {
                   6124:             if (&usertools_access($env{'user.name'},
                   6125:                                   $env{'user.domain'},
                   6126:                                   $type,undef,'requestcourses')) {
                   6127:                 $canreq ++;
1.1036    raeburn  6128:                 if (ref($request_domains) eq 'HASH') {
                   6129:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6130:                 }
1.1035    raeburn  6131:                 if ($dom eq $env{'user.domain'}) {
                   6132:                     $can_request->{$type} = 1;
                   6133:                 }
                   6134:             }
                   6135:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6136:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6137:                 if (@curr > 0) {
1.1036    raeburn  6138:                     foreach my $item (@curr) {
                   6139:                         if (ref($request_domains) eq 'HASH') {
                   6140:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6141:                             if ($otherdom ne '') {
                   6142:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6143:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6144:                                         push(@{$request_domains->{$type}},$otherdom);
                   6145:                                     }
                   6146:                                 } else {
                   6147:                                     push(@{$request_domains->{$type}},$otherdom);
                   6148:                                 }
                   6149:                             }
                   6150:                         }
                   6151:                     }
                   6152:                     unless($dom eq $env{'user.domain'}) {
                   6153:                         $canreq ++;
1.1035    raeburn  6154:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6155:                             $can_request->{$type} = 1;
                   6156:                         }
                   6157:                     }
                   6158:                 }
                   6159:             }
                   6160:         }
                   6161:     }
                   6162:     return $canreq;
                   6163: }
                   6164: 
1.341     www      6165: # ---------------------------------------------- Custom access rule evaluation
                   6166: 
                   6167: sub customaccess {
                   6168:     my ($priv,$uri)=@_;
1.807     albertel 6169:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6170:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6171:     $udom = &LONCAPA::clean_domain($udom);
                   6172:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6173:     my $access=0;
1.800     albertel 6174:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6175: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6176: 	if ($type eq 'user') {
                   6177: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6178: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6179: 		if ($tdom) {
                   6180: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6181: 		}
1.896     albertel 6182: 		if ($tuname) {
                   6183: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6184: 		}
                   6185: 		$access=($effect eq 'allow');
                   6186: 		last;
                   6187: 	    }
                   6188: 	} else {
                   6189: 	    if ($role) {
                   6190: 		if ($role ne $urole) { next; }
                   6191: 	    }
                   6192: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6193: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6194: 		if ($tdom) {
                   6195: 		    if ($tdom ne $udom) { next; }
                   6196: 		}
                   6197: 		if ($tcrs) {
                   6198: 		    if ($tcrs ne $ucrs) { next; }
                   6199: 		}
                   6200: 		if ($tsec) {
                   6201: 		    if ($tsec ne $usec) { next; }
                   6202: 		}
                   6203: 		$access=($effect eq 'allow');
                   6204: 		last;
                   6205: 	    }
                   6206: 	    if ($realm eq '' && $role eq '') {
                   6207: 		$access=($effect eq 'allow');
                   6208: 	    }
1.402     bowersj2 6209: 	}
1.341     www      6210:     }
                   6211:     return $access;
                   6212: }
                   6213: 
1.103     harris41 6214: # ------------------------------------------------- Check for a user privilege
1.12      www      6215: 
                   6216: sub allowed {
1.810     raeburn  6217:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6218:     my $ver_orguri=$uri;
1.439     www      6219:     $uri=&deversion($uri);
1.152     www      6220:     my $orguri=$uri;
1.52      www      6221:     $uri=&declutter($uri);
1.809     raeburn  6222: 
1.810     raeburn  6223:     if ($priv eq 'evb') {
                   6224: # Evade communication block restrictions for specified role in a course
                   6225:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6226:             return $1;
                   6227:         } else {
                   6228:             return;
                   6229:         }
                   6230:     }
                   6231: 
1.620     albertel 6232:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6233: # Free bre access to adm and meta resources
1.775     albertel 6234:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6235: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6236: 	&& ($priv eq 'bre')) {
1.14      www      6237: 	return 'F';
1.159     www      6238:     }
                   6239: 
1.545     banghart 6240: # Free bre access to user's own portfolio contents
1.714     raeburn  6241:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6242:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6243: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6244:         my %setters;
                   6245:         my ($startblock,$endblock) = 
                   6246:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6247:         if ($startblock && $endblock) {
                   6248:             return 'B';
                   6249:         } else {
                   6250:             return 'F';
                   6251:         }
1.545     banghart 6252:     }
                   6253: 
1.762     raeburn  6254: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6255:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6256:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6257:         if (exists($env{'request.course.id'})) {
                   6258:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6259:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6260:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6261:                 my $courseprivid=$env{'request.course.id'};
                   6262:                 $courseprivid=~s/\_/\//;
                   6263:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6264:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6265:                     return $1; 
1.762     raeburn  6266:                 } else {
                   6267:                     if ($env{'request.course.sec'}) {
                   6268:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6269:                     }
                   6270:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6271:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6272:                         return $2;
                   6273:                     }
1.714     raeburn  6274:                 }
                   6275:             }
                   6276:         }
                   6277:     }
                   6278: 
1.159     www      6279: # Free bre to public access
                   6280: 
                   6281:     if ($priv eq 'bre') {
1.238     www      6282:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6283: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6284:            return 'F'; 
                   6285:         }
1.238     www      6286:         if ($copyright eq 'priv') {
                   6287:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6288: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6289: 		return '';
                   6290:             }
                   6291:         }
                   6292:         if ($copyright eq 'domain') {
                   6293:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6294: 	    unless (($env{'user.domain'} eq $1) ||
                   6295:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6296: 		return '';
                   6297:             }
1.262     matthew  6298:         }
1.620     albertel 6299:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6300:             # Library role, so allow browsing of resources in this domain.
                   6301:             return 'F';
1.238     www      6302:         }
1.341     www      6303:         if ($copyright eq 'custom') {
                   6304: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6305:         }
1.14      www      6306:     }
1.264     matthew  6307:     # Domain coordinator is trying to create a course
1.620     albertel 6308:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6309:         # uri is the requested domain in this case.
                   6310:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6311:         # a role of dc for the domain in question.
1.620     albertel 6312:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6313:     }
1.29      www      6314: 
1.52      www      6315:     my $thisallowed='';
                   6316:     my $statecond=0;
                   6317:     my $courseprivid='';
                   6318: 
1.1039    raeburn  6319:     my $ownaccess;
1.1043    raeburn  6320:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6321:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6322:         if ($uri eq '') {
                   6323:             $ownaccess = 1;
                   6324:         } else {
                   6325:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6326:                 my $udom = $env{'user.domain'};
                   6327:                 my $uname = $env{'user.name'};
                   6328:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6329:                     $ownaccess = 1;
1.1040    raeburn  6330:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6331:                     unless ($uri =~ m{\.\./}) {
                   6332:                         $ownaccess = 1;
                   6333:                     }
                   6334:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6335:                     my $now = time;
                   6336:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6337:                         my $adom = $1;
                   6338:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6339:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6340:                                 my ($start,$end) = split('.',$env{$key});
                   6341:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6342:                                     $ownaccess = 1;
                   6343:                                     last;
                   6344:                                 }
                   6345:                             }
                   6346:                         }
                   6347:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6348:                         my $adom = $1;
                   6349:                         my $aname = $2;
1.1042    raeburn  6350:                         foreach my $role ('ca','aa') { 
                   6351:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6352:                                 my ($start,$end) =
                   6353:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6354:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6355:                                     $ownaccess = 1;
                   6356:                                     last;
                   6357:                                 }
1.1039    raeburn  6358:                             }
                   6359:                         }
                   6360:                     }
                   6361:                 }
                   6362:             }
                   6363:         }
                   6364:     }
                   6365: 
1.52      www      6366: # Course
                   6367: 
1.620     albertel 6368:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6369:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6370:             $thisallowed.=$1;
                   6371:         }
1.52      www      6372:     }
1.29      www      6373: 
1.52      www      6374: # Domain
                   6375: 
1.620     albertel 6376:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6377:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6378:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6379:             $thisallowed.=$1;
                   6380:         }
1.12      www      6381:     }
1.52      www      6382: 
1.1141    raeburn  6383: # User who is not author or co-author might still be able to edit
                   6384: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6385:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6386:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6387:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6388:             $thisallowed.=$1;
                   6389:         }
                   6390:     }
                   6391: 
1.52      www      6392: # Course: uri itself is a course
1.66      www      6393:     my $courseuri=$uri;
                   6394:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6395:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6396: 
1.620     albertel 6397:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6398:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6399:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6400:             $thisallowed.=$1;
                   6401:         }
1.12      www      6402:     }
1.29      www      6403: 
1.665     albertel 6404: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6405: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6406:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6407: 	$thisallowed='';
1.671     raeburn  6408:         my ($match)=&is_on_map($uri);
                   6409:         if ($match) {
                   6410:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6411:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6412:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6413:                 if (@blockers > 0) {
                   6414:                     $thisallowed = 'B';
                   6415:                 } else {
                   6416:                     $thisallowed.=$1;
                   6417:                 }
1.671     raeburn  6418:             }
                   6419:         } else {
1.705     albertel 6420:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6421:             if ($refuri) {
                   6422:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6423:                     $thisallowed='F';
1.671     raeburn  6424:                 } else {
                   6425:                     $refuri=&declutter($refuri);
                   6426:                     my ($match) = &is_on_map($refuri);
                   6427:                     if ($match) {
1.1162    raeburn  6428:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6429:                         if (@blockers > 0) {
                   6430:                             $thisallowed = 'B';
                   6431:                         } else {
                   6432:                             $thisallowed='F';
                   6433:                         }
1.671     raeburn  6434:                     }
1.669     raeburn  6435:                 }
1.671     raeburn  6436:             }
                   6437:         }
1.314     www      6438:     }
1.492     albertel 6439: 
1.766     albertel 6440:     if ($priv eq 'bre'
                   6441: 	&& $thisallowed ne 'F' 
                   6442: 	&& $thisallowed ne '2'
                   6443: 	&& &is_portfolio_url($uri)) {
                   6444: 	$thisallowed = &portfolio_access($uri);
                   6445:     }
                   6446:     
1.52      www      6447: # Full access at system, domain or course-wide level? Exit.
1.29      www      6448:     if ($thisallowed=~/F/) {
                   6449: 	return 'F';
                   6450:     }
                   6451: 
1.52      www      6452: # If this is generating or modifying users, exit with special codes
1.29      www      6453: 
1.643     www      6454:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6455: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6456: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6457: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6458: 	    unless ($auname) { return $thisallowed; }
                   6459: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6460: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6461: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6462: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6463: 	}
1.52      www      6464: 	return $thisallowed;
                   6465:     }
                   6466: #
1.103     harris41 6467: # Gathered so far: system, domain and course wide privileges
1.52      www      6468: #
                   6469: # Course: See if uri or referer is an individual resource that is part of 
                   6470: # the course
                   6471: 
1.620     albertel 6472:     if ($env{'request.course.id'}) {
1.232     www      6473: 
1.620     albertel 6474:        $courseprivid=$env{'request.course.id'};
                   6475:        if ($env{'request.course.sec'}) {
                   6476:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6477:        }
                   6478:        $courseprivid=~s/\_/\//;
                   6479:        my $checkreferer=1;
1.232     www      6480:        my ($match,$cond)=&is_on_map($uri);
                   6481:        if ($match) {
                   6482:            $statecond=$cond;
1.620     albertel 6483:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6484:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6485:                my $value = $1;
                   6486:                if ($priv eq 'bre') {
                   6487:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6488:                    if (@blockers > 0) {
                   6489:                        $thisallowed = 'B';
                   6490:                    } else {
                   6491:                        $thisallowed.=$value;
                   6492:                    }
                   6493:                } else {
                   6494:                    $thisallowed.=$value;
                   6495:                }
1.52      www      6496:                $checkreferer=0;
                   6497:            }
1.29      www      6498:        }
1.83      www      6499:        
1.148     www      6500:        if ($checkreferer) {
1.620     albertel 6501: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6502:             unless ($refuri) {
1.800     albertel 6503:                 foreach my $key (keys(%env)) {
                   6504: 		    if ($key=~/^httpref\..*\*/) {
                   6505: 			my $pattern=$key;
1.156     www      6506:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6507:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6508:                         $pattern=~s/\//\\\//g;
1.152     www      6509:                         if ($orguri=~/$pattern/) {
1.800     albertel 6510: 			    $refuri=$env{$key};
1.148     www      6511:                         }
                   6512:                     }
1.191     harris41 6513:                 }
1.148     www      6514:             }
1.232     www      6515: 
1.148     www      6516:          if ($refuri) { 
1.152     www      6517: 	  $refuri=&declutter($refuri);
1.232     www      6518:           my ($match,$cond)=&is_on_map($refuri);
                   6519:             if ($match) {
                   6520:               my $refstatecond=$cond;
1.620     albertel 6521:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6522:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6523:                   my $value = $1;
                   6524:                   if ($priv eq 'bre') {
                   6525:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6526:                       if (@blockers > 0) {
                   6527:                           $thisallowed = 'B';
                   6528:                       } else {
                   6529:                           $thisallowed.=$value;
                   6530:                       }
                   6531:                   } else {
                   6532:                       $thisallowed.=$value;
                   6533:                   }
1.53      www      6534:                   $uri=$refuri;
                   6535:                   $statecond=$refstatecond;
1.52      www      6536:               }
                   6537:           }
1.148     www      6538:         }
1.29      www      6539:        }
1.52      www      6540:    }
1.29      www      6541: 
1.52      www      6542: #
1.103     harris41 6543: # Gathered now: all privileges that could apply, and condition number
1.52      www      6544: # 
                   6545: #
                   6546: # Full or no access?
                   6547: #
1.29      www      6548: 
1.52      www      6549:     if ($thisallowed=~/F/) {
                   6550: 	return 'F';
                   6551:     }
1.29      www      6552: 
1.52      www      6553:     unless ($thisallowed) {
                   6554:         return '';
                   6555:     }
1.29      www      6556: 
1.52      www      6557: # Restrictions exist, deal with them
                   6558: #
                   6559: #   C:according to course preferences
                   6560: #   R:according to resource settings
                   6561: #   L:unless locked
                   6562: #   X:according to user session state
                   6563: #
                   6564: 
                   6565: # Possibly locked functionality, check all courses
1.54      www      6566: # Locks might take effect only after 10 minutes cache expiration for other
                   6567: # courses, and 2 minutes for current course
1.52      www      6568: 
                   6569:     my $envkey;
                   6570:     if ($thisallowed=~/L/) {
1.1000    raeburn  6571:         foreach $envkey (keys(%env)) {
1.54      www      6572:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6573:                my $courseid=$2;
                   6574:                my $roleid=$1.'.'.$2;
1.92      www      6575:                $courseid=~s/^\///;
1.54      www      6576:                my $expiretime=600;
1.620     albertel 6577:                if ($env{'request.role'} eq $roleid) {
1.54      www      6578: 		  $expiretime=120;
                   6579:                }
                   6580: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6581:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6582:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6583: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6584:                }
1.620     albertel 6585:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6586:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6587: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6588:                        &log($env{'user.domain'},$env{'user.name'},
                   6589:                             $env{'user.home'},
1.57      www      6590:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6591:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6592:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6593: 		       return '';
                   6594:                    }
                   6595:                }
1.620     albertel 6596:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6597:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6598: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6599:                        &log($env{'user.domain'},$env{'user.name'},
                   6600:                             $env{'user.home'},
1.57      www      6601:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6602:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6603:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6604: 		       return '';
                   6605:                    }
                   6606:                }
                   6607: 	   }
1.29      www      6608:        }
1.52      www      6609:     }
                   6610:    
                   6611: #
                   6612: # Rest of the restrictions depend on selected course
                   6613: #
                   6614: 
1.620     albertel 6615:     unless ($env{'request.course.id'}) {
1.766     albertel 6616: 	if ($thisallowed eq 'A') {
                   6617: 	    return 'A';
1.814     raeburn  6618:         } elsif ($thisallowed eq 'B') {
                   6619:             return 'B';
1.766     albertel 6620: 	} else {
                   6621: 	    return '1';
                   6622: 	}
1.52      www      6623:     }
1.29      www      6624: 
1.52      www      6625: #
                   6626: # Now user is definitely in a course
                   6627: #
1.53      www      6628: 
                   6629: 
                   6630: # Course preferences
                   6631: 
                   6632:    if ($thisallowed=~/C/) {
1.620     albertel 6633:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6634:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6635:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6636: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6637: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6638: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6639: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6640: 			$env{'request.course.id'});
                   6641: 	   }
1.237     www      6642:            return '';
                   6643:        }
                   6644: 
1.620     albertel 6645:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6646: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6647: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6648: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6649: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6650: 			$env{'request.course.id'});
                   6651: 	   }
1.54      www      6652:            return '';
                   6653:        }
1.53      www      6654:    }
                   6655: 
                   6656: # Resource preferences
                   6657: 
                   6658:    if ($thisallowed=~/R/) {
1.620     albertel 6659:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6660:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6661: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6662: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6663: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6664: 	   }
                   6665: 	   return '';
1.54      www      6666:        }
1.53      www      6667:    }
1.30      www      6668: 
1.246     www      6669: # Restricted by state or randomout?
1.30      www      6670: 
1.52      www      6671:    if ($thisallowed=~/X/) {
1.620     albertel 6672:       if ($env{'acc.randomout'}) {
1.579     albertel 6673: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6674:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6675:             return ''; 
                   6676:          }
1.247     www      6677:       }
                   6678:       if (&condval($statecond)) {
1.52      www      6679: 	 return '2';
                   6680:       } else {
                   6681:          return '';
                   6682:       }
                   6683:    }
1.30      www      6684: 
1.766     albertel 6685:     if ($thisallowed eq 'A') {
                   6686: 	return 'A';
1.814     raeburn  6687:     } elsif ($thisallowed eq 'B') {
                   6688:         return 'B';
1.766     albertel 6689:     }
1.52      www      6690:    return 'F';
1.232     www      6691: }
1.1162    raeburn  6692: 
1.1192    raeburn  6693: # ------------------------------------------- Check construction space access
                   6694: 
                   6695: sub constructaccess {
                   6696:     my ($url,$setpriv)=@_;
                   6697: 
                   6698: # We do not allow editing of previous versions of files
                   6699:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6700: 
                   6701: # Get username and domain from URL
                   6702:     my ($ownername,$ownerdomain,$ownerhome);
                   6703: 
                   6704:     ($ownerdomain,$ownername) =
                   6705:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6706: 
                   6707: # The URL does not really point to any authorspace, forget it
                   6708:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6709: 
                   6710: # Now we need to see if the user has access to the authorspace of
                   6711: # $ownername at $ownerdomain
                   6712: 
                   6713:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6714: # Real author for this?
                   6715:        $ownerhome = $env{'user.home'};
                   6716:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6717:           return ($ownername,$ownerdomain,$ownerhome);
                   6718:        }
                   6719:     } else {
                   6720: # Co-author for this?
                   6721:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6722:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6723:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6724:             return ($ownername,$ownerdomain,$ownerhome);
                   6725:         }
                   6726:     }
                   6727: 
                   6728: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6729: # we might as well leave
                   6730:    unless ($setpriv) { return ''; }
                   6731: 
                   6732: # Backdoor access?
                   6733:     my $allowed=&allowed('eco',$ownerdomain);
                   6734: # Nope
                   6735:     unless ($allowed) { return ''; }
                   6736: # Looks like we may have access, but could be locked by the owner of the construction space
                   6737:     if ($allowed eq 'U') {
                   6738:         my %blocked=&get('environment',['domcoord.author'],
                   6739:                          $ownerdomain,$ownername);
                   6740: # Is blocked by owner
                   6741:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6742:     }
                   6743:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6744: # Grant temporary access
                   6745:         my $then=$env{'user.login.time'};
                   6746:         my $update==$env{'user.update.time'};
                   6747:         if (!$update) { $update = $then; }
                   6748:         my $refresh=$env{'user.refresh.time'};
                   6749:         if (!$refresh) { $refresh = $update; }
                   6750:         my $now = time;
                   6751:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6752:                            $now,'ca','constructaccess');
                   6753:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6754:         return($ownername,$ownerdomain,$ownerhome);
                   6755:     }
                   6756: # No business here
                   6757:     return '';
                   6758: }
                   6759: 
1.1162    raeburn  6760: sub get_comm_blocks {
                   6761:     my ($cdom,$cnum) = @_;
                   6762:     if ($cdom eq '' || $cnum eq '') {
                   6763:         return unless ($env{'request.course.id'});
                   6764:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6765:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6766:     }
                   6767:     my %commblocks;
                   6768:     my $hashid=$cdom.'_'.$cnum;
                   6769:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6770:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6771:         %commblocks = %{$blocksref};
                   6772:     } else {
                   6773:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6774:         my $cachetime = 600;
                   6775:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6776:     }
                   6777:     return %commblocks;
                   6778: }
                   6779: 
                   6780: sub has_comm_blocking {
                   6781:     my ($priv,$symb,$uri,$blocks) = @_;
                   6782:     return unless ($env{'request.course.id'});
                   6783:     return unless ($priv eq 'bre');
                   6784:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6785:     my %commblocks;
                   6786:     if (ref($blocks) eq 'HASH') {
                   6787:         %commblocks = %{$blocks};
                   6788:     } else {
                   6789:         %commblocks = &get_comm_blocks();
                   6790:     }
                   6791:     return unless (keys(%commblocks) > 0);
                   6792:     if (!$symb) { $symb=&symbread($uri,1); }
                   6793:     my ($map,$resid,undef)=&decode_symb($symb);
                   6794:     my %tocheck = (
                   6795:                     maps      => $map,
                   6796:                     resources => $symb,
                   6797:                   );
                   6798:     my @blockers;
                   6799:     my $now = time;
1.1163    raeburn  6800:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6801:     foreach my $block (keys(%commblocks)) {
                   6802:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6803:             my ($start,$end) = ($1,$2);
                   6804:             if ($start <= $now && $end >= $now) {
                   6805:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6806:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6807:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6808:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6809:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6810:                                     push(@blockers,$block);
                   6811:                                 }
                   6812:                             }
                   6813:                         }
                   6814:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6815:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6816:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6817:                                     push(@blockers,$block);
                   6818:                                 }
                   6819:                             }
                   6820:                         }
                   6821:                     }
                   6822:                 }
                   6823:             }
                   6824:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6825:             my $item = $1;
1.1163    raeburn  6826:             my @to_test;
1.1162    raeburn  6827:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6828:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6829:                     my $check_interval;
                   6830:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6831:                         my @interval;
                   6832:                         my $type = 'map';
                   6833:                         if ($item eq 'course') {
                   6834:                             $type = 'course';
                   6835:                             @interval=&EXT("resource.0.interval");
                   6836:                         } else {
                   6837:                             if ($item =~ /___\d+___/) {
                   6838:                                 $type = 'resource';
                   6839:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6840:                                 if (ref($navmap)) {                        
                   6841:                                     my $res = $navmap->getBySymb($item); 
                   6842:                                     push(@to_test,$res);
                   6843:                                 }
1.1162    raeburn  6844:                             } else {
                   6845:                                 my $mapsymb = &symbread($item,1);
                   6846:                                 if ($mapsymb) {
                   6847:                                     if (ref($navmap)) {
                   6848:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6849:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6850:                                         foreach my $res (@to_test) {
1.1162    raeburn  6851:                                             my $symb = $res->symb();
                   6852:                                             next if ($symb eq $mapsymb);
                   6853:                                             if ($symb ne '') {
                   6854:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6855:                                                 last;
                   6856:                                             }
                   6857:                                         }
                   6858:                                     }
                   6859:                                 }
                   6860:                             }
                   6861:                         }
                   6862:                         if ($interval[0] =~ /\d+/) {
                   6863:                             my $first_access;
                   6864:                             if ($type eq 'resource') {
                   6865:                                 $first_access=&get_first_access($interval[1],$item);
                   6866:                             } elsif ($type eq 'map') {
                   6867:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6868:                             } else {
                   6869:                                 $first_access=&get_first_access($interval[1]);
                   6870:                             }
                   6871:                             if ($first_access) {
                   6872:                                 my $timesup = $first_access+$interval[0];
                   6873:                                 if ($timesup > $now) {
1.1163    raeburn  6874:                                     foreach my $res (@to_test) {
                   6875:                                         if ($res->is_problem()) {
                   6876:                                             if ($res->completable()) {
                   6877:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6878:                                                     push(@blockers,$block);
                   6879:                                                 }
                   6880:                                                 last;
                   6881:                                             }
                   6882:                                         }
1.1162    raeburn  6883:                                     }
                   6884:                                 }
                   6885:                             }
                   6886:                         }
                   6887:                     }
                   6888:                 }
                   6889:             }
                   6890:         }
                   6891:     }
                   6892:     return @blockers;
                   6893: }
                   6894: 
                   6895: sub check_docs_block {
                   6896:     my ($docsblock,$tocheck) =@_;
                   6897:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6898:         return;
                   6899:     }
                   6900:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6901:         if ($tocheck->{'maps'}) {
                   6902:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6903:                 return 1;
                   6904:             }
                   6905:         }
                   6906:     }
                   6907:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6908:         if ($tocheck->{'resources'}) {
                   6909:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6910:                 return 1;
                   6911:             }
                   6912:         }
                   6913:     }
                   6914:     return;
                   6915: }
                   6916: 
1.1133    foxr     6917: #
                   6918: #   Removes the versino from a URI and
                   6919: #   splits it in to its filename and path to the filename.
                   6920: #   Seems like File::Basename could have done this more clearly.
                   6921: #   Parameters:
                   6922: #      $uri   - input URI
                   6923: #   Returns:
                   6924: #     Two element list consisting of 
                   6925: #     $pathname  - the URI up to and excluding the trailing /
                   6926: #     $filename  - The part of the URI following the last /
                   6927: #  NOTE:
                   6928: #    Another realization of this is simply:
                   6929: #    use File::Basename;
                   6930: #    ...
                   6931: #    $uri = shift;
                   6932: #    $filename = basename($uri);
                   6933: #    $path     = dirname($uri);
                   6934: #    return ($filename, $path);
                   6935: #
                   6936: #     The implementation below is probably faster however.
                   6937: #
1.710     albertel 6938: sub split_uri_for_cond {
                   6939:     my $uri=&deversion(&declutter(shift));
                   6940:     my @uriparts=split(/\//,$uri);
                   6941:     my $filename=pop(@uriparts);
                   6942:     my $pathname=join('/',@uriparts);
                   6943:     return ($pathname,$filename);
                   6944: }
1.232     www      6945: # --------------------------------------------------- Is a resource on the map?
                   6946: 
                   6947: sub is_on_map {
1.710     albertel 6948:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6949:     #Trying to find the conditional for the file
1.620     albertel 6950:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6951: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6952:     if ($match) {
1.289     bowersj2 6953: 	return (1,$1);
                   6954:     } else {
1.434     www      6955: 	return (0,0);
1.289     bowersj2 6956:     }
1.12      www      6957: }
                   6958: 
1.427     www      6959: # --------------------------------------------------------- Get symb from alias
                   6960: 
                   6961: sub get_symb_from_alias {
                   6962:     my $symb=shift;
                   6963:     my ($map,$resid,$url)=&decode_symb($symb);
                   6964: # Already is a symb
                   6965:     if ($url) { return $symb; }
                   6966: # Must be an alias
                   6967:     my $aliassymb='';
                   6968:     my %bighash;
1.620     albertel 6969:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6970:                             &GDBM_READER(),0640)) {
                   6971:         my $rid=$bighash{'mapalias_'.$symb};
                   6972: 	if ($rid) {
                   6973: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6974: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6975: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6976: 	}
                   6977:         untie %bighash;
                   6978:     }
                   6979:     return $aliassymb;
                   6980: }
                   6981: 
1.12      www      6982: # ----------------------------------------------------------------- Define Role
                   6983: 
                   6984: sub definerole {
                   6985:   if (allowed('mcr','/')) {
                   6986:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6987:     foreach my $role (split(':',$sysrole)) {
                   6988: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6989:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6990:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6991: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6992:                return "refused:s:$crole&$cqual"; 
                   6993:             }
                   6994:         }
1.191     harris41 6995:     }
1.800     albertel 6996:     foreach my $role (split(':',$domrole)) {
                   6997: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6998:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6999:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7000: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7001:                return "refused:d:$crole&$cqual"; 
                   7002:             }
                   7003:         }
1.191     harris41 7004:     }
1.800     albertel 7005:     foreach my $role (split(':',$courole)) {
                   7006: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7007:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7008:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7009: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7010:                return "refused:c:$crole&$cqual"; 
                   7011:             }
                   7012:         }
1.191     harris41 7013:     }
1.620     albertel 7014:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7015:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7016: 	        "rolesdef_$rolename=".
                   7017:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7018:     return reply($command,$env{'user.home'});
1.12      www      7019:   } else {
                   7020:     return 'refused';
                   7021:   }
1.105     harris41 7022: }
                   7023: 
                   7024: # ---------------- Make a metadata query against the network of library servers
                   7025: 
                   7026: sub metadata_query {
1.244     matthew  7027:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7028:     my %rhash;
1.845     albertel 7029:     my %libserv = &all_library();
1.244     matthew  7030:     my @server_list = (defined($server_array) ? @$server_array
                   7031:                                               : keys(%libserv) );
                   7032:     for my $server (@server_list) {
1.118     harris41 7033: 	unless ($custom or $customshow) {
                   7034: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7035: 	    $rhash{$server}=$reply;
                   7036: 	}
                   7037: 	else {
                   7038: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7039: 			     &escape($custom).':'.&escape($customshow),
                   7040: 			     $server);
                   7041: 	    $rhash{$server}=$reply;
                   7042: 	}
1.112     harris41 7043:     }
1.118     harris41 7044:     return \%rhash;
1.240     www      7045: }
                   7046: 
                   7047: # ----------------------------------------- Send log queries and wait for reply
                   7048: 
                   7049: sub log_query {
                   7050:     my ($uname,$udom,$query,%filters)=@_;
                   7051:     my $uhome=&homeserver($uname,$udom);
                   7052:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7053:     my $uhost=&hostname($uhome);
1.800     albertel 7054:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7055:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7056:                        $uhome);
1.479     albertel 7057:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7058:     return get_query_reply($queryid);
                   7059: }
                   7060: 
1.818     raeburn  7061: # -------------------------- Update MySQL table for portfolio file
                   7062: 
                   7063: sub update_portfolio_table {
1.821     raeburn  7064:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7065:     if ($group ne '') {
                   7066:         $file_name =~s /^\Q$group\E//;
                   7067:     }
1.818     raeburn  7068:     my $homeserver = &homeserver($uname,$udom);
                   7069:     my $queryid=
1.821     raeburn  7070:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7071:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7072:     my $reply = &get_query_reply($queryid);
                   7073:     return $reply;
                   7074: }
                   7075: 
1.899     raeburn  7076: # -------------------------- Update MySQL allusers table
                   7077: 
                   7078: sub update_allusers_table {
                   7079:     my ($uname,$udom,$names) = @_;
                   7080:     my $homeserver = &homeserver($uname,$udom);
                   7081:     my $queryid=
                   7082:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7083:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7084:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7085:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7086:                'generation='.&escape($names->{'generation'}).'%%'.
                   7087:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7088:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7089:     return;
1.899     raeburn  7090: }
                   7091: 
1.508     raeburn  7092: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7093: 
                   7094: sub fetch_enrollment_query {
1.511     raeburn  7095:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7096:     my $homeserver;
1.547     raeburn  7097:     my $maxtries = 1;
1.508     raeburn  7098:     if ($context eq 'automated') {
                   7099:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7100:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7101:     } else {
                   7102:         $homeserver = &homeserver($cnum,$dom);
                   7103:     }
1.838     albertel 7104:     my $host=&hostname($homeserver);
1.506     raeburn  7105:     my $cmd = '';
1.1000    raeburn  7106:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7107:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7108:     }
                   7109:     $cmd =~ s/%%$//;
                   7110:     $cmd = &escape($cmd);
                   7111:     my $query = 'fetchenrollment';
1.620     albertel 7112:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7113:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7114:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7115:         return 'error: '.$queryid;
                   7116:     }
1.506     raeburn  7117:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7118:     my $tries = 1;
                   7119:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7120:         $reply = &get_query_reply($queryid);
                   7121:         $tries ++;
                   7122:     }
1.526     raeburn  7123:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7124:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7125:     } else {
1.901     albertel 7126:         my @responses = split(/:/,$reply);
1.515     raeburn  7127:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7128:             foreach my $line (@responses) {
                   7129:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7130:                 $$replyref{$key} = $value;
                   7131:             }
                   7132:         } else {
1.1117    foxr     7133:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7134:             foreach my $line (@responses) {
                   7135:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7136:                 $$replyref{$key} = $value;
                   7137:                 if ($value > 0) {
1.800     albertel 7138:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7139:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7140:                         my $destname = $pathname.'/'.$filename;
                   7141:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7142:                         if ($xml_classlist =~ /^error/) {
                   7143:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7144:                         } else {
1.506     raeburn  7145:                             if ( open(FILE,">$destname") ) {
                   7146:                                 print FILE &unescape($xml_classlist);
                   7147:                                 close(FILE);
1.526     raeburn  7148:                             } else {
                   7149:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7150:                             }
                   7151:                         }
                   7152:                     }
                   7153:                 }
                   7154:             }
                   7155:         }
                   7156:         return 'ok';
                   7157:     }
                   7158:     return 'error';
                   7159: }
                   7160: 
1.242     www      7161: sub get_query_reply {
                   7162:     my $queryid=shift;
1.1117    foxr     7163:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7164:     my $reply='';
                   7165:     for (1..100) {
                   7166: 	sleep 2;
                   7167:         if (-e $replyfile.'.end') {
1.448     albertel 7168: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7169: 		$reply = join('',<$fh>);
                   7170: 		close($fh);
1.240     www      7171: 	   } else { return 'error: reply_file_error'; }
1.242     www      7172:            return &unescape($reply);
                   7173: 	}
1.240     www      7174:     }
1.242     www      7175:     return 'timeout:'.$queryid;
1.240     www      7176: }
                   7177: 
                   7178: sub courselog_query {
1.241     www      7179: #
                   7180: # possible filters:
                   7181: # url: url or symb
                   7182: # username
                   7183: # domain
                   7184: # action: view, submit, grade
                   7185: # start: timestamp
                   7186: # end: timestamp
                   7187: #
1.240     www      7188:     my (%filters)=@_;
1.620     albertel 7189:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7190:     if ($filters{'url'}) {
                   7191: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7192:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7193:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7194:     }
1.620     albertel 7195:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7196:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7197:     return &log_query($cname,$cdom,'courselog',%filters);
                   7198: }
                   7199: 
                   7200: sub userlog_query {
1.858     raeburn  7201: #
                   7202: # possible filters:
                   7203: # action: log check role
                   7204: # start: timestamp
                   7205: # end: timestamp
                   7206: #
1.240     www      7207:     my ($uname,$udom,%filters)=@_;
                   7208:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7209: }
                   7210: 
1.506     raeburn  7211: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7212: 
                   7213: sub auto_run {
1.508     raeburn  7214:     my ($cnum,$cdom) = @_;
1.876     raeburn  7215:     my $response = 0;
                   7216:     my $settings;
                   7217:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7218:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7219:         $settings = $domconfig{'autoenroll'};
                   7220:         if ($settings->{'run'} eq '1') {
                   7221:             $response = 1;
                   7222:         }
                   7223:     } else {
1.934     raeburn  7224:         my $homeserver;
                   7225:         if (&is_course($cdom,$cnum)) {
                   7226:             $homeserver = &homeserver($cnum,$cdom);
                   7227:         } else {
                   7228:             $homeserver = &domain($cdom,'primary');
                   7229:         }
                   7230:         if ($homeserver ne 'no_host') {
                   7231:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7232:         }
1.876     raeburn  7233:     }
1.506     raeburn  7234:     return $response;
                   7235: }
1.776     albertel 7236: 
1.506     raeburn  7237: sub auto_get_sections {
1.508     raeburn  7238:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7239:     my $homeserver;
                   7240:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7241:         $homeserver = &homeserver($cnum,$cdom);
                   7242:     }
                   7243:     if (!defined($homeserver)) { 
                   7244:         if ($cdom =~ /^$match_domain$/) {
                   7245:             $homeserver = &domain($cdom,'primary');
                   7246:         }
                   7247:     }
                   7248:     my @secs;
                   7249:     if (defined($homeserver)) {
                   7250:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7251:         unless ($response eq 'refused') {
                   7252:             @secs = split(/:/,$response);
                   7253:         }
1.506     raeburn  7254:     }
                   7255:     return @secs;
                   7256: }
1.776     albertel 7257: 
1.506     raeburn  7258: sub auto_new_course {
1.1099    raeburn  7259:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7260:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7261:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7262:     return $response;
                   7263: }
1.776     albertel 7264: 
1.506     raeburn  7265: sub auto_validate_courseID {
1.508     raeburn  7266:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7267:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7268:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7269:     return $response;
                   7270: }
1.776     albertel 7271: 
1.1007    raeburn  7272: sub auto_validate_instcode {
1.1020    raeburn  7273:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7274:     my ($homeserver,$response);
                   7275:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7276:         $homeserver = &homeserver($cnum,$cdom);
                   7277:     }
                   7278:     if (!defined($homeserver)) {
                   7279:         if ($cdom =~ /^$match_domain$/) {
                   7280:             $homeserver = &domain($cdom,'primary');
                   7281:         }
                   7282:     }
1.1065    raeburn  7283:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7284:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  7285:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   7286:     return ($outcome,$description);
1.1007    raeburn  7287: }
                   7288: 
1.506     raeburn  7289: sub auto_create_password {
1.873     raeburn  7290:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7291:     my ($homeserver,$response);
1.506     raeburn  7292:     my $create_passwd = 0;
                   7293:     my $authchk = '';
1.873     raeburn  7294:     if ($udom =~ /^$match_domain$/) {
                   7295:         $homeserver = &domain($udom,'primary');
                   7296:     }
                   7297:     if ($homeserver eq '') {
                   7298:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7299:             $homeserver = &homeserver($cnum,$cdom);
                   7300:         }
                   7301:     }
                   7302:     if ($homeserver eq '') {
                   7303:         $authchk = 'nodomain';
1.506     raeburn  7304:     } else {
1.873     raeburn  7305:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7306:         if ($response eq 'refused') {
                   7307:             $authchk = 'refused';
                   7308:         } else {
1.901     albertel 7309:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7310:         }
1.506     raeburn  7311:     }
                   7312:     return ($authparam,$create_passwd,$authchk);
                   7313: }
                   7314: 
1.706     raeburn  7315: sub auto_photo_permission {
                   7316:     my ($cnum,$cdom,$students) = @_;
                   7317:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7318:     my ($outcome,$perm_reqd,$conditions) = 
                   7319: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7320:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7321: 	return (undef,undef);
                   7322:     }
1.706     raeburn  7323:     return ($outcome,$perm_reqd,$conditions);
                   7324: }
                   7325: 
                   7326: sub auto_checkphotos {
                   7327:     my ($uname,$udom,$pid) = @_;
                   7328:     my $homeserver = &homeserver($uname,$udom);
                   7329:     my ($result,$resulttype);
                   7330:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7331: 				   &escape($uname).':'.&escape($pid),
                   7332: 				   $homeserver));
1.709     albertel 7333:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7334: 	return (undef,undef);
                   7335:     }
1.706     raeburn  7336:     if ($outcome) {
                   7337:         ($result,$resulttype) = split(/:/,$outcome);
                   7338:     } 
                   7339:     return ($result,$resulttype);
                   7340: }
                   7341: 
                   7342: sub auto_photochoice {
                   7343:     my ($cnum,$cdom) = @_;
                   7344:     my $homeserver = &homeserver($cnum,$cdom);
                   7345:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7346: 						       &escape($cdom),
                   7347: 						       $homeserver)));
1.709     albertel 7348:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7349: 	return (undef,undef);
                   7350:     }
1.706     raeburn  7351:     return ($update,$comment);
                   7352: }
                   7353: 
                   7354: sub auto_photoupdate {
                   7355:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7356:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7357:     my $host=&hostname($homeserver);
1.706     raeburn  7358:     my $cmd = '';
                   7359:     my $maxtries = 1;
1.800     albertel 7360:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7361:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7362:     }
                   7363:     $cmd =~ s/%%$//;
                   7364:     $cmd = &escape($cmd);
                   7365:     my $query = 'institutionalphotos';
                   7366:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7367:     unless ($queryid=~/^\Q$host\E\_/) {
                   7368:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7369:         return 'error: '.$queryid;
                   7370:     }
                   7371:     my $reply = &get_query_reply($queryid);
                   7372:     my $tries = 1;
                   7373:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7374:         $reply = &get_query_reply($queryid);
                   7375:         $tries ++;
                   7376:     }
                   7377:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7378:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7379:     } else {
                   7380:         my @responses = split(/:/,$reply);
                   7381:         my $outcome = shift(@responses); 
                   7382:         foreach my $item (@responses) {
                   7383:             my ($key,$value) = split(/=/,$item);
                   7384:             $$photo{$key} = $value;
                   7385:         }
                   7386:         return $outcome;
                   7387:     }
                   7388:     return 'error';
                   7389: }
                   7390: 
1.521     raeburn  7391: sub auto_instcode_format {
1.793     albertel 7392:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7393: 	$cat_order) = @_;
1.521     raeburn  7394:     my $courses = '';
1.772     raeburn  7395:     my @homeservers;
1.521     raeburn  7396:     if ($caller eq 'global') {
1.841     albertel 7397: 	my %servers = &get_servers($codedom,'library');
                   7398: 	foreach my $tryserver (keys(%servers)) {
                   7399: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7400: 		push(@homeservers,$tryserver);
                   7401: 	    }
1.584     raeburn  7402:         }
1.1022    raeburn  7403:     } elsif ($caller eq 'requests') {
                   7404:         if ($codedom =~ /^$match_domain$/) {
                   7405:             my $chome = &domain($codedom,'primary');
                   7406:             unless ($chome eq 'no_host') {
                   7407:                 push(@homeservers,$chome);
                   7408:             }
                   7409:         }
1.521     raeburn  7410:     } else {
1.772     raeburn  7411:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7412:     }
1.793     albertel 7413:     foreach my $code (keys(%{$instcodes})) {
                   7414:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7415:     }
                   7416:     chop($courses);
1.772     raeburn  7417:     my $ok_response = 0;
                   7418:     my $response;
                   7419:     while (@homeservers > 0 && $ok_response == 0) {
                   7420:         my $server = shift(@homeservers); 
                   7421:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7422:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7423:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7424: 		split(/:/,$response);
1.772     raeburn  7425:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7426:             push(@{$codetitles},&str2array($codetitles_str));
                   7427:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7428:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7429:             $ok_response = 1;
                   7430:         }
                   7431:     }
                   7432:     if ($ok_response) {
1.521     raeburn  7433:         return 'ok';
1.772     raeburn  7434:     } else {
                   7435:         return $response;
1.521     raeburn  7436:     }
                   7437: }
                   7438: 
1.792     raeburn  7439: sub auto_instcode_defaults {
                   7440:     my ($domain,$returnhash,$code_order) = @_;
                   7441:     my @homeservers;
1.841     albertel 7442: 
                   7443:     my %servers = &get_servers($domain,'library');
                   7444:     foreach my $tryserver (keys(%servers)) {
                   7445: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7446: 	    push(@homeservers,$tryserver);
                   7447: 	}
1.792     raeburn  7448:     }
1.841     albertel 7449: 
1.792     raeburn  7450:     my $response;
1.841     albertel 7451:     foreach my $server (@homeservers) {
1.792     raeburn  7452:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7453:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7454: 	
                   7455: 	foreach my $pair (split(/\&/,$response)) {
                   7456: 	    my ($name,$value)=split(/\=/,$pair);
                   7457: 	    if ($name eq 'code_order') {
                   7458: 		@{$code_order} = split(/\&/,&unescape($value));
                   7459: 	    } else {
                   7460: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7461: 	    }
                   7462: 	}
                   7463: 	return 'ok';
1.792     raeburn  7464:     }
1.841     albertel 7465: 
                   7466:     return $response;
1.1003    raeburn  7467: }
                   7468: 
                   7469: sub auto_possible_instcodes {
1.1007    raeburn  7470:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7471:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7472:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7473:         return;
                   7474:     }
1.1003    raeburn  7475:     my (@homeservers,$uhome);
                   7476:     if (defined(&domain($domain,'primary'))) {
                   7477:         $uhome=&domain($domain,'primary');
                   7478:         push(@homeservers,&domain($domain,'primary'));
                   7479:     } else {
                   7480:         my %servers = &get_servers($domain,'library');
                   7481:         foreach my $tryserver (keys(%servers)) {
                   7482:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7483:                 push(@homeservers,$tryserver);
                   7484:             }
                   7485:         }
                   7486:     }
                   7487:     my $response;
                   7488:     foreach my $server (@homeservers) {
                   7489:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7490:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7491:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7492:             split(':',$response);
                   7493:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7494:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7495:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7496:             my ($name,$value)=split('=',$item);
                   7497:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7498:         }
                   7499:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7500:             my ($name,$value)=split('=',$item);
                   7501:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7502:         }
                   7503:         return 'ok';
                   7504:     }
                   7505:     return $response;
                   7506: }
1.792     raeburn  7507: 
1.1010    raeburn  7508: sub auto_courserequest_checks {
                   7509:     my ($dom) = @_;
1.1020    raeburn  7510:     my ($homeserver,%validations);
                   7511:     if ($dom =~ /^$match_domain$/) {
                   7512:         $homeserver = &domain($dom,'primary');
                   7513:     }
                   7514:     unless ($homeserver eq 'no_host') {
                   7515:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7516:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7517:             my @items = split(/&/,$response);
                   7518:             foreach my $item (@items) {
                   7519:                 my ($key,$value) = split('=',$item);
                   7520:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7521:             }
                   7522:         }
                   7523:     }
1.1010    raeburn  7524:     return %validations; 
                   7525: }
                   7526: 
1.1020    raeburn  7527: sub auto_courserequest_validation {
                   7528:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7529:     my ($homeserver,$response);
                   7530:     if ($dom =~ /^$match_domain$/) {
                   7531:         $homeserver = &domain($dom,'primary');
                   7532:     }
                   7533:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7534:           
1.1020    raeburn  7535:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7536:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7537:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7538:                                     $homeserver));
                   7539:     }
                   7540:     return $response;
                   7541: }
                   7542: 
1.777     albertel 7543: sub auto_validate_class_sec {
1.918     raeburn  7544:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7545:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7546:     my $ownerlist;
                   7547:     if (ref($owners) eq 'ARRAY') {
                   7548:         $ownerlist = join(',',@{$owners});
                   7549:     } else {
                   7550:         $ownerlist = $owners;
                   7551:     }
1.773     raeburn  7552:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7553:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7554:     return $response;
                   7555: }
                   7556: 
1.679     raeburn  7557: # ------------------------------------------------------- Course Group routines
                   7558: 
                   7559: sub get_coursegroups {
1.809     raeburn  7560:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7561:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7562: }
                   7563: 
1.679     raeburn  7564: sub modify_coursegroup {
                   7565:     my ($cdom,$cnum,$groupsettings) = @_;
                   7566:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7567: }
                   7568: 
1.809     raeburn  7569: sub toggle_coursegroup_status {
                   7570:     my ($cdom,$cnum,$group,$action) = @_;
                   7571:     my ($from_namespace,$to_namespace);
                   7572:     if ($action eq 'delete') {
                   7573:         $from_namespace = 'coursegroups';
                   7574:         $to_namespace = 'deleted_groups';
                   7575:     } else {
                   7576:         $from_namespace = 'deleted_groups';
                   7577:         $to_namespace = 'coursegroups';
                   7578:     }
                   7579:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7580:     if (my $tmp = &error(%curr_group)) {
                   7581:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7582:         return ('read error',$tmp);
                   7583:     } else {
                   7584:         my %savedsettings = %curr_group; 
1.809     raeburn  7585:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7586:         my $deloutcome;
                   7587:         if ($result eq 'ok') {
1.809     raeburn  7588:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7589:         } else {
                   7590:             return ('write error',$result);
                   7591:         }
                   7592:         if ($deloutcome eq 'ok') {
                   7593:             return 'ok';
                   7594:         } else {
                   7595:             return ('delete error',$deloutcome);
                   7596:         }
                   7597:     }
                   7598: }
                   7599: 
1.679     raeburn  7600: sub modify_group_roles {
1.957     raeburn  7601:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7602:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7603:     my $role = 'gr/'.&escape($userprivs);
                   7604:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7605:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7606:     if ($result eq 'ok') {
                   7607:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7608:     }
1.679     raeburn  7609:     return $result;
                   7610: }
                   7611: 
                   7612: sub modify_coursegroup_membership {
                   7613:     my ($cdom,$cnum,$membership) = @_;
                   7614:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7615:     return $result;
                   7616: }
                   7617: 
1.682     raeburn  7618: sub get_active_groups {
                   7619:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7620:     my $now = time;
                   7621:     my %groups = ();
                   7622:     foreach my $key (keys(%env)) {
1.811     albertel 7623:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7624:             my ($start,$end) = split(/\./,$env{$key});
                   7625:             if (($end!=0) && ($end<$now)) { next; }
                   7626:             if (($start!=0) && ($start>$now)) { next; }
                   7627:             if ($1 eq $cdom && $2 eq $cnum) {
                   7628:                 $groups{$3} = $env{$key} ;
                   7629:             }
                   7630:         }
                   7631:     }
                   7632:     return %groups;
                   7633: }
                   7634: 
1.683     raeburn  7635: sub get_group_membership {
                   7636:     my ($cdom,$cnum,$group) = @_;
                   7637:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7638: }
                   7639: 
                   7640: sub get_users_groups {
                   7641:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7642:     my @usersgroups;
1.683     raeburn  7643:     my $cachetime=1800;
                   7644: 
                   7645:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7646:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7647:     if (defined($cached)) {
1.734     albertel 7648:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7649:     } else {  
                   7650:         $grouplist = '';
1.816     raeburn  7651:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7652:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7653:         my $access_end = $env{'course.'.$courseid.
                   7654:                               '.default_enrollment_end_date'};
                   7655:         my $now = time;
                   7656:         foreach my $key (keys(%roleshash)) {
                   7657:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7658:                 my $group = $1;
                   7659:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7660:                     my $start = $2;
                   7661:                     my $end = $1;
                   7662:                     if ($start == -1) { next; } # deleted from group
                   7663:                     if (($start!=0) && ($start>$now)) { next; }
                   7664:                     if (($end!=0) && ($end<$now)) {
                   7665:                         if ($access_end && $access_end < $now) {
                   7666:                             if ($access_end - $end < 86400) {
                   7667:                                 push(@usersgroups,$group);
1.733     raeburn  7668:                             }
                   7669:                         }
1.817     raeburn  7670:                         next;
1.733     raeburn  7671:                     }
1.817     raeburn  7672:                     push(@usersgroups,$group);
1.683     raeburn  7673:                 }
                   7674:             }
                   7675:         }
1.817     raeburn  7676:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7677:         $grouplist = join(':',@usersgroups);
                   7678:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7679:     }
1.733     raeburn  7680:     return @usersgroups;
1.683     raeburn  7681: }
                   7682: 
                   7683: sub devalidate_getgroups_cache {
                   7684:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7685:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7686: 
1.683     raeburn  7687:     my $hashid="$udom:$uname:$courseid";
                   7688:     &devalidate_cache_new('getgroups',$hashid);
                   7689: }
                   7690: 
1.12      www      7691: # ------------------------------------------------------------------ Plain Text
                   7692: 
                   7693: sub plaintext {
1.988     raeburn  7694:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7695:     if ($short =~ m{^cr/}) {
1.758     albertel 7696: 	return (split('/',$short))[-1];
                   7697:     }
1.742     raeburn  7698:     if (!defined($cid)) {
                   7699:         $cid = $env{'request.course.id'};
                   7700:     }
                   7701:     my %rolenames = (
1.1008    raeburn  7702:                       Course    => 'std',
                   7703:                       Community => 'alt1',
1.742     raeburn  7704:                     );
1.1037    raeburn  7705:     if ($cid ne '') {
                   7706:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7707:             unless ($forcedefault) {
                   7708:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7709:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7710:                 return &Apache::lonlocal::mt($roletext);
                   7711:             }
                   7712:         }
                   7713:     }
                   7714:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7715:         (defined($rolenames{$type})) && 
                   7716:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7717:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7718:     } elsif ($cid ne '') {
                   7719:         my $crstype = $env{'course.'.$cid.'.type'};
                   7720:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7721:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7722:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7723:         }
1.742     raeburn  7724:     }
1.1037    raeburn  7725:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7726: }
                   7727: 
                   7728: # ----------------------------------------------------------------- Assign Role
                   7729: 
                   7730: sub assignrole {
1.957     raeburn  7731:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7732:         $context)=@_;
1.21      www      7733:     my $mrole;
                   7734:     if ($role =~ /^cr\//) {
1.393     www      7735:         my $cwosec=$url;
1.811     albertel 7736:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7737: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7738:            my $refused = 1;
                   7739:            if ($context eq 'requestcourses') {
                   7740:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7741:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7742:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7743:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7744:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7745:                            if ($crsenv{'internal.courseowner'} eq
                   7746:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7747:                                $refused = '';
                   7748:                            }
                   7749:                        }
                   7750:                    }
                   7751:                }
                   7752:            }
                   7753:            if ($refused) {
                   7754:                &logthis('Refused custom assignrole: '.
                   7755:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7756:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7757:                return 'refused';
                   7758:            }
1.104     www      7759:         }
1.21      www      7760:         $mrole='cr';
1.678     raeburn  7761:     } elsif ($role =~ /^gr\//) {
                   7762:         my $cwogrp=$url;
1.811     albertel 7763:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7764:         unless (&allowed('mdg',$cwogrp)) {
                   7765:             &logthis('Refused group assignrole: '.
                   7766:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7767:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7768:             return 'refused';
                   7769:         }
                   7770:         $mrole='gr';
1.21      www      7771:     } else {
1.82      www      7772:         my $cwosec=$url;
1.811     albertel 7773:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7774:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7775:             my $refused;
                   7776:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7777:                 if (!(&allowed('c'.$role,$url))) {
                   7778:                     $refused = 1;
                   7779:                 }
                   7780:             } else {
                   7781:                 $refused = 1;
                   7782:             }
1.947     raeburn  7783:             if ($refused) {
1.1045    raeburn  7784:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7785:                 if (!$selfenroll && $context eq 'course') {
                   7786:                     my %crsenv;
                   7787:                     if ($role eq 'cc' || $role eq 'co') {
                   7788:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7789:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7790:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7791:                                 if ($crsenv{'internal.courseowner'} eq 
                   7792:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7793:                                     $refused = '';
                   7794:                                 }
                   7795:                             }
                   7796:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7797:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7798:                                 if ($crsenv{'internal.courseowner'} eq 
                   7799:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7800:                                     $refused = '';
                   7801:                                 }
                   7802:                             }
                   7803:                         }
                   7804:                     }
                   7805:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7806:                     $refused = '';
1.1017    raeburn  7807:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7808:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7809:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7810:                         my $wrongcc;
                   7811:                         if ($cnum =~ /^$match_community$/) {
                   7812:                             $wrongcc = 1 if ($role eq 'cc');
                   7813:                         } else {
                   7814:                             $wrongcc = 1 if ($role eq 'co');
                   7815:                         }
                   7816:                         unless ($wrongcc) {
                   7817:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7818:                             if ($crsenv{'internal.courseowner'} eq 
                   7819:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7820:                                 $refused = '';
                   7821:                             }
1.1017    raeburn  7822:                         }
                   7823:                     }
1.1183    raeburn  7824:                 } elsif ($context eq 'requestauthor') {
                   7825:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   7826:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7827:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7828:                             $refused = '';
                   7829:                         } else {
                   7830:                             my %domdefaults = &get_domain_defaults($udom);
                   7831:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7832:                                 my $checkbystatus;
                   7833:                                 if ($env{'user.adv'}) { 
                   7834:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7835:                                     if ($disposition eq 'automatic') {
                   7836:                                         $refused = '';
                   7837:                                     } elsif ($disposition eq '') {
                   7838:                                         $checkbystatus = 1;
                   7839:                                     } 
                   7840:                                 } else {
                   7841:                                     $checkbystatus = 1;
                   7842:                                 }
                   7843:                                 if ($checkbystatus) {
                   7844:                                     if ($env{'environment.inststatus'}) {
                   7845:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7846:                                         foreach my $type (@inststatuses) {
                   7847:                                             if (($type ne '') &&
                   7848:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7849:                                                 $refused = '';
                   7850:                                             }
                   7851:                                         }
                   7852:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   7853:                                         $refused = '';
                   7854:                                     }
                   7855:                                 }
                   7856:                             }
                   7857:                         }
                   7858:                     }
1.1017    raeburn  7859:                 }
                   7860:                 if ($refused) {
1.947     raeburn  7861:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7862:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7863: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7864:                     return 'refused';
                   7865:                 }
1.932     raeburn  7866:             }
1.1131    raeburn  7867:         } elsif ($role eq 'au') {
                   7868:             if ($url ne '/'.$udom.'/') {
                   7869:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7870:                          ' to assign author role for '.$uname.':'.$udom.
                   7871:                          ' in domain: '.$url.' refused (wrong domain).');
                   7872:                 return 'refused';
                   7873:             }
1.104     www      7874:         }
1.21      www      7875:         $mrole=$role;
                   7876:     }
1.620     albertel 7877:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7878:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7879:     if ($end) { $command.='_'.$end; }
1.21      www      7880:     if ($start) {
                   7881: 	if ($end) { 
1.81      www      7882:            $command.='_'.$start; 
1.21      www      7883:         } else {
1.81      www      7884:            $command.='_0_'.$start;
1.21      www      7885:         }
                   7886:     }
1.739     raeburn  7887:     my $origstart = $start;
                   7888:     my $origend = $end;
1.957     raeburn  7889:     my $delflag;
1.357     www      7890: # actually delete
                   7891:     if ($deleteflag) {
1.373     www      7892: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7893: # modify command to delete the role
1.620     albertel 7894:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7895:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7896: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7897: # set start and finish to negative values for userrolelog
                   7898:            $start=-1;
                   7899:            $end=-1;
1.957     raeburn  7900:            $delflag = 1;
1.357     www      7901:         }
                   7902:     }
                   7903: # send command
1.349     www      7904:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7905: # log new user role if status is ok
1.349     www      7906:     if ($answer eq 'ok') {
1.663     raeburn  7907: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7908: # for course roles, perform group memberships changes triggered by role change.
                   7909:         unless ($role =~ /^gr/) {
                   7910:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7911:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7912:         }
1.1184    raeburn  7913:         if (($role eq 'cc') || ($role eq 'in') ||
                   7914:             ($role eq 'ep') || ($role eq 'ad') ||
                   7915:             ($role eq 'ta') || ($role eq 'st') ||
                   7916:             ($role=~/^cr/) || ($role eq 'gr') ||
                   7917:             ($role eq 'co')) {
                   7918:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7919:                            $selfenroll,$context);
                   7920:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   7921:                  ($role eq 'au') || ($role eq 'dc')) {
                   7922:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7923:                            $context);
                   7924:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   7925:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7926:                              $context); 
                   7927:         }
1.1053    raeburn  7928:         if ($role eq 'cc') {
                   7929:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7930:         }
1.349     www      7931:     }
                   7932:     return $answer;
1.169     harris41 7933: }
                   7934: 
1.1053    raeburn  7935: sub autoupdate_coowners {
                   7936:     my ($url,$end,$start,$uname,$udom) = @_;
                   7937:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7938:     if (($cdom ne '') && ($cnum ne '')) {
                   7939:         my $now = time;
                   7940:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7941:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7942:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7943:             my $instcode = $coursehash{'internal.coursecode'};
                   7944:             if ($instcode ne '') {
1.1056    raeburn  7945:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7946:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7947:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7948:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7949:                         if ($result eq 'valid') {
                   7950:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7951:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7952:                                     push(@newcoowners,$coowner);
                   7953:                                 }
                   7954:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7955:                                     push(@newcoowners,$uname.':'.$udom);
                   7956:                                 }
                   7957:                                 @newcoowners = sort(@newcoowners);
                   7958:                             } else {
                   7959:                                 push(@newcoowners,$uname.':'.$udom);
                   7960:                             }
                   7961:                         } else {
                   7962:                             if ($coursehash{'internal.co-owners'}) {
                   7963:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7964:                                     unless ($coowner eq $uname.':'.$udom) {
                   7965:                                         push(@newcoowners,$coowner);
                   7966:                                     }
                   7967:                                 }
                   7968:                                 unless (@newcoowners > 0) {
                   7969:                                     $delcoowners = 1;
                   7970:                                     $coowners = '';
                   7971:                                 }
                   7972:                             }
                   7973:                         }
                   7974:                         if (@newcoowners || $delcoowners) {
                   7975:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7976:                                             $delcoowners,@newcoowners);
                   7977:                         }
                   7978:                     }
                   7979:                 }
                   7980:             }
                   7981:         }
                   7982:     }
                   7983: }
                   7984: 
                   7985: sub store_coowners {
                   7986:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7987:     my $cid = $cdom.'_'.$cnum;
                   7988:     my ($coowners,$delresult,$putresult);
                   7989:     if (@newcoowners) {
                   7990:         $coowners = join(',',@newcoowners);
                   7991:         my %coownershash = (
                   7992:                             'internal.co-owners' => $coowners,
                   7993:                            );
                   7994:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7995:         if ($putresult eq 'ok') {
                   7996:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7997:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7998:             }
                   7999:         }
                   8000:     }
                   8001:     if ($delcoowners) {
                   8002:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8003:         if ($delresult eq 'ok') {
                   8004:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8005:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8006:             }
                   8007:         }
                   8008:     }
                   8009:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8010:         my %crsinfo =
                   8011:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8012:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8013:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8014:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8015:         }
                   8016:     }
                   8017: }
                   8018: 
1.169     harris41 8019: # -------------------------------------------------- Modify user authentication
1.197     www      8020: # Overrides without validation
                   8021: 
1.169     harris41 8022: sub modifyuserauth {
                   8023:     my ($udom,$uname,$umode,$upass)=@_;
                   8024:     my $uhome=&homeserver($uname,$udom);
1.197     www      8025:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8026:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8027:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8028:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8029:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8030: 		     &escape($upass),$uhome);
1.620     albertel 8031:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8032:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8033:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8034:     &log($udom,,$uname,$uhome,
1.620     albertel 8035:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8036:                                      $env{'user.name'}.', '.$umode.
1.197     www      8037:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8038:     unless ($reply eq 'ok') {
1.197     www      8039:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8040: 	return 'error: '.$reply;
                   8041:     }   
1.170     harris41 8042:     return 'ok';
1.80      www      8043: }
                   8044: 
1.81      www      8045: # --------------------------------------------------------------- Modify a user
1.80      www      8046: 
1.81      www      8047: sub modifyuser {
1.206     matthew  8048:     my ($udom,    $uname, $uid,
                   8049:         $umode,   $upass, $first,
                   8050:         $middle,  $last,  $gene,
1.1058    raeburn  8051:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8052:     $udom= &LONCAPA::clean_domain($udom);
                   8053:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8054:     my $showcandelete = 'none';
                   8055:     if (ref($candelete) eq 'ARRAY') {
                   8056:         if (@{$candelete} > 0) {
                   8057:             $showcandelete = join(', ',@{$candelete});
                   8058:         }
                   8059:     }
1.81      www      8060:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8061:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8062: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8063:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8064:                                      ' desiredhome not specified'). 
1.620     albertel 8065:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8066:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8067:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8068:     my $newuser;
                   8069:     if ($uhome eq 'no_host') {
                   8070:         $newuser = 1;
                   8071:     }
1.80      www      8072: # ----------------------------------------------------------------- Create User
1.406     albertel 8073:     if (($uhome eq 'no_host') && 
                   8074: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8075:         my $unhome='';
1.844     albertel 8076:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8077:             $unhome = $desiredhome;
1.620     albertel 8078: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8079: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8080:         } else { # load balancing routine for determining $unhome
1.81      www      8081:             my $loadm=10000000;
1.841     albertel 8082: 	    my %servers = &get_servers($udom,'library');
                   8083: 	    foreach my $tryserver (keys(%servers)) {
                   8084: 		my $answer=reply('load',$tryserver);
                   8085: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8086: 		    $loadm=$answer;
                   8087: 		    $unhome=$tryserver;
                   8088: 		}
1.80      www      8089: 	    }
                   8090:         }
                   8091:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8092: 	    return 'error: unable to find a home server for '.$uname.
                   8093:                    ' in domain '.$udom;
1.80      www      8094:         }
                   8095:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8096:                          &escape($upass),$unhome);
                   8097: 	unless ($reply eq 'ok') {
                   8098:             return 'error: '.$reply;
                   8099:         }   
1.230     stredwic 8100:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8101:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8102: 	    return 'error: unable verify users home machine.';
1.80      www      8103:         }
1.209     matthew  8104:     }   # End of creation of new user
1.80      www      8105: # ---------------------------------------------------------------------- Add ID
                   8106:     if ($uid) {
                   8107:        $uid=~tr/A-Z/a-z/;
                   8108:        my %uidhash=&idrget($udom,$uname);
1.196     www      8109:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8110:          && (!$forceid)) {
1.80      www      8111: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8112: 	      return 'error: user id "'.$uid.'" does not match '.
                   8113:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8114:           }
                   8115:        } else {
                   8116: 	  &idput($udom,($uname => $uid));
                   8117:        }
                   8118:     }
                   8119: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8120:     my @tmp=&get('environment',
1.899     raeburn  8121: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8122:                     'permanentemail','inststatus'],
1.134     albertel 8123: 		   $udom,$uname);
1.1075    raeburn  8124:     my (%names,%oldnames);
1.313     matthew  8125:     if ($tmp[0] =~ m/^error:.*/) { 
                   8126:         %names=(); 
                   8127:     } else {
                   8128:         %names = @tmp;
1.1075    raeburn  8129:         %oldnames = %names;
1.313     matthew  8130:     }
1.388     www      8131: #
1.1058    raeburn  8132: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8133: # of users did not contain them), do not overwrite existing values
                   8134: # unless field is in $candelete array ref.  
                   8135: #
                   8136: 
                   8137:     my @fields = ('firstname','middlename','lastname','generation',
                   8138:                   'permanentemail','id');
                   8139:     my %newvalues;
                   8140:     if (ref($candelete) eq 'ARRAY') {
                   8141:         foreach my $field (@fields) {
                   8142:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8143:                 if ($field eq 'firstname') {
                   8144:                     $names{$field} = $first;
                   8145:                 } elsif ($field eq 'middlename') {
                   8146:                     $names{$field} = $middle;
                   8147:                 } elsif ($field eq 'lastname') {
                   8148:                     $names{$field} = $last;
                   8149:                 } elsif ($field eq 'generation') { 
                   8150:                     $names{$field} = $gene;
                   8151:                 } elsif ($field eq 'permanentemail') {
                   8152:                     $names{$field} = $email;
                   8153:                 } elsif ($field eq 'id') {
                   8154:                     $names{$field}  = $uid;
                   8155:                 }
                   8156:             }
                   8157:         }
                   8158:     }
1.388     www      8159:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8160:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8161:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8162:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8163:     if ($email) {
                   8164:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8165:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8166:     }
1.899     raeburn  8167:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8168:     if (defined($inststatus)) {
                   8169:         $names{'inststatus'} = '';
                   8170:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8171:         if (ref($usertypes) eq 'HASH') {
                   8172:             my @okstatuses; 
                   8173:             foreach my $item (split(/:/,$inststatus)) {
                   8174:                 if (defined($usertypes->{$item})) {
                   8175:                     push(@okstatuses,$item);  
                   8176:                 }
                   8177:             }
                   8178:             if (@okstatuses) {
                   8179:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8180:             }
                   8181:         }
                   8182:     }
1.1075    raeburn  8183:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8184:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8185:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8186:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8187:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8188:     } else {
                   8189:         $logmsg .= ' during self creation';
                   8190:     }
1.1075    raeburn  8191:     my $changed;
                   8192:     if ($newuser) {
                   8193:         $changed = 1;
                   8194:     } else {
                   8195:         foreach my $field (@fields) {
                   8196:             if ($names{$field} ne $oldnames{$field}) {
                   8197:                 $changed = 1;
                   8198:                 last;
                   8199:             }
                   8200:         }
                   8201:     }
                   8202:     unless ($changed) {
                   8203:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8204:         &logthis($logmsg);
                   8205:         return 'ok';
                   8206:     }
                   8207:     my $reply = &put('environment', \%names, $udom,$uname);
                   8208:     if ($reply ne 'ok') { 
                   8209:         return 'error: '.$reply;
                   8210:     }
1.1087    raeburn  8211:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8212:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8213:     }
1.1075    raeburn  8214:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8215:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8216:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8217:     &logthis($logmsg);
1.134     albertel 8218:     return 'ok';
1.80      www      8219: }
                   8220: 
1.81      www      8221: # -------------------------------------------------------------- Modify student
1.80      www      8222: 
1.81      www      8223: sub modifystudent {
                   8224:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8225:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  8226:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 8227:     if (!$cid) {
1.620     albertel 8228: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8229: 	    return 'not_in_class';
                   8230: 	}
1.80      www      8231:     }
                   8232: # --------------------------------------------------------------- Make the user
1.81      www      8233:     my $reply=&modifyuser
1.209     matthew  8234: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8235:          $desiredhome,$email,$inststatus);
1.80      www      8236:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8237:     # This will cause &modify_student_enrollment to get the uid from the
                   8238:     # students environment
                   8239:     $uid = undef if (!$forceid);
1.455     albertel 8240:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  8241: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  8242:     return $reply;
                   8243: }
                   8244: 
                   8245: sub modify_student_enrollment {
1.957     raeburn  8246:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 8247:     my ($cdom,$cnum,$chome);
                   8248:     if (!$cid) {
1.620     albertel 8249: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8250: 	    return 'not_in_class';
                   8251: 	}
1.620     albertel 8252: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8253: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8254:     } else {
                   8255: 	($cdom,$cnum)=split(/_/,$cid);
                   8256:     }
1.620     albertel 8257:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8258:     if (!$chome) {
1.457     raeburn  8259: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8260:     }
1.455     albertel 8261:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8262:     # Make sure the user exists
1.81      www      8263:     my $uhome=&homeserver($uname,$udom);
                   8264:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8265: 	return 'error: no such user';
                   8266:     }
1.297     matthew  8267:     # Get student data if we were not given enough information
                   8268:     if (!defined($first)  || $first  eq '' || 
                   8269:         !defined($last)   || $last   eq '' || 
                   8270:         !defined($uid)    || $uid    eq '' || 
                   8271:         !defined($middle) || $middle eq '' || 
                   8272:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8273:         # They did not supply us with enough data to enroll the student, so
                   8274:         # we need to pick up more information.
1.297     matthew  8275:         my %tmp = &get('environment',
1.294     matthew  8276:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8277:                        ,$udom,$uname);
                   8278: 
1.800     albertel 8279:         #foreach my $key (keys(%tmp)) {
                   8280:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8281:         #}
1.294     matthew  8282:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8283:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8284:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8285:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8286:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8287:     }
1.556     albertel 8288:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8289:     my $user = "$uname:$udom";
                   8290:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8291:     my $reply=cput('classlist',
1.1148    raeburn  8292: 		   {$user => 
1.515     raeburn  8293: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 8294: 		   $cdom,$cnum);
1.1148    raeburn  8295:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8296:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8297:     } else { 
1.81      www      8298: 	return 'error: '.$reply;
                   8299:     }
1.297     matthew  8300:     # Add student role to user
1.83      www      8301:     my $uurl='/'.$cid;
1.81      www      8302:     $uurl=~s/\_/\//g;
                   8303:     if ($usec) {
                   8304: 	$uurl.='/'.$usec;
                   8305:     }
1.1148    raeburn  8306:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8307:                              $selfenroll,$context);
                   8308:     if ($result ne 'ok') {
                   8309:         if ($old_entry{$user} ne '') {
                   8310:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8311:         } else {
                   8312:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8313:         }
                   8314:     }
                   8315:     return $result; 
1.21      www      8316: }
                   8317: 
1.556     albertel 8318: sub format_name {
                   8319:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8320:     my $name;
                   8321:     if ($first ne 'lastname') {
                   8322: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8323:     } else {
                   8324: 	if ($lastname=~/\S/) {
                   8325: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8326: 	    $name=~s/\s+,/,/;
                   8327: 	} else {
                   8328: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8329: 	}
                   8330:     }
                   8331:     $name=~s/^\s+//;
                   8332:     $name=~s/\s+$//;
                   8333:     $name=~s/\s+/ /g;
                   8334:     return $name;
                   8335: }
                   8336: 
1.84      www      8337: # ------------------------------------------------- Write to course preferences
                   8338: 
                   8339: sub writecoursepref {
                   8340:     my ($courseid,%prefs)=@_;
                   8341:     $courseid=~s/^\///;
                   8342:     $courseid=~s/\_/\//g;
                   8343:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8344:     my $chome=homeserver($cnum,$cdomain);
                   8345:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8346: 	return 'error: no such course';
                   8347:     }
                   8348:     my $cstring='';
1.800     albertel 8349:     foreach my $pref (keys(%prefs)) {
                   8350: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8351:     }
1.84      www      8352:     $cstring=~s/\&$//;
                   8353:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8354: }
                   8355: 
                   8356: # ---------------------------------------------------------- Make/modify course
                   8357: 
                   8358: sub createcourse {
1.741     raeburn  8359:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8360:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8361:     $url=&declutter($url);
                   8362:     my $cid='';
1.1028    raeburn  8363:     if ($context eq 'requestcourses') {
                   8364:         my $can_create = 0;
                   8365:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8366:         if ($udom eq $ownerdom) {
                   8367:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8368:                                   $context)) {
                   8369:                 $can_create = 1;
                   8370:             }
                   8371:         } else {
                   8372:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8373:                                            $category);
                   8374:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8375:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8376:                 if (@curr > 0) {
                   8377:                     my @options = qw(approval validate autolimit);
                   8378:                     my $optregex = join('|',@options);
                   8379:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8380:                         $can_create = 1;
                   8381:                     }
                   8382:                 }
                   8383:             }
                   8384:         }
                   8385:         if ($can_create) {
                   8386:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8387:                 unless (&allowed('ccc',$udom)) {
                   8388:                     return 'refused'; 
                   8389:                 }
1.1017    raeburn  8390:             }
                   8391:         } else {
                   8392:             return 'refused';
                   8393:         }
1.1028    raeburn  8394:     } elsif (!&allowed('ccc',$udom)) {
                   8395:         return 'refused';
1.84      www      8396:     }
1.1011    raeburn  8397: # --------------------------------------------------------------- Get Unique ID
                   8398:     my $uname;
                   8399:     if ($cnum =~ /^$match_courseid$/) {
                   8400:         my $chome=&homeserver($cnum,$udom,'true');
                   8401:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8402:             $uname = $cnum;
                   8403:         } else {
1.1038    raeburn  8404:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8405:         }
                   8406:     } else {
1.1038    raeburn  8407:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8408:     }
                   8409:     return $uname if ($uname =~ /^error/);
                   8410: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8411:     if (!defined($course_server)) {
                   8412:         if (defined(&domain($udom,'primary'))) {
                   8413:             $course_server = &domain($udom,'primary');
                   8414:         } else {
                   8415:             $course_server = $env{'user.home'}; 
                   8416:         }
                   8417:     }
                   8418:     my %host_servers =
                   8419:         &Apache::lonnet::get_servers($udom,'library');
                   8420:     unless ($host_servers{$course_server}) {
                   8421:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8422:     }
1.84      www      8423: # ------------------------------------------------------------- Make the course
                   8424:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8425:                       $course_server);
1.84      www      8426:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8427:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8428:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8429: 	return 'error: no such course';
                   8430:     }
1.271     www      8431: # ----------------------------------------------------------------- Course made
1.516     raeburn  8432: # log existence
1.1029    raeburn  8433:     my $now = time;
1.918     raeburn  8434:     my $newcourse = {
                   8435:                     $udom.'_'.$uname => {
1.921     raeburn  8436:                                      description => $description,
                   8437:                                      inst_code   => $inst_code,
                   8438:                                      owner       => $course_owner,
                   8439:                                      type        => $crstype,
1.1029    raeburn  8440:                                      creator     => $env{'user.name'}.':'.
                   8441:                                                     $env{'user.domain'},
                   8442:                                      created     => $now,
                   8443:                                      context     => $context,
1.918     raeburn  8444:                                                 },
                   8445:                     };
1.921     raeburn  8446:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8447: # set toplevel url
1.271     www      8448:     my $topurl=$url;
                   8449:     unless ($nonstandard) {
                   8450: # ------------------------------------------ For standard courses, make top url
                   8451:         my $mapurl=&clutter($url);
1.278     www      8452:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8453:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8454: <map>
                   8455: <resource id="1" type="start"></resource>
                   8456: <resource id="2" src="$mapurl"></resource>
                   8457: <resource id="3" type="finish"></resource>
                   8458: <link index="1" from="1" to="2"></link>
                   8459: <link index="2" from="2" to="3"></link>
                   8460: </map>
                   8461: ENDINITMAP
                   8462:         $topurl=&declutter(
1.638     albertel 8463:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8464:                           );
                   8465:     }
                   8466: # ----------------------------------------------------------- Write preferences
1.84      www      8467:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8468:                      ('description'              => $description,
                   8469:                       'url'                      => $topurl,
                   8470:                       'internal.creator'         => $env{'user.name'}.':'.
                   8471:                                                     $env{'user.domain'},
                   8472:                       'internal.created'         => $now,
                   8473:                       'internal.creationcontext' => $context)
                   8474:                     );
1.84      www      8475:     return '/'.$udom.'/'.$uname;
                   8476: }
                   8477: 
1.1011    raeburn  8478: # ------------------------------------------------------------------- Create ID
                   8479: sub generate_coursenum {
1.1038    raeburn  8480:     my ($udom,$crstype) = @_;
1.1011    raeburn  8481:     my $domdesc = &domain($udom);
                   8482:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8483:     my $first;
                   8484:     if ($crstype eq 'Community') {
                   8485:         $first = '0';
                   8486:     } else {
                   8487:         $first = int(1+rand(9)); 
                   8488:     } 
                   8489:     my $uname=$first.
1.1011    raeburn  8490:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8491:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8492:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8493: # ----------------------------------------------- Make sure that does not exist
                   8494:     my $uhome=&homeserver($uname,$udom,'true');
                   8495:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8496:         if ($crstype eq 'Community') {
                   8497:             $first = '0';
                   8498:         } else {
                   8499:             $first = int(1+rand(9));
                   8500:         }
                   8501:         $uname=$first.
1.1011    raeburn  8502:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8503:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8504:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8505:         $uhome=&homeserver($uname,$udom,'true');
                   8506:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8507:             return 'error: unable to generate unique course-ID';
                   8508:         }
                   8509:     }
                   8510:     return $uname;
                   8511: }
                   8512: 
1.813     albertel 8513: sub is_course {
1.1167    droeschl 8514:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8515:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8516: 
                   8517:     return unless $cdom and $cnum;
                   8518: 
                   8519:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8520:         '.');
                   8521: 
                   8522:     return unless exists($courses{$cdom.'_'.$cnum});
                   8523:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8524: }
                   8525: 
1.1015    raeburn  8526: sub store_userdata {
                   8527:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8528:     my $result;
1.1016    raeburn  8529:     if ($datakey ne '') {
1.1013    raeburn  8530:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8531:             if ($udom eq '' || $uname eq '') {
                   8532:                 $udom = $env{'user.domain'};
                   8533:                 $uname = $env{'user.name'};
                   8534:             }
                   8535:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8536:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8537:                 $result = 'error: no_host';
                   8538:             } else {
                   8539:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8540:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8541: 
                   8542:                 my $namevalue='';
                   8543:                 foreach my $key (keys(%{$storehash})) {
                   8544:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8545:                 }
                   8546:                 $namevalue=~s/\&$//;
1.1105    raeburn  8547:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8548:                                   $namevalue,$uhome);
1.1013    raeburn  8549:             }
                   8550:         } else {
                   8551:             $result = 'error: data to store was not a hash reference'; 
                   8552:         }
                   8553:     } else {
                   8554:         $result= 'error: invalid requestkey'; 
                   8555:     }
                   8556:     return $result;
                   8557: }
                   8558: 
1.21      www      8559: # ---------------------------------------------------------- Assign Custom Role
                   8560: 
                   8561: sub assigncustomrole {
1.957     raeburn  8562:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8563:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8564:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8565: }
                   8566: 
                   8567: # ----------------------------------------------------------------- Revoke Role
                   8568: 
                   8569: sub revokerole {
1.957     raeburn  8570:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8571:     my $now=time;
1.965     raeburn  8572:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8573: }
                   8574: 
                   8575: # ---------------------------------------------------------- Revoke Custom Role
                   8576: 
                   8577: sub revokecustomrole {
1.957     raeburn  8578:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8579:     my $now=time;
1.357     www      8580:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8581:            $deleteflag,$selfenroll,$context);
1.17      www      8582: }
                   8583: 
1.533     banghart 8584: # ------------------------------------------------------------ Disk usage
1.535     albertel 8585: sub diskusage {
1.955     raeburn  8586:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8587:     $directorypath =~ s/\/$//;
                   8588:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8589:                        .&escape($getpropath).':'.&escape($uname).':'
                   8590:                        .&escape($udom),homeserver($uname,$udom));
                   8591:     if ($listing eq 'unknown_cmd') {
                   8592:         if ($getpropath) {
                   8593:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8594:         }
                   8595:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8596:     }
1.514     albertel 8597:     return $listing;
1.512     banghart 8598: }
                   8599: 
1.566     banghart 8600: sub is_locked {
1.1096    raeburn  8601:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8602:     my @check;
                   8603:     my $is_locked;
1.1093    raeburn  8604:     push (@check,$file_name);
1.613     albertel 8605:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8606: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8607:     my ($tmp)=keys(%locked);
                   8608:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8609:     
1.566     banghart 8610:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8611:         $is_locked = 'false';
                   8612:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8613:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8614:                $is_locked = 'true';
1.1096    raeburn  8615:                if (ref($which) eq 'ARRAY') {
                   8616:                    push(@{$which},$entry);
                   8617:                } else {
                   8618:                    last;
                   8619:                }
1.745     raeburn  8620:            }
                   8621:        }
1.566     banghart 8622:     } else {
                   8623:         $is_locked = 'false';
                   8624:     }
1.1093    raeburn  8625:     return $is_locked;
1.566     banghart 8626: }
                   8627: 
1.759     albertel 8628: sub declutter_portfile {
                   8629:     my ($file) = @_;
1.833     albertel 8630:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8631:     return $file;
                   8632: }
                   8633: 
1.559     banghart 8634: # ------------------------------------------------------------- Mark as Read Only
                   8635: 
                   8636: sub mark_as_readonly {
                   8637:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8638:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8639:     my ($tmp)=keys(%current_permissions);
                   8640:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8641:     foreach my $file (@{$files}) {
1.759     albertel 8642: 	$file = &declutter_portfile($file);
1.561     banghart 8643:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8644:     }
1.613     albertel 8645:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8646:     return;
                   8647: }
                   8648: 
1.572     banghart 8649: # ------------------------------------------------------------Save Selected Files
                   8650: 
                   8651: sub save_selected_files {
                   8652:     my ($user, $path, @files) = @_;
                   8653:     my $filename = $user."savedfiles";
1.573     banghart 8654:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8655:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8656:     foreach my $file (@files) {
1.620     albertel 8657:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8658:     }
                   8659:     foreach my $file (@other_files) {
1.574     banghart 8660:         print (OUT $file."\n");
1.572     banghart 8661:     }
1.574     banghart 8662:     close (OUT);
1.572     banghart 8663:     return 'ok';
                   8664: }
                   8665: 
1.574     banghart 8666: sub clear_selected_files {
                   8667:     my ($user) = @_;
                   8668:     my $filename = $user."savedfiles";
1.1117    foxr     8669:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8670:     print (OUT undef);
                   8671:     close (OUT);
                   8672:     return ("ok");    
                   8673: }
                   8674: 
1.572     banghart 8675: sub files_in_path {
                   8676:     my ($user, $path) = @_;
                   8677:     my $filename = $user."savedfiles";
                   8678:     my %return_files;
1.1117    foxr     8679:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8680:     while (my $line_in = <IN>) {
1.574     banghart 8681:         chomp ($line_in);
                   8682:         my @paths_and_file = split (m!/!, $line_in);
                   8683:         my $file_part = pop (@paths_and_file);
                   8684:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8685:         $path_part.='/';
                   8686:         my $path_and_file = $path_part.$file_part;
                   8687:         if ($path_part eq $path) {
                   8688:             $return_files{$file_part}= 'selected';
                   8689:         }
                   8690:     }
1.574     banghart 8691:     close (IN);
                   8692:     return (\%return_files);
1.572     banghart 8693: }
                   8694: 
                   8695: # called in portfolio select mode, to show files selected NOT in current directory
                   8696: sub files_not_in_path {
                   8697:     my ($user, $path) = @_;
                   8698:     my $filename = $user."savedfiles";
                   8699:     my @return_files;
                   8700:     my $path_part;
1.1117    foxr     8701:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8702:     while (my $line = <IN>) {
1.572     banghart 8703:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8704:         my @paths_and_file = split(m|/|, $line);
                   8705:         my $file_part = pop(@paths_and_file);
                   8706:         chomp($file_part);
                   8707:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8708:         $path_part .= '/';
                   8709:         my $path_and_file = $path_part.$file_part;
                   8710:         if ($path_part ne $path) {
1.800     albertel 8711:             push(@return_files, ($path_and_file));
1.572     banghart 8712:         }
                   8713:     }
1.800     albertel 8714:     close(OUT);
1.574     banghart 8715:     return (@return_files);
1.572     banghart 8716: }
                   8717: 
1.745     raeburn  8718: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8719: 
1.745     raeburn  8720: sub get_portfile_permissions {
                   8721:     my ($domain,$user) = @_;
1.613     albertel 8722:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8723:     my ($tmp)=keys(%current_permissions);
                   8724:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8725:     return \%current_permissions;
                   8726: }
                   8727: 
                   8728: #---------------------------------------------Get portfolio file access controls
                   8729: 
1.749     raeburn  8730: sub get_access_controls {
1.745     raeburn  8731:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8732:     my %access;
                   8733:     my $real_file = $file;
                   8734:     $file =~ s/\.meta$//;
1.745     raeburn  8735:     if (defined($file)) {
1.749     raeburn  8736:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8737:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8738:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8739:             }
                   8740:         }
1.745     raeburn  8741:     } else {
1.749     raeburn  8742:         foreach my $key (keys(%{$current_permissions})) {
                   8743:             if ($key =~ /\0accesscontrol$/) {
                   8744:                 if (defined($group)) {
                   8745:                     if ($key !~ m-^\Q$group\E/-) {
                   8746:                         next;
                   8747:                     }
                   8748:                 }
                   8749:                 my ($fullpath) = split(/\0/,$key);
                   8750:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8751:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8752:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8753:                     }
                   8754:                 }
                   8755:             }
                   8756:         }
                   8757:     }
                   8758:     return %access;
                   8759: }
                   8760: 
                   8761: sub modify_access_controls {
                   8762:     my ($file_name,$changes,$domain,$user)=@_;
                   8763:     my ($outcome,$deloutcome);
                   8764:     my %store_permissions;
                   8765:     my %new_values;
                   8766:     my %new_control;
                   8767:     my %translation;
                   8768:     my @deletions = ();
                   8769:     my $now = time;
                   8770:     if (exists($$changes{'activate'})) {
                   8771:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8772:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8773:             my $numnew = scalar(@newitems);
                   8774:             for (my $i=0; $i<$numnew; $i++) {
                   8775:                 my $newkey = $newitems[$i];
                   8776:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8777:                 if ($newkey =~ /^\d+:/) { 
                   8778:                     $newkey =~ s/^(\d+)/$newid/;
                   8779:                     $translation{$1} = $newid;
                   8780:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8781:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8782:                     $translation{$1} = $newid;
                   8783:                 }
1.749     raeburn  8784:                 $new_values{$file_name."\0".$newkey} = 
                   8785:                                           $$changes{'activate'}{$newitems[$i]};
                   8786:                 $new_control{$newkey} = $now;
                   8787:             }
                   8788:         }
                   8789:     }
                   8790:     my %todelete;
                   8791:     my %changed_items;
                   8792:     foreach my $action ('delete','update') {
                   8793:         if (exists($$changes{$action})) {
                   8794:             if (ref($$changes{$action}) eq 'HASH') {
                   8795:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8796:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8797:                     if ($action eq 'delete') { 
                   8798:                         $todelete{$itemnum} = 1;
                   8799:                     } else {
                   8800:                         $changed_items{$itemnum} = $key;
                   8801:                     }
                   8802:                 }
1.745     raeburn  8803:             }
                   8804:         }
1.749     raeburn  8805:     }
                   8806:     # get lock on access controls for file.
                   8807:     my $lockhash = {
                   8808:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8809:                                                        ':'.$env{'user.domain'},
                   8810:                    }; 
                   8811:     my $tries = 0;
                   8812:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8813:    
                   8814:     while (($gotlock ne 'ok') && $tries <3) {
                   8815:         $tries ++;
                   8816:         sleep 1;
                   8817:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8818:     }
                   8819:     if ($gotlock eq 'ok') {
                   8820:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8821:         my ($tmp)=keys(%curr_permissions);
                   8822:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8823:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8824:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8825:             if (ref($curr_controls) eq 'HASH') {
                   8826:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8827:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8828:                     if (defined($todelete{$itemnum})) {
                   8829:                         push(@deletions,$file_name."\0".$control_item);
                   8830:                     } else {
                   8831:                         if (defined($changed_items{$itemnum})) {
                   8832:                             $new_control{$changed_items{$itemnum}} = $now;
                   8833:                             push(@deletions,$file_name."\0".$control_item);
                   8834:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8835:                         } else {
                   8836:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8837:                         }
                   8838:                     }
1.745     raeburn  8839:                 }
                   8840:             }
                   8841:         }
1.970     raeburn  8842:         my ($group);
                   8843:         if (&is_course($domain,$user)) {
                   8844:             ($group,my $file) = split(/\//,$file_name,2);
                   8845:         }
1.749     raeburn  8846:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8847:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8848:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8849:         #  remove lock
                   8850:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8851:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8852:         my $sqlresult =
1.970     raeburn  8853:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8854:                                     $group);
1.749     raeburn  8855:     } else {
                   8856:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8857:     }
1.749     raeburn  8858:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8859: }
                   8860: 
1.827     raeburn  8861: sub make_public_indefinitely {
                   8862:     my ($requrl) = @_;
                   8863:     my $now = time;
                   8864:     my $action = 'activate';
                   8865:     my $aclnum = 0;
                   8866:     if (&is_portfolio_url($requrl)) {
                   8867:         my (undef,$udom,$unum,$file_name,$group) =
                   8868:             &parse_portfolio_url($requrl);
                   8869:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8870:         my %access_controls = &get_access_controls($current_perms,
                   8871:                                                    $group,$file_name);
                   8872:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8873:             my ($num,$scope,$end,$start) = 
                   8874:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8875:             if ($scope eq 'public') {
                   8876:                 if ($start <= $now && $end == 0) {
                   8877:                     $action = 'none';
                   8878:                 } else {
                   8879:                     $action = 'update';
                   8880:                     $aclnum = $num;
                   8881:                 }
                   8882:                 last;
                   8883:             }
                   8884:         }
                   8885:         if ($action eq 'none') {
                   8886:              return 'ok';
                   8887:         } else {
                   8888:             my %changes;
                   8889:             my $newend = 0;
                   8890:             my $newstart = $now;
                   8891:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8892:             $changes{$action}{$newkey} = {
                   8893:                 type => 'public',
                   8894:                 time => {
                   8895:                     start => $newstart,
                   8896:                     end   => $newend,
                   8897:                 },
                   8898:             };
                   8899:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8900:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8901:             return $outcome;
                   8902:         }
                   8903:     } else {
                   8904:         return 'invalid';
                   8905:     }
                   8906: }
                   8907: 
1.745     raeburn  8908: #------------------------------------------------------Get Marked as Read Only
                   8909: 
                   8910: sub get_marked_as_readonly {
                   8911:     my ($domain,$user,$what,$group) = @_;
                   8912:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8913:     my @readonly_files;
1.629     banghart 8914:     my $cmp1=$what;
                   8915:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8916:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8917:         if (defined($group)) {
                   8918:             if ($file_name !~ m-^\Q$group\E/-) {
                   8919:                 next;
                   8920:             }
                   8921:         }
1.561     banghart 8922:         if (ref($value) eq "ARRAY"){
                   8923:             foreach my $stored_what (@{$value}) {
1.629     banghart 8924:                 my $cmp2=$stored_what;
1.759     albertel 8925:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8926:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8927:                 }
1.629     banghart 8928:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8929:                     push(@readonly_files, $file_name);
1.745     raeburn  8930:                     last;
1.563     banghart 8931:                 } elsif (!defined($what)) {
                   8932:                     push(@readonly_files, $file_name);
1.745     raeburn  8933:                     last;
1.561     banghart 8934:                 }
                   8935:             }
1.745     raeburn  8936:         }
1.561     banghart 8937:     }
                   8938:     return @readonly_files;
                   8939: }
1.577     banghart 8940: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8941: 
1.577     banghart 8942: sub get_marked_as_readonly_hash {
1.745     raeburn  8943:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8944:     my %readonly_files;
1.745     raeburn  8945:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8946:         if (defined($group)) {
                   8947:             if ($file_name !~ m-^\Q$group\E/-) {
                   8948:                 next;
                   8949:             }
                   8950:         }
1.577     banghart 8951:         if (ref($value) eq "ARRAY"){
                   8952:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8953:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8954:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8955:                         if ($lock_descriptor eq 'graded') {
                   8956:                             $readonly_files{$file_name} = 'graded';
                   8957:                         } elsif ($lock_descriptor eq 'handback') {
                   8958:                             $readonly_files{$file_name} = 'handback';
                   8959:                         } else {
                   8960:                             if (!exists($readonly_files{$file_name})) {
                   8961:                                 $readonly_files{$file_name} = 'locked';
                   8962:                             }
                   8963:                         }
1.745     raeburn  8964:                     }
1.750     banghart 8965:                 } 
1.577     banghart 8966:             }
                   8967:         } 
                   8968:     }
                   8969:     return %readonly_files;
                   8970: }
1.559     banghart 8971: # ------------------------------------------------------------ Unmark as Read Only
                   8972: 
                   8973: sub unmark_as_readonly {
1.629     banghart 8974:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8975:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8976:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8977:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8978:     my $symb_crs = $what;
                   8979:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8980:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8981:     my ($tmp)=keys(%current_permissions);
                   8982:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8983:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8984:     foreach my $file (@readonly_files) {
1.759     albertel 8985: 	my $clean_file = &declutter_portfile($file);
                   8986: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8987: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8988:         my @new_locks;
                   8989:         my @del_keys;
                   8990:         if (ref($current_locks) eq "ARRAY"){
                   8991:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8992:                 my $compare=$locker;
1.749     raeburn  8993:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8994:                     $compare=join('',@{$locker});
1.746     raeburn  8995:                     if ($compare ne $symb_crs) {
                   8996:                         push(@new_locks, $locker);
                   8997:                     }
1.563     banghart 8998:                 }
                   8999:             }
1.650     albertel 9000:             if (scalar(@new_locks) > 0) {
1.563     banghart 9001:                 $current_permissions{$file} = \@new_locks;
                   9002:             } else {
                   9003:                 push(@del_keys, $file);
1.613     albertel 9004:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9005:                 delete($current_permissions{$file});
1.563     banghart 9006:             }
                   9007:         }
1.561     banghart 9008:     }
1.613     albertel 9009:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9010:     return;
                   9011: }
1.512     banghart 9012: 
1.17      www      9013: # ------------------------------------------------------------ Directory lister
                   9014: 
                   9015: sub dirlist {
1.955     raeburn  9016:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9017:     $uri=~s/^\///;
                   9018:     $uri=~s/\/$//;
1.253     stredwic 9019:     my ($udom, $uname);
1.955     raeburn  9020:     if ($getuserdir) {
1.253     stredwic 9021:         $udom = $userdomain;
                   9022:         $uname = $username;
1.955     raeburn  9023:     } else {
                   9024:         (undef,$udom,$uname)=split(/\//,$uri);
                   9025:         if(defined($userdomain)) {
                   9026:             $udom = $userdomain;
                   9027:         }
                   9028:         if(defined($username)) {
                   9029:             $uname = $username;
                   9030:         }
1.253     stredwic 9031:     }
1.955     raeburn  9032:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9033: 
1.955     raeburn  9034:     $dirRoot = $perlvar{'lonDocRoot'};
                   9035:     if (defined($getpropath)) {
                   9036:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9037:         $dirRoot =~ s/\/$//;
1.955     raeburn  9038:     } elsif (defined($getuserdir)) {
                   9039:         my $subdir=$uname.'__';
                   9040:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9041:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9042:                    ."/$udom/$subdir/$uname";
                   9043:     } elsif (defined($alternateRoot)) {
                   9044:         $dirRoot = $alternateRoot;
1.751     banghart 9045:     }
1.253     stredwic 9046: 
                   9047:     if($udom) {
                   9048:         if($uname) {
1.1135    raeburn  9049:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9050:             if ($uhome eq 'no_host') {
                   9051:                 return ([],'no_host');
                   9052:             }
1.955     raeburn  9053:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9054:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9055:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9056:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9057:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9058:             } else {
                   9059:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9060:             }
1.605     matthew  9061:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9062:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9063:                 @listing_results = split(/:/,$listing);
                   9064:             } else {
                   9065:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9066:             }
1.1135    raeburn  9067:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9068:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9069:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9070:                 return ([],$listing);
                   9071:             } else {
                   9072:                 return (\@listing_results);
1.1135    raeburn  9073:             }
1.955     raeburn  9074:         } elsif(!$alternateRoot) {
1.1136    raeburn  9075:             my (%allusers,%listerror);
1.841     albertel 9076: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9077:  	    foreach my $tryserver (keys(%servers)) {
                   9078:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9079:                                   &escape($udom),$tryserver);
                   9080:                 if ($listing eq 'unknown_cmd') {
                   9081: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9082: 				      $udom, $tryserver);
                   9083:                 } else {
                   9084:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9085:                 }
1.841     albertel 9086: 		if ($listing eq 'unknown_cmd') {
                   9087: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9088: 				      $udom, $tryserver);
                   9089: 		    @listing_results = split(/:/,$listing);
                   9090: 		} else {
                   9091: 		    @listing_results =
                   9092: 			map { &unescape($_); } split(/:/,$listing);
                   9093: 		}
1.1136    raeburn  9094:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9095:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9096:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9097:                     $listerror{$tryserver} = $listing;
                   9098:                 } else {
1.841     albertel 9099: 		    foreach my $line (@listing_results) {
                   9100: 			my ($entry) = split(/&/,$line,2);
                   9101: 			$allusers{$entry} = 1;
                   9102: 		    }
                   9103: 		}
1.253     stredwic 9104:             }
1.1136    raeburn  9105:             my @alluserslist=();
1.800     albertel 9106:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9107:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9108:             }
1.1136    raeburn  9109:             return (\@alluserslist);
1.253     stredwic 9110:         } else {
1.1136    raeburn  9111:             return ([],'missing username');
1.253     stredwic 9112:         }
1.955     raeburn  9113:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9114:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9115:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9116:         return (\@all_domains);
1.955     raeburn  9117:     } else {
1.1136    raeburn  9118:         return ([],'missing domain');
1.275     stredwic 9119:     }
                   9120: }
                   9121: 
                   9122: # --------------------------------------------- GetFileTimestamp
                   9123: # This function utilizes dirlist and returns the date stamp for
                   9124: # when it was last modified.  It will also return an error of -1
                   9125: # if an error occurs
                   9126: 
                   9127: sub GetFileTimestamp {
1.955     raeburn  9128:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9129:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9130:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9131:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9132:                                     undef,$getuserdir);
                   9133:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9134:         return -1;
                   9135:     }
                   9136:     if (ref($fileref) eq 'ARRAY') {
                   9137:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9138:         # @stats contains first the filename, then the stat output
                   9139:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9140:     } else {
                   9141:         return -1;
1.253     stredwic 9142:     }
1.26      www      9143: }
                   9144: 
1.712     albertel 9145: sub stat_file {
                   9146:     my ($uri) = @_;
1.787     albertel 9147:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9148: 
1.955     raeburn  9149:     my ($udom,$uname,$file);
1.712     albertel 9150:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9151: 	($udom,$uname,$file) =
1.811     albertel 9152: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9153: 	$file = 'userfiles/'.$file;
                   9154:     }
                   9155:     if ($uri =~ m-^/res/-) {
                   9156: 	($udom,$uname) = 
1.807     albertel 9157: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9158: 	$file = $uri;
                   9159:     }
                   9160: 
                   9161:     if (!$udom || !$uname || !$file) {
                   9162: 	# unable to handle the uri
                   9163: 	return ();
                   9164:     }
1.956     raeburn  9165:     my $getpropath;
                   9166:     if ($file =~ /^userfiles\//) {
                   9167:         $getpropath = 1;
                   9168:     }
1.1136    raeburn  9169:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9170:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9171:         return ();
                   9172:     } else {
                   9173:         if (ref($listref) eq 'ARRAY') {
                   9174:             my @stats = split('&',$listref->[0]);
                   9175: 	    shift(@stats); #filename is first
                   9176: 	    return @stats;
                   9177:         }
1.712     albertel 9178:     }
                   9179:     return ();
                   9180: }
                   9181: 
1.26      www      9182: # -------------------------------------------------------- Value of a Condition
                   9183: 
1.713     albertel 9184: # gets the value of a specific preevaluated condition
                   9185: #    stored in the string  $env{user.state.<cid>}
                   9186: # or looks up a condition reference in the bighash and if if hasn't
                   9187: # already been evaluated recurses into docondval to get the value of
                   9188: # the condition, then memoizing it to 
                   9189: #   $env{user.state.<cid>.<condition>}
1.40      www      9190: sub directcondval {
                   9191:     my $number=shift;
1.620     albertel 9192:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9193: 	&Apache::lonuserstate::evalstate();
                   9194:     }
1.713     albertel 9195:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9196: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9197:     } elsif ($number =~ /^_/) {
                   9198: 	my $sub_condition;
                   9199: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9200: 		&GDBM_READER(),0640)) {
                   9201: 	    $sub_condition=$bighash{'conditions'.$number};
                   9202: 	    untie(%bighash);
                   9203: 	}
                   9204: 	my $value = &docondval($sub_condition);
1.949     raeburn  9205: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9206: 	return $value;
                   9207:     }
1.620     albertel 9208:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9209:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9210:     } else {
                   9211:        return 2;
                   9212:     }
                   9213: }
                   9214: 
1.713     albertel 9215: # get the collection of conditions for this resource
1.26      www      9216: sub condval {
                   9217:     my $condidx=shift;
1.54      www      9218:     my $allpathcond='';
1.713     albertel 9219:     foreach my $cond (split(/\|/,$condidx)) {
                   9220: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9221: 	    $allpathcond.=
                   9222: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9223: 	}
1.191     harris41 9224:     }
1.54      www      9225:     $allpathcond=~s/\|$//;
1.713     albertel 9226:     return &docondval($allpathcond);
                   9227: }
                   9228: 
                   9229: #evaluates an expression of conditions
                   9230: sub docondval {
                   9231:     my ($allpathcond) = @_;
                   9232:     my $result=0;
                   9233:     if ($env{'request.course.id'}
                   9234: 	&& defined($allpathcond)) {
                   9235: 	my $operand='|';
                   9236: 	my @stack;
                   9237: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9238: 	    if ($chunk eq '(') {
                   9239: 		push @stack,($operand,$result);
                   9240: 	    } elsif ($chunk eq ')') {
                   9241: 		my $before=pop @stack;
                   9242: 		if (pop @stack eq '&') {
                   9243: 		    $result=$result>$before?$before:$result;
                   9244: 		} else {
                   9245: 		    $result=$result>$before?$result:$before;
                   9246: 		}
                   9247: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9248: 		$operand=$chunk;
                   9249: 	    } else {
                   9250: 		my $new=directcondval($chunk);
                   9251: 		if ($operand eq '&') {
                   9252: 		    $result=$result>$new?$new:$result;
                   9253: 		} else {
                   9254: 		    $result=$result>$new?$result:$new;
                   9255: 		}
                   9256: 	    }
                   9257: 	}
1.26      www      9258:     }
                   9259:     return $result;
1.421     albertel 9260: }
                   9261: 
                   9262: # ---------------------------------------------------- Devalidate courseresdata
                   9263: 
                   9264: sub devalidatecourseresdata {
                   9265:     my ($coursenum,$coursedomain)=@_;
                   9266:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9267:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9268: }
                   9269: 
1.763     www      9270: 
1.200     www      9271: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9272: #
                   9273: #  Parameters:
                   9274: #      $coursenum    - Number of the course.
                   9275: #      $coursedomain - Domain at which the course was created.
                   9276: #  Returns:
                   9277: #     A hash of the course parameters along (I think) with timestamps
                   9278: #     and version info.
1.877     foxr     9279: 
1.624     albertel 9280: sub get_courseresdata {
                   9281:     my ($coursenum,$coursedomain)=@_;
1.200     www      9282:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9283:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9284:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9285:     my %dumpreply;
1.417     albertel 9286:     unless (defined($cached)) {
1.624     albertel 9287: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9288: 	$result=\%dumpreply;
1.251     albertel 9289: 	my ($tmp) = keys(%dumpreply);
                   9290: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9291: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9292: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9293: 	    return $tmp;
1.416     albertel 9294: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9295: 	    $result=undef;
1.599     albertel 9296: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9297: 	}
                   9298:     }
1.624     albertel 9299:     return $result;
                   9300: }
                   9301: 
1.633     albertel 9302: sub devalidateuserresdata {
                   9303:     my ($uname,$udom)=@_;
                   9304:     my $hashid="$udom:$uname";
                   9305:     &devalidate_cache_new('userres',$hashid);
                   9306: }
                   9307: 
1.624     albertel 9308: sub get_userresdata {
                   9309:     my ($uname,$udom)=@_;
                   9310:     #most student don\'t have any data set, check if there is some data
                   9311:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9312: 
                   9313:     my $hashid="$udom:$uname";
                   9314:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9315:     if (!defined($cached)) {
                   9316: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9317: 	$result=\%resourcedata;
                   9318: 	&do_cache_new('userres',$hashid,$result,600);
                   9319:     }
                   9320:     my ($tmp)=keys(%$result);
                   9321:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9322: 	return $result;
                   9323:     }
                   9324:     #error 2 occurs when the .db doesn't exist
                   9325:     if ($tmp!~/error: 2 /) {
1.672     albertel 9326: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9327: 		 " Trying to get resource data for ".
                   9328: 		 $uname." at ".$udom.": ".
                   9329: 		 $tmp."</font>");
                   9330:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9331: 	#&EXT_cache_set($udom,$uname);
                   9332: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9333: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9334:     }
                   9335:     return $tmp;
                   9336: }
1.879     foxr     9337: #----------------------------------------------- resdata - return resource data
                   9338: #  Purpose:
                   9339: #    Return resource data for either users or for a course.
                   9340: #  Parameters:
                   9341: #     $name      - Course/user name.
                   9342: #     $domain    - Name of the domain the user/course is registered on.
                   9343: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9344: #     @which     - Array of names of resources desired.
                   9345: #  Returns:
                   9346: #     The value of the first reasource in @which that is found in the
                   9347: #     resource hash.
                   9348: #  Exceptional Conditions:
                   9349: #     If the $type passed in is not valid (not the string 'course' or 
                   9350: #     'user', an undefined  reference is returned.
                   9351: #     If none of the resources are found, an undef is returned
1.624     albertel 9352: sub resdata {
                   9353:     my ($name,$domain,$type,@which)=@_;
                   9354:     my $result;
                   9355:     if ($type eq 'course') {
                   9356: 	$result=&get_courseresdata($name,$domain);
                   9357:     } elsif ($type eq 'user') {
                   9358: 	$result=&get_userresdata($name,$domain);
                   9359:     }
                   9360:     if (!ref($result)) { return $result; }    
1.251     albertel 9361:     foreach my $item (@which) {
1.927     albertel 9362: 	if (defined($result->{$item->[0]})) {
                   9363: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9364: 	}
1.250     albertel 9365:     }
1.291     albertel 9366:     return undef;
1.200     www      9367: }
                   9368: 
1.379     matthew  9369: #
                   9370: # EXT resource caching routines
                   9371: #
                   9372: 
                   9373: sub clear_EXT_cache_status {
1.383     albertel 9374:     &delenv('cache.EXT.');
1.379     matthew  9375: }
                   9376: 
                   9377: sub EXT_cache_status {
                   9378:     my ($target_domain,$target_user) = @_;
1.383     albertel 9379:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9380:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9381:         # We know already the user has no data
                   9382:         return 1;
                   9383:     } else {
                   9384:         return 0;
                   9385:     }
                   9386: }
                   9387: 
                   9388: sub EXT_cache_set {
                   9389:     my ($target_domain,$target_user) = @_;
1.383     albertel 9390:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9391:     #&appenv({$cachename => time});
1.379     matthew  9392: }
                   9393: 
1.28      www      9394: # --------------------------------------------------------- Value of a Variable
1.58      www      9395: sub EXT {
1.715     albertel 9396: 
1.395     albertel 9397:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9398:     unless ($varname) { return ''; }
1.218     albertel 9399:     #get real user name/domain, courseid and symb
                   9400:     my $courseid;
1.359     albertel 9401:     my $publicuser;
1.427     www      9402:     if ($symbparm) {
                   9403: 	$symbparm=&get_symb_from_alias($symbparm);
                   9404:     }
1.218     albertel 9405:     if (!($uname && $udom)) {
1.790     albertel 9406:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9407:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9408:     } else {
1.620     albertel 9409: 	$courseid=$env{'request.course.id'};
1.218     albertel 9410:     }
1.48      www      9411:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9412:     my $rest;
1.320     albertel 9413:     if (defined($therest[0])) {
1.48      www      9414:        $rest=join('.',@therest);
                   9415:     } else {
                   9416:        $rest='';
                   9417:     }
1.320     albertel 9418: 
1.57      www      9419:     my $qualifierrest=$qualifier;
                   9420:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9421:     my $spacequalifierrest=$space;
                   9422:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9423:     if ($realm eq 'user') {
1.48      www      9424: # --------------------------------------------------------------- user.resource
                   9425: 	if ($space eq 'resource') {
1.651     albertel 9426: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9427: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9428: 		 &&
1.744     albertel 9429: 		 ($symbparm eq &symbread()) ) {	
                   9430: 		# if we are in the middle of processing the resource the
                   9431: 		# get the value we are planning on committing
                   9432:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9433:                     return $Apache::lonhomework::results{$qualifierrest};
                   9434:                 } else {
                   9435:                     return $Apache::lonhomework::history{$qualifierrest};
                   9436:                 }
1.335     albertel 9437: 	    } else {
1.359     albertel 9438: 		my %restored;
1.620     albertel 9439: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9440: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9441: 		} else {
                   9442: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9443: 		}
1.335     albertel 9444: 		return $restored{$qualifierrest};
                   9445: 	    }
1.48      www      9446: # ----------------------------------------------------------------- user.access
                   9447:         } elsif ($space eq 'access') {
1.218     albertel 9448: 	    # FIXME - not supporting calls for a specific user
1.48      www      9449:             return &allowed($qualifier,$rest);
                   9450: # ------------------------------------------ user.preferences, user.environment
                   9451:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9452: 	    if (($uname eq $env{'user.name'}) &&
                   9453: 		($udom eq $env{'user.domain'})) {
                   9454: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9455: 	    } else {
1.359     albertel 9456: 		my %returnhash;
                   9457: 		if (!$publicuser) {
                   9458: 		    %returnhash=&userenvironment($udom,$uname,
                   9459: 						 $qualifierrest);
                   9460: 		}
1.218     albertel 9461: 		return $returnhash{$qualifierrest};
                   9462: 	    }
1.48      www      9463: # ----------------------------------------------------------------- user.course
                   9464:         } elsif ($space eq 'course') {
1.218     albertel 9465: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9466:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9467: # ------------------------------------------------------------------- user.role
                   9468:         } elsif ($space eq 'role') {
1.218     albertel 9469: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9470:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9471:             if ($qualifier eq 'value') {
                   9472: 		return $role;
                   9473:             } elsif ($qualifier eq 'extent') {
                   9474:                 return $where;
                   9475:             }
                   9476: # ----------------------------------------------------------------- user.domain
                   9477:         } elsif ($space eq 'domain') {
1.218     albertel 9478:             return $udom;
1.48      www      9479: # ------------------------------------------------------------------- user.name
                   9480:         } elsif ($space eq 'name') {
1.218     albertel 9481:             return $uname;
1.48      www      9482: # ---------------------------------------------------- Any other user namespace
1.29      www      9483:         } else {
1.359     albertel 9484: 	    my %reply;
                   9485: 	    if (!$publicuser) {
                   9486: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9487: 	    }
                   9488: 	    return $reply{$qualifierrest};
1.48      www      9489:         }
1.236     www      9490:     } elsif ($realm eq 'query') {
                   9491: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9492:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9493: 						[$spacequalifierrest]);
1.620     albertel 9494: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9495:    } elsif ($realm eq 'request') {
1.48      www      9496: # ------------------------------------------------------------- request.browser
                   9497:         if ($space eq 'browser') {
1.1145    bisitz   9498:             return $env{'browser.'.$qualifier};
1.57      www      9499: # ------------------------------------------------------------ request.filename
                   9500:         } else {
1.620     albertel 9501:             return $env{'request.'.$spacequalifierrest};
1.29      www      9502:         }
1.28      www      9503:     } elsif ($realm eq 'course') {
1.48      www      9504: # ---------------------------------------------------------- course.description
1.620     albertel 9505:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9506:     } elsif ($realm eq 'resource') {
1.165     www      9507: 
1.620     albertel 9508: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9509: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9510: 	}
1.693     albertel 9511: 
                   9512: 	if ($space eq 'title') {
                   9513: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9514: 	    return &gettitle($symbparm);
                   9515: 	}
                   9516: 	
                   9517: 	if ($space eq 'map') {
                   9518: 	    my ($map) = &decode_symb($symbparm);
                   9519: 	    return &symbread($map);
                   9520: 	}
1.905     albertel 9521: 	if ($space eq 'filename') {
                   9522: 	    if ($symbparm) {
                   9523: 		return &clutter((&decode_symb($symbparm))[2]);
                   9524: 	    }
                   9525: 	    return &hreflocation('',$env{'request.filename'});
                   9526: 	}
1.693     albertel 9527: 
                   9528: 	my ($section, $group, @groups);
1.593     albertel 9529: 	my ($courselevelm,$courselevel);
1.539     albertel 9530: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9531: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9532: 
1.218     albertel 9533: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9534: 
1.60      www      9535: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9536: 	    my $symbp=$symbparm;
1.735     albertel 9537: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9538: 
                   9539: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9540: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9541: 
1.620     albertel 9542: 	    if (($env{'user.name'} eq $uname) &&
                   9543: 		($env{'user.domain'} eq $udom)) {
                   9544: 		$section=$env{'request.course.sec'};
1.733     raeburn  9545:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9546:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9547: 	    } else {
1.539     albertel 9548: 		if (! defined($usection)) {
1.551     albertel 9549: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9550: 		} else {
                   9551: 		    $section = $usection;
                   9552: 		}
1.733     raeburn  9553:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9554: 	    }
                   9555: 
                   9556: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9557: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9558: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9559: 
1.593     albertel 9560: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9561: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9562: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9563: 
1.60      www      9564: # ----------------------------------------------------------- first, check user
1.624     albertel 9565: 
                   9566: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9567: 				       ([$courselevelr,'resource'],
                   9568: 					[$courselevelm,'map'     ],
                   9569: 					[$courselevel, 'course'  ]));
1.931     albertel 9570: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9571: 
1.594     albertel 9572: # ------------------------------------------------ second, check some of course
1.684     raeburn  9573:             my $coursereply;
1.691     raeburn  9574:             if (@groups > 0) {
                   9575:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9576:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9577:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9578:             }
1.96      www      9579: 
1.684     raeburn  9580: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9581: 				  $env{'course.'.$courseid.'.domain'},
                   9582: 				  'course',
                   9583: 				  ([$seclevelr,   'resource'],
                   9584: 				   [$seclevelm,   'map'     ],
                   9585: 				   [$seclevel,    'course'  ],
                   9586: 				   [$courselevelr,'resource']));
                   9587: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9588: 
1.60      www      9589: # ------------------------------------------------------ third, check map parms
1.218     albertel 9590: 	    my %parmhash=();
                   9591: 	    my $thisparm='';
                   9592: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9593: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9594: 		    &GDBM_READER(),0640)) {
1.218     albertel 9595: 		$thisparm=$parmhash{$symbparm};
                   9596: 		untie(%parmhash);
                   9597: 	    }
1.927     albertel 9598: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9599: 	}
1.594     albertel 9600: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9601: 
1.218     albertel 9602: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9603: 	my $filename;
                   9604: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9605: 	if ($symbparm) {
1.409     www      9606: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9607: 	} else {
1.620     albertel 9608: 	    $filename=$env{'request.filename'};
1.282     albertel 9609: 	}
                   9610: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9611: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9612: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9613: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9614: 
1.927     albertel 9615: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9616: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9617: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9618: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9619: 				     $env{'course.'.$courseid.'.domain'},
                   9620: 				     'course',
1.927     albertel 9621: 				     ([$courselevelm,'map'   ],
                   9622: 				      [$courselevel, 'course']));
                   9623: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9624: 	}
1.145     www      9625: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9626: 	unless ($space eq '0') {
1.336     albertel 9627: 	    my @parts=split(/_/,$space);
                   9628: 	    my $id=pop(@parts);
                   9629: 	    my $part=join('_',@parts);
                   9630: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9631: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9632: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9633: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9634: 	}
1.395     albertel 9635: 	if ($recurse) { return undef; }
                   9636: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9637: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9638: # ---------------------------------------------------- Any other user namespace
                   9639:     } elsif ($realm eq 'environment') {
                   9640: # ----------------------------------------------------------------- environment
1.620     albertel 9641: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9642: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9643: 	} else {
1.770     albertel 9644: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9645: 		return '';
                   9646: 	    }
1.219     albertel 9647: 	    my %returnhash=&userenvironment($udom,$uname,
                   9648: 					    $spacequalifierrest);
                   9649: 	    return $returnhash{$spacequalifierrest};
                   9650: 	}
1.28      www      9651:     } elsif ($realm eq 'system') {
1.48      www      9652: # ----------------------------------------------------------------- system.time
                   9653: 	if ($space eq 'time') {
                   9654: 	    return time;
                   9655:         }
1.696     albertel 9656:     } elsif ($realm eq 'server') {
                   9657: # ----------------------------------------------------------------- system.time
                   9658: 	if ($space eq 'name') {
                   9659: 	    return $ENV{'SERVER_NAME'};
                   9660:         }
1.28      www      9661:     }
1.48      www      9662:     return '';
1.61      www      9663: }
                   9664: 
1.927     albertel 9665: sub get_reply {
                   9666:     my ($reply_value) = @_;
1.940     raeburn  9667:     if (ref($reply_value) eq 'ARRAY') {
                   9668:         if (wantarray) {
                   9669: 	    return @$reply_value;
                   9670:         }
                   9671:         return $reply_value->[0];
                   9672:     } else {
                   9673:         return $reply_value;
1.927     albertel 9674:     }
                   9675: }
                   9676: 
1.691     raeburn  9677: sub check_group_parms {
                   9678:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9679:     my @groupitems = ();
                   9680:     my $resultitem;
1.927     albertel 9681:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9682:     foreach my $group (@{$groups}) {
                   9683:         foreach my $level (@levels) {
1.927     albertel 9684:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9685:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9686:         }
                   9687:     }
                   9688:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9689:                             $env{'course.'.$courseid.'.domain'},
                   9690:                                      'course',@groupitems);
                   9691:     return $coursereply;
                   9692: }
                   9693: 
                   9694: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9695:     my ($courseid,@groups) = @_;
                   9696:     @groups = sort(@groups);
1.691     raeburn  9697:     return @groups;
                   9698: }
                   9699: 
1.395     albertel 9700: sub packages_tab_default {
                   9701:     my ($uri,$varname)=@_;
                   9702:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9703: 
                   9704:     my (@extension,@specifics,$do_default);
                   9705:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9706: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9707: 	if ($pack_type eq 'default') {
                   9708: 	    $do_default=1;
                   9709: 	} elsif ($pack_type eq 'extension') {
                   9710: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9711: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9712: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9713: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9714: 	}
                   9715:     }
                   9716:     # first look for a package that matches the requested part id
                   9717:     foreach my $package (@specifics) {
                   9718: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9719: 	next if ($pack_part ne $part);
                   9720: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9721: 	    return $packagetab{"$pack_type&$name&default"};
                   9722: 	}
                   9723:     }
                   9724:     # look for any possible matching non extension_ package
                   9725:     foreach my $package (@specifics) {
                   9726: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9727: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9728: 	    return $packagetab{"$pack_type&$name&default"};
                   9729: 	}
1.585     albertel 9730: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9731: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9732: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9733: 	}
                   9734:     }
1.738     albertel 9735:     # look for any posible extension_ match
                   9736:     foreach my $package (@extension) {
                   9737: 	my ($package,$pack_type)=@{$package};
                   9738: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9739: 	    return $packagetab{"$pack_type&$name&default"};
                   9740: 	}
                   9741: 	if (defined($packagetab{$package."&$name&default"})) {
                   9742: 	    return $packagetab{$package."&$name&default"};
                   9743: 	}
                   9744:     }
                   9745:     # look for a global default setting
                   9746:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9747: 	return $packagetab{"default&$name&default"};
                   9748:     }
1.395     albertel 9749:     return undef;
                   9750: }
                   9751: 
1.334     albertel 9752: sub add_prefix_and_part {
                   9753:     my ($prefix,$part)=@_;
                   9754:     my $keyroot;
                   9755:     if (defined($prefix) && $prefix !~ /^__/) {
                   9756: 	# prefix that has a part already
                   9757: 	$keyroot=$prefix;
                   9758:     } elsif (defined($prefix)) {
                   9759: 	# prefix that is missing a part
                   9760: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9761:     } else {
                   9762: 	# no prefix at all
                   9763: 	if (defined($part)) { $keyroot='_'.$part; }
                   9764:     }
                   9765:     return $keyroot;
                   9766: }
                   9767: 
1.71      www      9768: # ---------------------------------------------------------------- Get metadata
                   9769: 
1.599     albertel 9770: my %metaentry;
1.1070    www      9771: my %importedpartids;
1.71      www      9772: sub metadata {
1.176     www      9773:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9774:     $uri=&declutter($uri);
1.288     albertel 9775:     # if it is a non metadata possible uri return quickly
1.529     albertel 9776:     if (($uri eq '') || 
                   9777: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9778: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9779:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9780: 	return undef;
                   9781:     }
1.1140    www      9782:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9783: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9784: 	return undef;
1.288     albertel 9785:     }
1.73      www      9786:     my $filename=$uri;
                   9787:     $uri=~s/\.meta$//;
1.172     www      9788: #
                   9789: # Is the metadata already cached?
1.177     www      9790: # Look at timestamp of caching
1.172     www      9791: # Everything is cached by the main uri, libraries are never directly cached
                   9792: #
1.428     albertel 9793:     if (!defined($liburi)) {
1.599     albertel 9794: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9795: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9796:     }
                   9797:     {
1.1069    www      9798: # Imported parts would go here
1.1070    www      9799:         my %importedids=();
                   9800:         my @origfileimportpartids=();
1.1069    www      9801:         my $importedparts=0;
1.172     www      9802: #
                   9803: # Is this a recursive call for a library?
                   9804: #
1.599     albertel 9805: #	if (! exists($metacache{$uri})) {
                   9806: #	    $metacache{$uri}={};
                   9807: #	}
1.924     albertel 9808: 	my $cachetime = 60*60;
1.171     www      9809:         if ($liburi) {
                   9810: 	    $liburi=&declutter($liburi);
                   9811:             $filename=$liburi;
1.401     bowersj2 9812:         } else {
1.599     albertel 9813: 	    &devalidate_cache_new('meta',$uri);
                   9814: 	    undef(%metaentry);
1.401     bowersj2 9815: 	}
1.140     www      9816:         my %metathesekeys=();
1.73      www      9817:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9818: 	my $metastring;
1.1140    www      9819: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9820: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9821: 	    $metastring = 
1.929     albertel 9822: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9823: 					  ('grade_target' => 'meta'));
                   9824: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9825: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9826:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9827: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9828: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9829: 	    $metastring=&getfile($file);
1.489     albertel 9830: 	}
1.208     albertel 9831:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9832:         my $token;
1.140     www      9833:         undef %metathesekeys;
1.71      www      9834:         while ($token=$parser->get_token) {
1.339     albertel 9835: 	    if ($token->[0] eq 'S') {
                   9836: 		if (defined($token->[2]->{'package'})) {
1.172     www      9837: #
                   9838: # This is a package - get package info
                   9839: #
1.339     albertel 9840: 		    my $package=$token->[2]->{'package'};
                   9841: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9842: 		    if (defined($token->[2]->{'id'})) { 
                   9843: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9844: 		    }
1.599     albertel 9845: 		    if ($metaentry{':packages'}) {
                   9846: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9847: 		    } else {
1.599     albertel 9848: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9849: 		    }
1.736     albertel 9850: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9851: 			my $part=$keyroot;
                   9852: 			$part=~s/^\_//;
1.736     albertel 9853: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9854: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9855: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9856: 			    # ignore package.tab specified default values
                   9857:                             # here &package_tab_default() will fetch those
                   9858: 			    if ($subp eq 'default') { next; }
1.736     albertel 9859: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9860: 			    my $unikey;
                   9861: 			    if ($pack =~ /_0$/) {
                   9862: 				$unikey='parameter_0_'.$name;
                   9863: 				$part=0;
                   9864: 			    } else {
                   9865: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9866: 			    }
1.339     albertel 9867: 			    if ($subp eq 'display') {
                   9868: 				$value.=' [Part: '.$part.']';
                   9869: 			    }
1.599     albertel 9870: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9871: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9872: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9873: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9874: 			    }
1.599     albertel 9875: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9876: 				$metaentry{':'.$unikey}=
                   9877: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9878: 			    }
1.339     albertel 9879: 			}
                   9880: 		    }
                   9881: 		} else {
1.172     www      9882: #
                   9883: # This is not a package - some other kind of start tag
1.339     albertel 9884: #
                   9885: 		    my $entry=$token->[1];
1.1068    www      9886: 		    my $unikey='';
1.175     www      9887: 
1.339     albertel 9888: 		    if ($entry eq 'import') {
1.175     www      9889: #
                   9890: # Importing a library here
1.339     albertel 9891: #
1.1067    www      9892:                         my $location=$parser->get_text('/import');
                   9893:                         my $dir=$filename;
                   9894:                         $dir=~s|[^/]*$||;
                   9895:                         $location=&filelocation($dir,$location);
1.1069    www      9896:                        
1.1068    www      9897:                         my $importmode=$token->[2]->{'importmode'};
                   9898:                         if ($importmode eq 'problem') {
1.1069    www      9899: # Import as problem/response
1.1068    www      9900:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9901:                         } elsif ($importmode eq 'part') {
                   9902: # Import as part(s)
1.1069    www      9903:                            $importedparts=1;
                   9904: # We need to get the original file and the imported file to get the part order correct
                   9905: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9906: # Load and inspect original file
1.1070    www      9907:                            if ($#origfileimportpartids<0) {
                   9908:                               undef(%importedpartids);
                   9909:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9910:                               my $origfile=&getfile($origfilelocation);
                   9911:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9912:                            }
                   9913: 
1.1069    www      9914: # Load and inspect imported file
                   9915:                            my $impfile=&getfile($location);
                   9916:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9917:                            if ($#impfilepartids>=0) {
                   9918: # This problem had parts
1.1070    www      9919:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9920:                            } else {
                   9921: # Importing by turning a single problem into a problem part
                   9922: # It gets the import-tags ID as part-ID
                   9923:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9924:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9925:                            }
1.1068    www      9926:                         } else {
                   9927: # Normal import
                   9928:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9929:                            if (defined($token->[2]->{'id'})) {
                   9930:                               $unikey.='_'.$token->[2]->{'id'};
                   9931:                            }
1.1067    www      9932:                         }
                   9933: 
1.339     albertel 9934: 			if ($depthcount<20) {
1.736     albertel 9935: 			    my $metadata = 
                   9936: 				&metadata($uri,'keys', $location,$unikey,
                   9937: 					  $depthcount+1);
                   9938: 			    foreach my $meta (split(',',$metadata)) {
                   9939: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9940: 				$metathesekeys{$meta}=1;
1.339     albertel 9941: 			    }
1.1068    www      9942: 			
                   9943:                         }
1.1067    www      9944: 		    } else {
                   9945: #
                   9946: # Not importing, some other kind of non-package, non-library start tag
                   9947: # 
                   9948:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9949:                         if (defined($token->[2]->{'id'})) {
                   9950:                             $unikey.='_'.$token->[2]->{'id'};
                   9951:                         }
1.339     albertel 9952: 			if (defined($token->[2]->{'name'})) { 
                   9953: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9954: 			}
                   9955: 			$metathesekeys{$unikey}=1;
1.736     albertel 9956: 			foreach my $param (@{$token->[3]}) {
                   9957: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9958: 				$token->[2]->{$param};
1.339     albertel 9959: 			}
                   9960: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9961: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9962: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9963: 		 # only ws inside the tag, and not in default, so use default
                   9964: 		 # as value
1.599     albertel 9965: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9966: 			} elsif ( $internaltext =~ /\S/ ) {
                   9967: 		  # something interesting inside the tag
                   9968: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9969: 			} else {
1.908     albertel 9970: 		  # no interesting values, don't set a default
1.339     albertel 9971: 			}
1.172     www      9972: # end of not-a-package not-a-library import
1.339     albertel 9973: 		    }
1.172     www      9974: # end of not-a-package start tag
1.339     albertel 9975: 		}
1.172     www      9976: # the next is the end of "start tag"
1.339     albertel 9977: 	    }
                   9978: 	}
1.483     albertel 9979: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9980: 	$extension = lc($extension);
                   9981: 	if ($extension eq 'htm') { $extension='html'; }
                   9982: 
1.737     albertel 9983: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9984: 	    #no specific packages #how's our extension
                   9985: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9986: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9987: 					 \%metathesekeys);
                   9988: 	}
1.883     albertel 9989: 
                   9990: 	if (!exists($metaentry{':packages'})
                   9991: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9992: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9993: 		#no specific packages well let's get default then
                   9994: 		if ($key!~/^default&/) { next; }
1.488     albertel 9995: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9996: 					     \%metathesekeys);
                   9997: 	    }
                   9998: 	}
1.338     www      9999: # are there custom rights to evaluate
1.599     albertel 10000: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10001: 
1.338     www      10002:     #
                   10003:     # Importing a rights file here
1.339     albertel 10004:     #
                   10005: 	    unless ($depthcount) {
1.599     albertel 10006: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10007: 		my $dir=$filename;
                   10008: 		$dir=~s|[^/]*$||;
                   10009: 		$location=&filelocation($dir,$location);
1.736     albertel 10010: 		my $rights_metadata =
                   10011: 		    &metadata($uri,'keys',$location,'_rights',
                   10012: 			      $depthcount+1);
                   10013: 		foreach my $rights (split(',',$rights_metadata)) {
                   10014: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10015: 		    $metathesekeys{$rights}=1;
1.339     albertel 10016: 		}
                   10017: 	    }
                   10018: 	}
1.737     albertel 10019: 	# uniqifiy package listing
                   10020: 	my %seen;
                   10021: 	my @uniq_packages =
                   10022: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10023: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10024: 
1.1070    www      10025:         if ($importedparts) {
                   10026: # We had imported parts and need to rebuild partorder
                   10027:            $metaentry{':partorder'}='';
                   10028:            $metathesekeys{'partorder'}=1;
                   10029:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10030:                if ($origfileimportpartids[$index] eq 'part') {
                   10031: # original part, part of the problem
                   10032:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10033:                } else {
                   10034: # we have imported parts at this position
                   10035:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10036:                }
                   10037:            }
                   10038:            $metaentry{':partorder'}=~s/^\,//;
                   10039:         }
                   10040: 
1.737     albertel 10041: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10042: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10043: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10044: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10045: # this is the end of "was not already recently cached
1.71      www      10046:     }
1.599     albertel 10047:     return $metaentry{':'.$what};
1.261     albertel 10048: }
                   10049: 
1.488     albertel 10050: sub metadata_create_package_def {
1.483     albertel 10051:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10052:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10053:     if ($subp eq 'default') { next; }
                   10054:     
1.599     albertel 10055:     if (defined($metaentry{':packages'})) {
                   10056: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10057:     } else {
1.599     albertel 10058: 	$metaentry{':packages'}=$package;
1.483     albertel 10059:     }
                   10060:     my $value=$packagetab{$key};
                   10061:     my $unikey;
                   10062:     $unikey='parameter_0_'.$name;
1.599     albertel 10063:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10064:     $$metathesekeys{$unikey}=1;
1.599     albertel 10065:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10066: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10067:     }
1.599     albertel 10068:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10069: 	$metaentry{':'.$unikey}=
                   10070: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10071:     }
                   10072: }
                   10073: 
1.261     albertel 10074: sub metadata_generate_part0 {
                   10075:     my ($metadata,$metacache,$uri) = @_;
                   10076:     my %allnames;
1.737     albertel 10077:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10078: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10079: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10080: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10081: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10082: 	    $allnames{$name}=$part;
                   10083: 	  }
                   10084: 	}
                   10085:     }
                   10086:     foreach my $name (keys(%allnames)) {
                   10087:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10088:       my $key=":parameter_0_$name";
1.261     albertel 10089:       $$metacache{"$key.part"}='0';
                   10090:       $$metacache{"$key.name"}=$name;
1.428     albertel 10091:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10092: 					   $allnames{$name}.'_'.$name.
                   10093: 					   '.type'};
1.428     albertel 10094:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10095: 			     '.display'};
1.644     www      10096:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10097:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10098:       $$metacache{"$key.display"}=$olddis;
                   10099:     }
1.71      www      10100: }
                   10101: 
1.764     albertel 10102: # ------------------------------------------------------ Devalidate title cache
                   10103: 
                   10104: sub devalidate_title_cache {
                   10105:     my ($url)=@_;
                   10106:     if (!$env{'request.course.id'}) { return; }
                   10107:     my $symb=&symbread($url);
                   10108:     if (!$symb) { return; }
                   10109:     my $key=$env{'request.course.id'}."\0".$symb;
                   10110:     &devalidate_cache_new('title',$key);
                   10111: }
                   10112: 
1.1014    droeschl 10113: # ------------------------------------------------- Get the title of a course
                   10114: 
                   10115: sub current_course_title {
                   10116:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10117: }
1.301     www      10118: # ------------------------------------------------- Get the title of a resource
                   10119: 
                   10120: sub gettitle {
                   10121:     my $urlsymb=shift;
                   10122:     my $symb=&symbread($urlsymb);
1.534     albertel 10123:     if ($symb) {
1.620     albertel 10124: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10125: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10126: 	if (defined($cached)) { 
                   10127: 	    return $result;
                   10128: 	}
1.534     albertel 10129: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10130: 	my $title='';
1.907     albertel 10131: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10132: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10133: 	} else {
                   10134: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10135: 		    &GDBM_READER(),0640)) {
                   10136: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10137: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10138: 		untie(%bighash);
                   10139: 	    }
1.534     albertel 10140: 	}
                   10141: 	$title=~s/\&colon\;/\:/gs;
                   10142: 	if ($title) {
1.1159    www      10143: # Remember both $symb and $title for dynamic metadata
                   10144:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10145:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10146: # Cache this title and then return it
1.599     albertel 10147: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10148: 	}
                   10149: 	$urlsymb=$url;
                   10150:     }
                   10151:     my $title=&metadata($urlsymb,'title');
                   10152:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10153:     return $title;
1.301     www      10154: }
1.613     albertel 10155: 
1.614     albertel 10156: sub get_slot {
                   10157:     my ($which,$cnum,$cdom)=@_;
                   10158:     if (!$cnum || !$cdom) {
1.790     albertel 10159: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10160: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10161: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10162:     }
1.703     albertel 10163:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10164:     my %slotinfo;
                   10165:     if (exists($remembered{$key})) {
                   10166: 	$slotinfo{$which} = $remembered{$key};
                   10167:     } else {
                   10168: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10169: 	&Apache::lonhomework::showhash(%slotinfo);
                   10170: 	my ($tmp)=keys(%slotinfo);
                   10171: 	if ($tmp=~/^error:/) { return (); }
                   10172: 	$remembered{$key} = $slotinfo{$which};
                   10173:     }
1.616     albertel 10174:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10175: 	return %{$slotinfo{$which}};
                   10176:     }
                   10177:     return $slotinfo{$which};
1.614     albertel 10178: }
1.1150    raeburn  10179: 
                   10180: sub get_reservable_slots {
                   10181:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10182:     my $now = time;
                   10183:     my $reservable_info;
                   10184:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10185:     if (exists($remembered{$key})) {
                   10186:         $reservable_info = $remembered{$key};
                   10187:     } else {
                   10188:         my %resv;
                   10189:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10190:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10191:         $reservable_info = \%resv;
                   10192:         $remembered{$key} = $reservable_info;
                   10193:     }
                   10194:     return $reservable_info;
                   10195: }
                   10196: 
                   10197: sub get_course_slots {
                   10198:     my ($cnum,$cdom) = @_;
                   10199:     my $hashid=$cnum.':'.$cdom;
                   10200:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10201:     if (defined($cached)) {
                   10202:         if (ref($result) eq 'HASH') {
                   10203:             return %{$result};
                   10204:         }
                   10205:     } else {
                   10206:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10207:         my ($tmp) = keys(%slots);
                   10208:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10209:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10210:             return %slots;
                   10211:         }
                   10212:     }
                   10213:     return;
                   10214: }
                   10215: 
                   10216: sub devalidate_slots_cache {
                   10217:     my ($cnum,$cdom)=@_;
                   10218:     my $hashid=$cnum.':'.$cdom;
                   10219:     &devalidate_cache_new('allslots',$hashid);
                   10220: }
                   10221: 
1.1181    raeburn  10222: sub get_coursechange {
                   10223:     my ($cdom,$cnum) = @_;
                   10224:     if ($cdom eq '' || $cnum eq '') {
                   10225:         return unless ($env{'request.course.id'});
                   10226:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10227:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10228:     }
                   10229:     my $hashid=$cdom.'_'.$cnum;
                   10230:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10231:     if ((defined($cached)) && ($change ne '')) {
                   10232:         return $change;
                   10233:     } else {
                   10234:         my %crshash;
                   10235:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10236:         if ($crshash{'internal.contentchange'} eq '') {
                   10237:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10238:             if ($change eq '') {
                   10239:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10240:                 $change = $crshash{'internal.created'};
                   10241:             }
                   10242:         } else {
                   10243:             $change = $crshash{'internal.contentchange'};
                   10244:         }
                   10245:         my $cachetime = 600;
                   10246:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10247:     }
                   10248:     return $change;
                   10249: }
                   10250: 
                   10251: sub devalidate_coursechange_cache {
                   10252:     my ($cnum,$cdom)=@_;
                   10253:     my $hashid=$cnum.':'.$cdom;
                   10254:     &devalidate_cache_new('crschange',$hashid);
                   10255: }
                   10256: 
1.31      www      10257: # ------------------------------------------------- Update symbolic store links
                   10258: 
                   10259: sub symblist {
                   10260:     my ($mapname,%newhash)=@_;
1.438     www      10261:     $mapname=&deversion(&declutter($mapname));
1.31      www      10262:     my %hash;
1.620     albertel 10263:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10264:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10265:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10266: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10267: 		next if ($url eq 'last_known'
                   10268: 			 && $env{'form.no_update_last_known'});
                   10269: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10270: 						    $newhash{$url}->[1],
                   10271: 						    $newhash{$url}->[0]);
1.191     harris41 10272:             }
1.31      www      10273:             if (untie(%hash)) {
                   10274: 		return 'ok';
                   10275:             }
                   10276:         }
                   10277:     }
                   10278:     return 'error';
1.212     www      10279: }
                   10280: 
                   10281: # --------------------------------------------------------------- Verify a symb
                   10282: 
                   10283: sub symbverify {
1.1190    raeburn  10284:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10285:     my $thisfn=$thisurl;
1.439     www      10286:     $thisfn=&declutter($thisfn);
1.215     www      10287: # direct jump to resource in page or to a sequence - will construct own symbs
                   10288:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10289: # check URL part
1.409     www      10290:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10291: 
1.431     www      10292:     unless ($url eq $thisfn) { return 0; }
1.213     www      10293: 
1.216     www      10294:     $symb=&symbclean($symb);
1.510     www      10295:     $thisurl=&deversion($thisurl);
1.439     www      10296:     $thisfn=&deversion($thisfn);
1.213     www      10297: 
                   10298:     my %bighash;
                   10299:     my $okay=0;
1.431     www      10300: 
1.620     albertel 10301:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10302:                             &GDBM_READER(),0640)) {
1.1032    raeburn  10303:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10304:             $thisurl =~ s/\?.+$//;
                   10305:         }
1.510     www      10306:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  10307:         unless ($ids) {
                   10308:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10309:             $ids=$bighash{$idkey};
1.216     www      10310:         }
                   10311:         if ($ids) {
                   10312: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 10313: 	    foreach my $id (split(/\,/,$ids)) {
                   10314: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  10315:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10316:                    $symb =~ s/\?.+$//;
                   10317:                }
1.216     www      10318:                if (
                   10319:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10320:    eq $symb) {
                   10321:                    if (ref($encstate)) {
                   10322:                        $$encstate = $bighash{'encrypted_'.$id};
                   10323:                    }
1.620     albertel 10324: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10325: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10326:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10327: 		       $okay=1;
1.582     albertel 10328: 		   }
                   10329: 	       }
1.216     www      10330: 	   }
                   10331:         }
1.213     www      10332: 	untie(%bighash);
                   10333:     }
                   10334:     return $okay;
1.31      www      10335: }
                   10336: 
1.210     www      10337: # --------------------------------------------------------------- Clean-up symb
                   10338: 
                   10339: sub symbclean {
                   10340:     my $symb=shift;
1.568     albertel 10341:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10342: # remove version from map
                   10343:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10344: 
1.210     www      10345: # remove version from URL
                   10346:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10347: 
1.507     www      10348: # remove wrapper
                   10349: 
1.510     www      10350:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10351:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10352:     return $symb;
1.409     www      10353: }
                   10354: 
                   10355: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10356: 
                   10357: sub encode_symb {
                   10358:     my ($map,$resid,$url)=@_;
                   10359:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10360: }
1.409     www      10361: 
                   10362: sub decode_symb {
1.568     albertel 10363:     my $symb=shift;
                   10364:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10365:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10366:     return (&fixversion($map),$resid,&fixversion($url));
                   10367: }
                   10368: 
                   10369: sub fixversion {
                   10370:     my $fn=shift;
1.609     banghart 10371:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10372:     my %bighash;
                   10373:     my $uri=&clutter($fn);
1.620     albertel 10374:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10375: # is this cached?
1.599     albertel 10376:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10377:     if (defined($cached)) { return $result; }
                   10378: # unfortunately not cached, or expired
1.620     albertel 10379:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10380: 	    &GDBM_READER(),0640)) {
                   10381:  	if ($bighash{'version_'.$uri}) {
                   10382:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10383:  	    unless (($version eq 'mostrecent') || 
                   10384: 		    ($version==&getversion($uri))) {
1.440     www      10385:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10386:  	    }
                   10387:  	}
                   10388:  	untie %bighash;
1.413     www      10389:     }
1.599     albertel 10390:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10391: }
                   10392: 
                   10393: sub deversion {
                   10394:     my $url=shift;
                   10395:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10396:     return $url;
1.210     www      10397: }
                   10398: 
1.31      www      10399: # ------------------------------------------------------ Return symb list entry
                   10400: 
                   10401: sub symbread {
1.249     www      10402:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 10403:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1179    raeburn  10404:     if (defined($env{$cache_str})) {
                   10405:         if (($thisfn) || ($env{$cache_str} ne '')) {
                   10406:             return $env{$cache_str};
                   10407:         }
                   10408:     }
1.242     www      10409: # no filename provided? try from environment
1.44      www      10410:     unless ($thisfn) {
1.620     albertel 10411:         if ($env{'request.symb'}) {
                   10412: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10413: 	}
1.620     albertel 10414: 	$thisfn=$env{'request.filename'};
1.44      www      10415:     }
1.569     albertel 10416:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10417: # is that filename actually a symb? Verify, clean, and return
                   10418:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10419: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10420: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10421: 	}
1.242     www      10422:     }
1.44      www      10423:     $thisfn=declutter($thisfn);
1.31      www      10424:     my %hash;
1.37      www      10425:     my %bighash;
                   10426:     my $syval='';
1.620     albertel 10427:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10428:         my $targetfn = $thisfn;
1.609     banghart 10429:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10430:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10431:         }
1.687     albertel 10432: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10433: 	    $targetfn=$1;
                   10434: 	}
1.620     albertel 10435:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10436:                       &GDBM_READER(),0640)) {
1.481     raeburn  10437: 	    $syval=$hash{$targetfn};
1.37      www      10438:             untie(%hash);
                   10439:         }
                   10440: # ---------------------------------------------------------- There was an entry
                   10441:         if ($syval) {
1.601     albertel 10442: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10443: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10444: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10445: 		    #return $env{$cache_str}='';
1.601     albertel 10446: 		#}    
                   10447: 		#$syval.=$1;
                   10448: 	    #}
1.37      www      10449:         } else {
                   10450: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10451:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10452:                             &GDBM_READER(),0640)) {
1.37      www      10453: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10454:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10455:               unless ($ids) { 
                   10456:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10457:               }
                   10458:               unless ($ids) {
                   10459: # alias?
                   10460: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10461:               }
1.37      www      10462:               if ($ids) {
                   10463: # ------------------------------------------------------------------- Has ID(s)
                   10464:                  my @possibilities=split(/\,/,$ids);
1.39      www      10465:                  if ($#possibilities==0) {
                   10466: # ----------------------------------------------- There is only one possibility
1.37      www      10467: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10468: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10469: 						    $resid,$thisfn);
1.249     www      10470:                  } elsif (!$donotrecurse) {
1.39      www      10471: # ------------------------------------------ There is more than one possibility
                   10472:                      my $realpossible=0;
1.800     albertel 10473:                      foreach my $id (@possibilities) {
                   10474: 			 my $file=$bighash{'src_'.$id};
1.39      www      10475:                          if (&allowed('bre',$file)) {
1.800     albertel 10476:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10477:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10478: 				$realpossible++;
1.626     albertel 10479:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10480: 						    $resid,$thisfn);
1.39      www      10481:                             }
                   10482: 			 }
1.191     harris41 10483:                      }
1.39      www      10484: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10485:                  } else {
                   10486:                      $syval='';
1.37      www      10487:                  }
                   10488: 	      }
                   10489:               untie(%bighash)
1.481     raeburn  10490:            }
1.31      www      10491:         }
1.62      www      10492:         if ($syval) {
1.620     albertel 10493: 	    return $env{$cache_str}=$syval;
1.62      www      10494:         }
1.31      www      10495:     }
1.949     raeburn  10496:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10497:     return $env{$cache_str}='';
1.31      www      10498: }
                   10499: 
                   10500: # ---------------------------------------------------------- Return random seed
                   10501: 
1.32      www      10502: sub numval {
                   10503:     my $txt=shift;
                   10504:     $txt=~tr/A-J/0-9/;
                   10505:     $txt=~tr/a-j/0-9/;
                   10506:     $txt=~tr/K-T/0-9/;
                   10507:     $txt=~tr/k-t/0-9/;
                   10508:     $txt=~tr/U-Z/0-5/;
                   10509:     $txt=~tr/u-z/0-5/;
                   10510:     $txt=~s/\D//g;
1.564     albertel 10511:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10512:     return int($txt);
1.368     albertel 10513: }
                   10514: 
1.484     albertel 10515: sub numval2 {
                   10516:     my $txt=shift;
                   10517:     $txt=~tr/A-J/0-9/;
                   10518:     $txt=~tr/a-j/0-9/;
                   10519:     $txt=~tr/K-T/0-9/;
                   10520:     $txt=~tr/k-t/0-9/;
                   10521:     $txt=~tr/U-Z/0-5/;
                   10522:     $txt=~tr/u-z/0-5/;
                   10523:     $txt=~s/\D//g;
                   10524:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10525:     my $total;
                   10526:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10527:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10528:     return int($total);
                   10529: }
                   10530: 
1.575     albertel 10531: sub numval3 {
                   10532:     use integer;
                   10533:     my $txt=shift;
                   10534:     $txt=~tr/A-J/0-9/;
                   10535:     $txt=~tr/a-j/0-9/;
                   10536:     $txt=~tr/K-T/0-9/;
                   10537:     $txt=~tr/k-t/0-9/;
                   10538:     $txt=~tr/U-Z/0-5/;
                   10539:     $txt=~tr/u-z/0-5/;
                   10540:     $txt=~s/\D//g;
                   10541:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10542:     my $total;
                   10543:     foreach my $val (@txts) { $total+=$val; }
                   10544:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10545:     return $total;
                   10546: }
                   10547: 
1.675     albertel 10548: sub digest {
                   10549:     my ($data)=@_;
                   10550:     my $digest=&Digest::MD5::md5($data);
                   10551:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10552:     my ($e,$f);
                   10553:     {
                   10554:         use integer;
                   10555:         $e=($a+$b);
                   10556:         $f=($c+$d);
                   10557:         if ($_64bit) {
                   10558:             $e=(($e<<32)>>32);
                   10559:             $f=(($f<<32)>>32);
                   10560:         }
                   10561:     }
                   10562:     if (wantarray) {
                   10563: 	return ($e,$f);
                   10564:     } else {
                   10565: 	my $g;
                   10566: 	{
                   10567: 	    use integer;
                   10568: 	    $g=($e+$f);
                   10569: 	    if ($_64bit) {
                   10570: 		$g=(($g<<32)>>32);
                   10571: 	    }
                   10572: 	}
                   10573: 	return $g;
                   10574:     }
                   10575: }
                   10576: 
1.368     albertel 10577: sub latest_rnd_algorithm_id {
1.675     albertel 10578:     return '64bit5';
1.366     albertel 10579: }
1.32      www      10580: 
1.503     albertel 10581: sub get_rand_alg {
                   10582:     my ($courseid)=@_;
1.790     albertel 10583:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10584:     if ($courseid) {
1.620     albertel 10585: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10586:     }
                   10587:     return &latest_rnd_algorithm_id();
                   10588: }
                   10589: 
1.562     albertel 10590: sub validCODE {
                   10591:     my ($CODE)=@_;
                   10592:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10593:     return 0;
                   10594: }
                   10595: 
1.491     albertel 10596: sub getCODE {
1.620     albertel 10597:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10598:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10599: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10600: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10601: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10602:     }
                   10603:     return undef;
                   10604: }
1.1133    foxr     10605: #
                   10606: #  Determines the random seed for a specific context:
                   10607: #
                   10608: # parameters:
                   10609: #   symb      - in course context the symb for the seed.
                   10610: #   course_id - The course id of the form domain_coursenum.
                   10611: #   domain    - Domain for the user.
                   10612: #   course    - Course for the user.
                   10613: #   cenv      - environment of the course.
                   10614: #
                   10615: # NOTE:
                   10616: #   All parameters are picked out of the environment if missing
                   10617: #   or not defined.
                   10618: #   If a symb cannot be determined the current time is used instead.
                   10619: #
                   10620: #  For a given well defined symb, courside, domain, username,
                   10621: #  and course environment, the seed is reproducible.
                   10622: #
1.31      www      10623: sub rndseed {
1.1133    foxr     10624:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10625:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10626:     if (!defined($symb)) {
1.366     albertel 10627: 	unless ($symb=$wsymb) { return time; }
                   10628:     }
1.1146    foxr     10629:     if (!defined $courseid) { 
                   10630: 	$courseid=$wcourseid; 
                   10631:     }
                   10632:     if (!defined $domain) { $domain=$wdomain; }
                   10633:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10634: 
                   10635:     my $which;
                   10636:     if (defined($cenv->{'rndseed'})) {
                   10637: 	$which = $cenv->{'rndseed'};
                   10638:     } else {
                   10639: 	$which =&get_rand_alg($courseid);
                   10640:     }
1.491     albertel 10641:     if (defined(&getCODE())) {
1.1133    foxr     10642: 
1.675     albertel 10643: 	if ($which eq '64bit5') {
                   10644: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10645: 	} elsif ($which eq '64bit4') {
1.575     albertel 10646: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10647: 	} else {
                   10648: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10649: 	}
1.675     albertel 10650:     } elsif ($which eq '64bit5') {
                   10651: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10652:     } elsif ($which eq '64bit4') {
                   10653: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10654:     } elsif ($which eq '64bit3') {
                   10655: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10656:     } elsif ($which eq '64bit2') {
                   10657: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10658:     } elsif ($which eq '64bit') {
                   10659: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10660:     }
                   10661:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10662: }
                   10663: 
                   10664: sub rndseed_32bit {
                   10665:     my ($symb,$courseid,$domain,$username)=@_;
                   10666:     {
                   10667: 	use integer;
                   10668: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10669: 	my $symbseed=numval($symb) << 22;
                   10670: 	my $namechck=unpack("%32C*",$username) << 17;
                   10671: 	my $nameseed=numval($username) << 12;
                   10672: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10673: 	my $courseseed=unpack("%32C*",$courseid);
                   10674: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10675: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10676: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10677: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10678: 	return $num;
                   10679:     }
                   10680: }
                   10681: 
                   10682: sub rndseed_64bit {
                   10683:     my ($symb,$courseid,$domain,$username)=@_;
                   10684:     {
                   10685: 	use integer;
                   10686: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10687: 	my $symbseed=numval($symb) << 10;
                   10688: 	my $namechck=unpack("%32S*",$username);
                   10689: 	
                   10690: 	my $nameseed=numval($username) << 21;
                   10691: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10692: 	my $courseseed=unpack("%32S*",$courseid);
                   10693: 	
                   10694: 	my $num1=$symbchck+$symbseed+$namechck;
                   10695: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10696: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10697: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10698: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10699: 	return "$num1,$num2";
1.155     albertel 10700:     }
1.366     albertel 10701: }
                   10702: 
1.443     albertel 10703: sub rndseed_64bit2 {
                   10704:     my ($symb,$courseid,$domain,$username)=@_;
                   10705:     {
                   10706: 	use integer;
                   10707: 	# strings need to be an even # of cahracters long, it it is odd the
                   10708:         # last characters gets thrown away
                   10709: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10710: 	my $symbseed=numval($symb) << 10;
                   10711: 	my $namechck=unpack("%32S*",$username.' ');
                   10712: 	
                   10713: 	my $nameseed=numval($username) << 21;
1.501     albertel 10714: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10715: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10716: 	
                   10717: 	my $num1=$symbchck+$symbseed+$namechck;
                   10718: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10719: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10720: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10721: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10722: 	return "$num1,$num2";
                   10723:     }
                   10724: }
                   10725: 
                   10726: sub rndseed_64bit3 {
                   10727:     my ($symb,$courseid,$domain,$username)=@_;
                   10728:     {
                   10729: 	use integer;
                   10730: 	# strings need to be an even # of cahracters long, it it is odd the
                   10731:         # last characters gets thrown away
                   10732: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10733: 	my $symbseed=numval2($symb) << 10;
                   10734: 	my $namechck=unpack("%32S*",$username.' ');
                   10735: 	
                   10736: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10737: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10738: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10739: 	
                   10740: 	my $num1=$symbchck+$symbseed+$namechck;
                   10741: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10742: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10743: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10744: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10745: 	
1.503     albertel 10746: 	return "$num1:$num2";
1.443     albertel 10747:     }
                   10748: }
                   10749: 
1.575     albertel 10750: sub rndseed_64bit4 {
                   10751:     my ($symb,$courseid,$domain,$username)=@_;
                   10752:     {
                   10753: 	use integer;
                   10754: 	# strings need to be an even # of cahracters long, it it is odd the
                   10755:         # last characters gets thrown away
                   10756: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10757: 	my $symbseed=numval3($symb) << 10;
                   10758: 	my $namechck=unpack("%32S*",$username.' ');
                   10759: 	
                   10760: 	my $nameseed=numval3($username) << 21;
                   10761: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10762: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10763: 	
                   10764: 	my $num1=$symbchck+$symbseed+$namechck;
                   10765: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10766: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10767: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10768: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10769: 	
1.575     albertel 10770: 	return "$num1:$num2";
                   10771:     }
                   10772: }
                   10773: 
1.675     albertel 10774: sub rndseed_64bit5 {
                   10775:     my ($symb,$courseid,$domain,$username)=@_;
                   10776:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10777:     return "$num1:$num2";
                   10778: }
                   10779: 
1.366     albertel 10780: sub rndseed_CODE_64bit {
                   10781:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10782:     {
1.366     albertel 10783: 	use integer;
1.443     albertel 10784: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10785: 	my $symbseed=numval2($symb);
1.491     albertel 10786: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10787: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10788: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10789: 	my $num1=$symbseed+$CODEchck;
                   10790: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10791: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10792: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10793: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10794: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10795: 	return "$num1:$num2";
1.366     albertel 10796:     }
                   10797: }
                   10798: 
1.575     albertel 10799: sub rndseed_CODE_64bit4 {
                   10800:     my ($symb,$courseid,$domain,$username)=@_;
                   10801:     {
                   10802: 	use integer;
                   10803: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10804: 	my $symbseed=numval3($symb);
                   10805: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10806: 	my $CODEseed=numval3(&getCODE());
                   10807: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10808: 	my $num1=$symbseed+$CODEchck;
                   10809: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10810: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10811: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10812: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10813: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10814: 	return "$num1:$num2";
                   10815:     }
                   10816: }
                   10817: 
1.675     albertel 10818: sub rndseed_CODE_64bit5 {
                   10819:     my ($symb,$courseid,$domain,$username)=@_;
                   10820:     my $code = &getCODE();
                   10821:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10822:     return "$num1:$num2";
                   10823: }
                   10824: 
1.366     albertel 10825: sub setup_random_from_rndseed {
                   10826:     my ($rndseed)=@_;
1.503     albertel 10827:     if ($rndseed =~/([,:])/) {
                   10828: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10829: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10830:     } else {
                   10831: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10832:     }
1.36      albertel 10833: }
                   10834: 
1.474     albertel 10835: sub latest_receipt_algorithm_id {
1.835     albertel 10836:     return 'receipt3';
1.474     albertel 10837: }
                   10838: 
1.480     www      10839: sub recunique {
                   10840:     my $fucourseid=shift;
                   10841:     my $unique;
1.835     albertel 10842:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10843: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10844: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10845:     } else {
                   10846: 	$unique=$perlvar{'lonReceipt'};
                   10847:     }
                   10848:     return unpack("%32C*",$unique);
                   10849: }
                   10850: 
                   10851: sub recprefix {
                   10852:     my $fucourseid=shift;
                   10853:     my $prefix;
1.835     albertel 10854:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10855: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10856: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10857:     } else {
                   10858: 	$prefix=$perlvar{'lonHostID'};
                   10859:     }
                   10860:     return unpack("%32C*",$prefix);
                   10861: }
                   10862: 
1.76      www      10863: sub ireceipt {
1.474     albertel 10864:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10865: 
                   10866:     my $return =&recprefix($fucourseid).'-';
                   10867: 
                   10868:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10869: 	$env{'request.state'} eq 'construct') {
                   10870: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10871: 	return $return;
                   10872:     }
                   10873: 
1.76      www      10874:     my $cuname=unpack("%32C*",$funame);
                   10875:     my $cudom=unpack("%32C*",$fudom);
                   10876:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10877:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10878:     my $cunique=&recunique($fucourseid);
1.474     albertel 10879:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10880:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10881: 
1.790     albertel 10882: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10883: 			       
                   10884: 	$return.= ($cunique%$cuname+
                   10885: 		   $cunique%$cudom+
                   10886: 		   $cusymb%$cuname+
                   10887: 		   $cusymb%$cudom+
                   10888: 		   $cucourseid%$cuname+
                   10889: 		   $cucourseid%$cudom+
                   10890: 		   $cpart%$cuname+
                   10891: 		   $cpart%$cudom);
                   10892:     } else {
                   10893: 	$return.= ($cunique%$cuname+
                   10894: 		   $cunique%$cudom+
                   10895: 		   $cusymb%$cuname+
                   10896: 		   $cusymb%$cudom+
                   10897: 		   $cucourseid%$cuname+
                   10898: 		   $cucourseid%$cudom);
                   10899:     }
                   10900:     return $return;
1.76      www      10901: }
                   10902: 
                   10903: sub receipt {
1.474     albertel 10904:     my ($part)=@_;
1.790     albertel 10905:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10906:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10907: }
1.260     ng       10908: 
1.790     albertel 10909: sub whichuser {
                   10910:     my ($passedsymb)=@_;
                   10911:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10912:     if (defined($env{'form.grade_symb'})) {
                   10913: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10914: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10915: 	if (!$allowed &&
                   10916: 	    exists($env{'request.course.sec'}) &&
                   10917: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10918: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10919: 			      '/'.$env{'request.course.sec'});
                   10920: 	}
                   10921: 	if ($allowed) {
                   10922: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10923: 	    $courseid=$tmp_courseid;
                   10924: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10925: 	    ($name)=&get_env_multiple('form.grade_username');
                   10926: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10927: 	}
                   10928:     }
                   10929:     if (!$passedsymb) {
                   10930: 	$symb=&symbread();
                   10931:     } else {
                   10932: 	$symb=$passedsymb;
                   10933:     }
                   10934:     $courseid=$env{'request.course.id'};
                   10935:     $domain=$env{'user.domain'};
                   10936:     $name=$env{'user.name'};
                   10937:     if ($name eq 'public' && $domain eq 'public') {
                   10938: 	if (!defined($env{'form.username'})) {
                   10939: 	    $env{'form.username'}.=time.rand(10000000);
                   10940: 	}
                   10941: 	$name.=$env{'form.username'};
                   10942:     }
                   10943:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10944: 
                   10945: }
                   10946: 
1.36      albertel 10947: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10948: # returns either the contents of the file or 
                   10949: # -1 if the file doesn't exist
1.481     raeburn  10950: #
                   10951: # if the target is a file that was uploaded via DOCS, 
                   10952: # a check will be made to see if a current copy exists on the local server,
                   10953: # if it does this will be served, otherwise a copy will be retrieved from
                   10954: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10955: # the local server.   
1.472     albertel 10956: 
1.36      albertel 10957: sub getfile {
1.538     albertel 10958:     my ($file) = @_;
1.609     banghart 10959:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10960:     &repcopy($file);
                   10961:     return &readfile($file);
                   10962: }
                   10963: 
                   10964: sub repcopy_userfile {
                   10965:     my ($file)=@_;
1.1142    raeburn  10966:     my $londocroot = $perlvar{'lonDocRoot'};
                   10967:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10968:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10969:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10970: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10971:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10972:     if (-e "$file") {
1.828     www      10973: # we already have a local copy, check it out
1.538     albertel 10974: 	my @fileinfo = stat($file);
1.828     www      10975: 	my $rtncode;
                   10976: 	my $info;
1.538     albertel 10977: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10978: 	if ($lwpresp ne 'ok') {
1.828     www      10979: # there is no such file anymore, even though we had a local copy
1.482     albertel 10980: 	    if ($rtncode eq '404') {
1.538     albertel 10981: 		unlink($file);
1.482     albertel 10982: 	    }
                   10983: 	    return -1;
                   10984: 	}
                   10985: 	if ($info < $fileinfo[9]) {
1.828     www      10986: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10987: 	    return 'ok';
1.828     www      10988: 	} else {
                   10989: # the file is outdated, get rid of it
                   10990: 	    unlink($file);
1.482     albertel 10991: 	}
1.828     www      10992:     }
                   10993: # one way or the other, at this point, we don't have the file
                   10994: # construct the correct path for the file
                   10995:     my @parts = ($cdom,$cnum); 
                   10996:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10997: 	push @parts, split(/\//,$1);
                   10998:     }
                   10999:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11000:     foreach my $part (@parts) {
                   11001: 	$path .= '/'.$part;
                   11002: 	if (!-e $path) {
                   11003: 	    mkdir($path,0770);
1.482     albertel 11004: 	}
                   11005:     }
1.828     www      11006: # now the path exists for sure
                   11007: # get a user agent
                   11008:     my $ua=new LWP::UserAgent;
                   11009:     my $transferfile=$file.'.in.transfer';
                   11010: # FIXME: this should flock
                   11011:     if (-e $transferfile) { return 'ok'; }
                   11012:     my $request;
                   11013:     $uri=~s/^\///;
1.980     raeburn  11014:     my $homeserver = &homeserver($cnum,$cdom);
                   11015:     my $protocol = $protocol{$homeserver};
                   11016:     $protocol = 'http' if ($protocol ne 'https');
                   11017:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11018:     my $response=$ua->request($request,$transferfile);
                   11019: # did it work?
                   11020:     if ($response->is_error()) {
                   11021: 	unlink($transferfile);
                   11022: 	&logthis("Userfile repcopy failed for $uri");
                   11023: 	return -1;
                   11024:     }
                   11025: # worked, rename the transfer file
                   11026:     rename($transferfile,$file);
1.607     raeburn  11027:     return 'ok';
1.481     raeburn  11028: }
                   11029: 
1.517     albertel 11030: sub tokenwrapper {
                   11031:     my $uri=shift;
1.980     raeburn  11032:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11033:     $uri=~s|^/||;
1.620     albertel 11034:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11035:     my $token=$1;
1.552     albertel 11036:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11037:     if ($udom && $uname && $file) {
                   11038: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11039:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11040:         my $homeserver = &homeserver($uname,$udom);
                   11041:         my $protocol = $protocol{$homeserver};
                   11042:         $protocol = 'http' if ($protocol ne 'https');
                   11043:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11044:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11045:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11046:     } else {
                   11047:         return '/adm/notfound.html';
                   11048:     }
                   11049: }
                   11050: 
1.828     www      11051: # call with reqtype HEAD: get last modification time
                   11052: # call with reqtype GET: get the file contents
                   11053: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11054: #
1.481     raeburn  11055: sub getuploaded {
                   11056:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11057:     $uri=~s/^\///;
1.980     raeburn  11058:     my $homeserver = &homeserver($cnum,$cdom);
                   11059:     my $protocol = $protocol{$homeserver};
                   11060:     $protocol = 'http' if ($protocol ne 'https');
                   11061:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11062:     my $ua=new LWP::UserAgent;
                   11063:     my $request=new HTTP::Request($reqtype,$uri);
                   11064:     my $response=$ua->request($request);
                   11065:     $$rtncode = $response->code;
1.482     albertel 11066:     if (! $response->is_success()) {
                   11067: 	return 'failed';
                   11068:     }      
                   11069:     if ($reqtype eq 'HEAD') {
1.486     www      11070: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11071:     } elsif ($reqtype eq 'GET') {
                   11072: 	$$info = $response->content;
1.472     albertel 11073:     }
1.482     albertel 11074:     return 'ok';
1.36      albertel 11075: }
                   11076: 
1.481     raeburn  11077: sub readfile {
                   11078:     my $file = shift;
                   11079:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11080:     my $fh;
                   11081:     open($fh,"<$file");
                   11082:     my $a='';
1.800     albertel 11083:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11084:     return $a;
                   11085: }
                   11086: 
1.36      albertel 11087: sub filelocation {
1.590     banghart 11088:     my ($dir,$file) = @_;
                   11089:     my $location;
                   11090:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11091: 
                   11092:     if ($file =~ m-^/adm/-) {
                   11093: 	$file=~s-^/adm/wrapper/-/-;
                   11094: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11095:     }
1.882     albertel 11096: 
1.1139    www      11097:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11098:         $location = $file;
1.609     banghart 11099:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11100:         my ($udom,$uname,$filename)=
1.811     albertel 11101:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11102:         my $home=&homeserver($uname,$udom);
                   11103:         my $is_me=0;
                   11104:         my @ids=&current_machine_ids();
                   11105:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11106:         if ($is_me) {
1.1117    foxr     11107:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11108:         } else {
                   11109:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11110:   	      $udom.'/'.$uname.'/'.$filename;
                   11111:         }
1.882     albertel 11112:     } elsif ($file =~ m-^/adm/-) {
                   11113: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11114:     } else {
                   11115:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11116:         $file=~s:^/(res|priv)/:/:;
                   11117:         my $space=$1;
1.590     banghart 11118:         if ( !( $file =~ m:^/:) ) {
                   11119:             $location = $dir. '/'.$file;
                   11120:         } else {
1.1142    raeburn  11121:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11122:         }
1.59      albertel 11123:     }
1.590     banghart 11124:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11125:     while ($location=~m{/\.\./}) {
                   11126: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11127: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11128: 	} else {
                   11129: 	    $location=~ s{/\.\./}{/}g;
                   11130: 	}
                   11131:     } #remove dir/..
1.590     banghart 11132:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11133:     return $location;
1.46      www      11134: }
1.36      albertel 11135: 
1.46      www      11136: sub hreflocation {
                   11137:     my ($dir,$file)=@_;
1.980     raeburn  11138:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11139: 	$file=filelocation($dir,$file);
1.700     albertel 11140:     } elsif ($file=~m-^/adm/-) {
                   11141: 	$file=~s-^/adm/wrapper/-/-;
                   11142: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11143:     }
                   11144:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11145: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11146:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11147: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11148: 	        {/uploaded/$1/$2/}x;
1.46      www      11149:     }
1.913     albertel 11150:     if ($file=~ m{^/userfiles/}) {
                   11151: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11152:     }
1.462     albertel 11153:     return $file;
1.465     albertel 11154: }
                   11155: 
1.1139    www      11156: 
                   11157: 
                   11158: 
                   11159: 
1.465     albertel 11160: sub current_machine_domains {
1.853     albertel 11161:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11162: }
                   11163: 
                   11164: sub machine_domains {
                   11165:     my ($hostname) = @_;
1.465     albertel 11166:     my @domains;
1.838     albertel 11167:     my %hostname = &all_hostnames();
1.465     albertel 11168:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11169: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11170: 	if ($hostname eq $name) {
1.844     albertel 11171: 	    push(@domains,&host_domain($id));
1.465     albertel 11172: 	}
                   11173:     }
                   11174:     return @domains;
                   11175: }
                   11176: 
                   11177: sub current_machine_ids {
1.853     albertel 11178:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11179: }
                   11180: 
                   11181: sub machine_ids {
                   11182:     my ($hostname) = @_;
                   11183:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11184:     my @ids;
1.888     albertel 11185:     my %name_to_host = &all_names();
1.889     albertel 11186:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11187: 	return @{ $name_to_host{$hostname} };
                   11188:     }
                   11189:     return;
1.31      www      11190: }
                   11191: 
1.824     raeburn  11192: sub additional_machine_domains {
                   11193:     my @domains;
                   11194:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11195:     while( my $line = <$fh>) {
                   11196:         $line =~ s/\s//g;
                   11197:         push(@domains,$line);
                   11198:     }
                   11199:     return @domains;
                   11200: }
                   11201: 
                   11202: sub default_login_domain {
                   11203:     my $domain = $perlvar{'lonDefDomain'};
                   11204:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11205:     foreach my $posdom (&current_machine_domains(),
                   11206:                         &additional_machine_domains()) {
                   11207:         if (lc($posdom) eq lc($testdomain)) {
                   11208:             $domain=$posdom;
                   11209:             last;
                   11210:         }
                   11211:     }
                   11212:     return $domain;
                   11213: }
                   11214: 
1.31      www      11215: # ------------------------------------------------------------- Declutters URLs
                   11216: 
                   11217: sub declutter {
                   11218:     my $thisfn=shift;
1.569     albertel 11219:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11220:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11221:     $thisfn=~s/^\///;
1.697     albertel 11222:     $thisfn=~s|^adm/wrapper/||;
                   11223:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11224:     $thisfn=~s/^res\///;
1.1172    bisitz   11225:     $thisfn=~s/^priv\///;
1.1032    raeburn  11226:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11227:         $thisfn=~s/\?.+$//;
                   11228:     }
1.268     www      11229:     return $thisfn;
                   11230: }
                   11231: 
                   11232: # ------------------------------------------------------------- Clutter up URLs
                   11233: 
                   11234: sub clutter {
                   11235:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11236:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11237: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11238:        $thisfn='/res'.$thisfn; 
                   11239:     }
1.1031    raeburn  11240:     if ($thisfn !~m|^/adm|) {
                   11241: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11242: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11243: 	} else {
                   11244: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11245: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11246: 	    if ($embstyle eq 'ssi'
                   11247: 		|| ($embstyle eq 'hdn')
                   11248: 		|| ($embstyle eq 'rat')
                   11249: 		|| ($embstyle eq 'prv')
                   11250: 		|| ($embstyle eq 'ign')) {
                   11251: 		#do nothing with these
                   11252: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11253: 		|| ($embstyle eq 'emb')
                   11254: 		|| ($embstyle eq 'wrp')) {
                   11255: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11256: 	    } elsif ($embstyle eq 'unk'
                   11257: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11258: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11259: 	    } else {
1.718     www      11260: #		&logthis("Got a blank emb style");
1.695     albertel 11261: 	    }
1.694     albertel 11262: 	}
                   11263:     }
1.31      www      11264:     return $thisfn;
1.12      www      11265: }
                   11266: 
1.787     albertel 11267: sub clutter_with_no_wrapper {
                   11268:     my $uri = &clutter(shift);
                   11269:     if ($uri =~ m-^/adm/-) {
                   11270: 	$uri =~ s-^/adm/wrapper/-/-;
                   11271: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11272:     }
                   11273:     return $uri;
                   11274: }
                   11275: 
1.557     albertel 11276: sub freeze_escape {
                   11277:     my ($value)=@_;
                   11278:     if (ref($value)) {
                   11279: 	$value=&nfreeze($value);
                   11280: 	return '__FROZEN__'.&escape($value);
                   11281:     }
                   11282:     return &escape($value);
                   11283: }
                   11284: 
1.11      www      11285: 
1.557     albertel 11286: sub thaw_unescape {
                   11287:     my ($value)=@_;
                   11288:     if ($value =~ /^__FROZEN__/) {
                   11289: 	substr($value,0,10,undef);
                   11290: 	$value=&unescape($value);
                   11291: 	return &thaw($value);
                   11292:     }
                   11293:     return &unescape($value);
                   11294: }
                   11295: 
1.436     albertel 11296: sub correct_line_ends {
                   11297:     my ($result)=@_;
                   11298:     $$result =~s/\r\n/\n/mg;
                   11299:     $$result =~s/\r/\n/mg;
1.415     albertel 11300: }
1.1       albertel 11301: # ================================================================ Main Program
                   11302: 
1.184     www      11303: sub goodbye {
1.204     albertel 11304:    &logthis("Starting Shut down");
1.443     albertel 11305: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11306:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11307: #converted
1.599     albertel 11308: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11309:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11310: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11311: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11312: #1.1 only
1.870     albertel 11313: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11314: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11315: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11316: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11317:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11318:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11319:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11320:    &flushcourselogs();
                   11321:    &logthis("Shutting down");
                   11322: }
                   11323: 
1.852     albertel 11324: sub get_dns {
1.869     albertel 11325:     my ($url,$func,$ignore_cache) = @_;
                   11326:     if (!$ignore_cache) {
                   11327: 	my ($content,$cached)=
                   11328: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11329: 	if ($cached) {
                   11330: 	    &$func($content);
                   11331: 	    return;
                   11332: 	}
                   11333:     }
                   11334: 
                   11335:     my %alldns;
1.852     albertel 11336:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11337:     foreach my $dns (<$config>) {
                   11338: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11339:         my $line = $1;
                   11340:         my ($host,$protocol) = split(/:/,$line);
                   11341:         if ($protocol ne 'https') {
                   11342:             $protocol = 'http';
                   11343:         }
                   11344: 	$alldns{$host} = $protocol;
1.869     albertel 11345:     }
                   11346:     while (%alldns) {
                   11347: 	my ($dns) = keys(%alldns);
1.852     albertel 11348: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11349:         $ua->timeout(30);
1.979     raeburn  11350: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11351: 	my $response=$ua->request($request);
1.979     raeburn  11352:         delete($alldns{$dns});
1.852     albertel 11353: 	next if ($response->is_error());
                   11354: 	my @content = split("\n",$response->content);
1.869     albertel 11355: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 11356: 	&$func(\@content);
1.869     albertel 11357: 	return;
1.852     albertel 11358:     }
                   11359:     close($config);
1.871     albertel 11360:     my $which = (split('/',$url))[3];
                   11361:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11362:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11363:     my @content = <$config>;
                   11364:     &$func(\@content);
                   11365:     return;
1.852     albertel 11366: }
1.327     albertel 11367: # ------------------------------------------------------------ Read domain file
                   11368: {
1.852     albertel 11369:     my $loaded;
1.846     albertel 11370:     my %domain;
                   11371: 
1.852     albertel 11372:     sub parse_domain_tab {
                   11373: 	my ($lines) = @_;
                   11374: 	foreach my $line (@$lines) {
                   11375: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11376: 
1.846     albertel 11377: 	    chomp($line);
1.852     albertel 11378: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11379: 	    my %this_domain;
                   11380: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11381: 			       'lang_def', 'city', 'longi', 'lati',
                   11382: 			       'primary') {
                   11383: 		$this_domain{$field} = shift(@elements);
                   11384: 	    }
                   11385: 	    $domain{$name} = \%this_domain;
1.852     albertel 11386: 	}
                   11387:     }
1.864     albertel 11388: 
                   11389:     sub reset_domain_info {
                   11390: 	undef($loaded);
                   11391: 	undef(%domain);
                   11392:     }
                   11393: 
1.852     albertel 11394:     sub load_domain_tab {
1.869     albertel 11395: 	my ($ignore_cache) = @_;
                   11396: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11397: 	my $fh;
                   11398: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11399: 	    my @lines = <$fh>;
                   11400: 	    &parse_domain_tab(\@lines);
1.448     albertel 11401: 	}
1.852     albertel 11402: 	close($fh);
                   11403: 	$loaded = 1;
1.327     albertel 11404:     }
1.846     albertel 11405: 
                   11406:     sub domain {
1.852     albertel 11407: 	&load_domain_tab() if (!$loaded);
                   11408: 
1.846     albertel 11409: 	my ($name,$what) = @_;
                   11410: 	return if ( !exists($domain{$name}) );
                   11411: 
                   11412: 	if (!$what) {
                   11413: 	    return $domain{$name}{'description'};
                   11414: 	}
                   11415: 	return $domain{$name}{$what};
                   11416:     }
1.974     raeburn  11417: 
                   11418:     sub domain_info {
                   11419:         &load_domain_tab() if (!$loaded);
                   11420:         return %domain;
                   11421:     }
                   11422: 
1.327     albertel 11423: }
                   11424: 
                   11425: 
1.1       albertel 11426: # ------------------------------------------------------------- Read hosts file
                   11427: {
1.838     albertel 11428:     my %hostname;
1.844     albertel 11429:     my %hostdom;
1.845     albertel 11430:     my %libserv;
1.852     albertel 11431:     my $loaded;
1.888     albertel 11432:     my %name_to_host;
1.1074    raeburn  11433:     my %internetdom;
1.1107    raeburn  11434:     my %LC_dns_serv;
1.852     albertel 11435: 
                   11436:     sub parse_hosts_tab {
                   11437: 	my ($file) = @_;
                   11438: 	foreach my $configline (@$file) {
                   11439: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11440:             chomp($configline);
                   11441: 	    if ($configline =~ /^\^/) {
                   11442:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11443:                     $LC_dns_serv{$1} = 1;
                   11444:                 }
                   11445:                 next;
                   11446:             }
1.1074    raeburn  11447: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11448: 	    $name=~s/\s//g;
                   11449: 	    if ($id && $domain && $role && $name) {
                   11450: 		$hostname{$id}=$name;
1.888     albertel 11451: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11452: 		$hostdom{$id}=$domain;
                   11453: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11454:                 if (defined($protocol)) {
                   11455:                     if ($protocol eq 'https') {
                   11456:                         $protocol{$id} = $protocol;
                   11457:                     } else {
                   11458:                         $protocol{$id} = 'http'; 
                   11459:                     }
1.968     raeburn  11460:                 } else {
1.969     raeburn  11461:                     $protocol{$id} = 'http';
1.968     raeburn  11462:                 }
1.1074    raeburn  11463:                 if (defined($intdom)) {
                   11464:                     $internetdom{$id} = $intdom;
                   11465:                 }
1.852     albertel 11466: 	    }
                   11467: 	}
                   11468:     }
1.864     albertel 11469:     
                   11470:     sub reset_hosts_info {
1.897     albertel 11471: 	&purge_remembered();
1.864     albertel 11472: 	&reset_domain_info();
                   11473: 	&reset_hosts_ip_info();
1.892     albertel 11474: 	undef(%name_to_host);
1.864     albertel 11475: 	undef(%hostname);
                   11476: 	undef(%hostdom);
                   11477: 	undef(%libserv);
                   11478: 	undef($loaded);
                   11479:     }
1.1       albertel 11480: 
1.852     albertel 11481:     sub load_hosts_tab {
1.869     albertel 11482: 	my ($ignore_cache) = @_;
                   11483: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11484: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11485: 	my @config = <$config>;
                   11486: 	&parse_hosts_tab(\@config);
                   11487: 	close($config);
                   11488: 	$loaded=1;
1.1       albertel 11489:     }
1.852     albertel 11490: 
1.838     albertel 11491:     sub hostname {
1.852     albertel 11492: 	&load_hosts_tab() if (!$loaded);
                   11493: 
1.838     albertel 11494: 	my ($lonid) = @_;
                   11495: 	return $hostname{$lonid};
                   11496:     }
1.845     albertel 11497: 
1.838     albertel 11498:     sub all_hostnames {
1.852     albertel 11499: 	&load_hosts_tab() if (!$loaded);
                   11500: 
1.838     albertel 11501: 	return %hostname;
                   11502:     }
1.845     albertel 11503: 
1.888     albertel 11504:     sub all_names {
                   11505: 	&load_hosts_tab() if (!$loaded);
                   11506: 
                   11507: 	return %name_to_host;
                   11508:     }
                   11509: 
1.974     raeburn  11510:     sub all_host_domain {
                   11511:         &load_hosts_tab() if (!$loaded);
                   11512:         return %hostdom;
                   11513:     }
                   11514: 
1.845     albertel 11515:     sub is_library {
1.852     albertel 11516: 	&load_hosts_tab() if (!$loaded);
                   11517: 
1.845     albertel 11518: 	return exists($libserv{$_[0]});
                   11519:     }
                   11520: 
                   11521:     sub all_library {
1.852     albertel 11522: 	&load_hosts_tab() if (!$loaded);
                   11523: 
1.845     albertel 11524: 	return %libserv;
                   11525:     }
                   11526: 
1.1062    droeschl 11527:     sub unique_library {
                   11528: 	#2x reverse removes all hostnames that appear more than once
                   11529:         my %unique = reverse &all_library();
                   11530:         return reverse %unique;
                   11531:     }
                   11532: 
1.841     albertel 11533:     sub get_servers {
1.852     albertel 11534: 	&load_hosts_tab() if (!$loaded);
                   11535: 
1.841     albertel 11536: 	my ($domain,$type) = @_;
                   11537: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11538: 	                                          : %hostname;
                   11539: 	my %result;
1.842     albertel 11540: 	if (ref($domain) eq 'ARRAY') {
                   11541: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11542: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11543: 		    $result{$host} = $hostname;
                   11544: 		}
                   11545: 	    }
                   11546: 	} else {
                   11547: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11548: 		if ($hostdom{$host} eq $domain) {
                   11549: 		    $result{$host} = $hostname;
                   11550: 		}
1.841     albertel 11551: 	    }
                   11552: 	}
                   11553: 	return %result;
                   11554:     }
1.845     albertel 11555: 
1.1062    droeschl 11556:     sub get_unique_servers {
                   11557:         my %unique = reverse &get_servers(@_);
                   11558: 	return reverse %unique;
                   11559:     }
                   11560: 
1.844     albertel 11561:     sub host_domain {
1.852     albertel 11562: 	&load_hosts_tab() if (!$loaded);
                   11563: 
1.844     albertel 11564: 	my ($lonid) = @_;
                   11565: 	return $hostdom{$lonid};
                   11566:     }
                   11567: 
1.841     albertel 11568:     sub all_domains {
1.852     albertel 11569: 	&load_hosts_tab() if (!$loaded);
                   11570: 
1.841     albertel 11571: 	my %seen;
                   11572: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11573: 	return @uniq;
                   11574:     }
1.1074    raeburn  11575: 
                   11576:     sub internet_dom {
                   11577:         &load_hosts_tab() if (!$loaded);
                   11578: 
                   11579:         my ($lonid) = @_;
                   11580:         return $internetdom{$lonid};
                   11581:     }
1.1107    raeburn  11582: 
                   11583:     sub is_LC_dns {
                   11584:         &load_hosts_tab() if (!$loaded);
                   11585: 
                   11586:         my ($hostname) = @_;
                   11587:         return exists($LC_dns_serv{$hostname});
                   11588:     }
                   11589: 
1.1       albertel 11590: }
                   11591: 
1.847     albertel 11592: { 
                   11593:     my %iphost;
1.856     albertel 11594:     my %name_to_ip;
                   11595:     my %lonid_to_ip;
1.869     albertel 11596: 
1.847     albertel 11597:     sub get_hosts_from_ip {
                   11598: 	my ($ip) = @_;
                   11599: 	my %iphosts = &get_iphost();
                   11600: 	if (ref($iphosts{$ip})) {
                   11601: 	    return @{$iphosts{$ip}};
                   11602: 	}
                   11603: 	return;
1.839     albertel 11604:     }
1.864     albertel 11605:     
                   11606:     sub reset_hosts_ip_info {
                   11607: 	undef(%iphost);
                   11608: 	undef(%name_to_ip);
                   11609: 	undef(%lonid_to_ip);
                   11610:     }
1.856     albertel 11611: 
                   11612:     sub get_host_ip {
                   11613: 	my ($lonid) = @_;
                   11614: 	if (exists($lonid_to_ip{$lonid})) {
                   11615: 	    return $lonid_to_ip{$lonid};
                   11616: 	}
                   11617: 	my $name=&hostname($lonid);
                   11618:    	my $ip = gethostbyname($name);
                   11619: 	return if (!$ip || length($ip) ne 4);
                   11620: 	$ip=inet_ntoa($ip);
                   11621: 	$name_to_ip{$name}   = $ip;
                   11622: 	$lonid_to_ip{$lonid} = $ip;
                   11623: 	return $ip;
                   11624:     }
1.847     albertel 11625:     
                   11626:     sub get_iphost {
1.869     albertel 11627: 	my ($ignore_cache) = @_;
1.894     albertel 11628: 
1.869     albertel 11629: 	if (!$ignore_cache) {
                   11630: 	    if (%iphost) {
                   11631: 		return %iphost;
                   11632: 	    }
                   11633: 	    my ($ip_info,$cached)=
                   11634: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11635: 	    if ($cached) {
                   11636: 		%iphost      = %{$ip_info->[0]};
                   11637: 		%name_to_ip  = %{$ip_info->[1]};
                   11638: 		%lonid_to_ip = %{$ip_info->[2]};
                   11639: 		return %iphost;
                   11640: 	    }
                   11641: 	}
1.894     albertel 11642: 
                   11643: 	# get yesterday's info for fallback
                   11644: 	my %old_name_to_ip;
                   11645: 	my ($ip_info,$cached)=
                   11646: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11647: 	if ($cached) {
                   11648: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11649: 	}
                   11650: 
1.888     albertel 11651: 	my %name_to_host = &all_names();
                   11652: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11653: 	    my $ip;
                   11654: 	    if (!exists($name_to_ip{$name})) {
                   11655: 		$ip = gethostbyname($name);
                   11656: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11657: 		    if (defined($old_name_to_ip{$name})) {
                   11658: 			$ip = $old_name_to_ip{$name};
                   11659: 			&logthis("Can't find $name defaulting to old $ip");
                   11660: 		    } else {
                   11661: 			&logthis("Name $name no IP found");
                   11662: 			next;
                   11663: 		    }
                   11664: 		} else {
                   11665: 		    $ip=inet_ntoa($ip);
1.847     albertel 11666: 		}
                   11667: 		$name_to_ip{$name} = $ip;
                   11668: 	    } else {
                   11669: 		$ip = $name_to_ip{$name};
1.653     albertel 11670: 	    }
1.888     albertel 11671: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11672: 		$lonid_to_ip{$id} = $ip;
                   11673: 	    }
                   11674: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11675: 	}
1.869     albertel 11676: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11677: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11678: 				      48*60*60);
1.869     albertel 11679: 
1.847     albertel 11680: 	return %iphost;
1.598     albertel 11681:     }
                   11682: 
1.992     raeburn  11683:     #
                   11684:     #  Given a DNS returns the loncapa host name for that DNS 
                   11685:     # 
                   11686:     sub host_from_dns {
                   11687:         my ($dns) = @_;
                   11688:         my @hosts;
                   11689:         my $ip;
                   11690: 
1.993     raeburn  11691:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11692:             $ip = $name_to_ip{$dns};
                   11693:         }
                   11694:         if (!$ip) {
                   11695:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11696:             if (length($ip) == 4) { 
                   11697: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11698:             }
                   11699:         }
                   11700:         if ($ip) {
                   11701: 	    @hosts = get_hosts_from_ip($ip);
                   11702: 	    return $hosts[0];
                   11703:         }
                   11704:         return undef;
1.986     foxr     11705:     }
1.992     raeburn  11706: 
1.1074    raeburn  11707:     sub get_internet_names {
                   11708:         my ($lonid) = @_;
                   11709:         return if ($lonid eq '');
                   11710:         my ($idnref,$cached)=
                   11711:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11712:         if ($cached) {
                   11713:             return $idnref;
                   11714:         }
                   11715:         my $ip = &get_host_ip($lonid);
                   11716:         my @hosts = &get_hosts_from_ip($ip);
                   11717:         my %iphost = &get_iphost();
                   11718:         my (@idns,%seen);
                   11719:         foreach my $id (@hosts) {
                   11720:             my $dom = &host_domain($id);
                   11721:             my $prim_id = &domain($dom,'primary');
                   11722:             my $prim_ip = &get_host_ip($prim_id);
                   11723:             next if ($seen{$prim_ip});
                   11724:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11725:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11726:                     my $intdom = &internet_dom($id);
                   11727:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11728:                         push(@idns,$intdom);
                   11729:                     }
                   11730:                 }
                   11731:             }
                   11732:             $seen{$prim_ip} = 1;
                   11733:         }
                   11734:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11735:     }
                   11736: 
1.986     foxr     11737: }
                   11738: 
1.1079    raeburn  11739: sub all_loncaparevs {
                   11740:     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);
                   11741: }
                   11742: 
1.862     albertel 11743: BEGIN {
                   11744: 
                   11745: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11746:     unless ($readit) {
                   11747: {
                   11748:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11749:     %perlvar = (%perlvar,%{$configvars});
                   11750: }
                   11751: 
                   11752: 
1.1       albertel 11753: # ------------------------------------------------------ Read spare server file
                   11754: {
1.448     albertel 11755:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11756: 
                   11757:     while (my $configline=<$config>) {
                   11758:        chomp($configline);
1.284     matthew  11759:        if ($configline) {
1.784     albertel 11760: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11761: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11762: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11763:        }
                   11764:     }
1.448     albertel 11765:     close($config);
1.1       albertel 11766: }
1.11      www      11767: # ------------------------------------------------------------ Read permissions
                   11768: {
1.448     albertel 11769:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11770: 
                   11771:     while (my $configline=<$config>) {
1.448     albertel 11772: 	chomp($configline);
                   11773: 	if ($configline) {
                   11774: 	    my ($role,$perm)=split(/ /,$configline);
                   11775: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11776: 	}
1.11      www      11777:     }
1.448     albertel 11778:     close($config);
1.11      www      11779: }
                   11780: 
                   11781: # -------------------------------------------- Read plain texts for permissions
                   11782: {
1.448     albertel 11783:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11784: 
                   11785:     while (my $configline=<$config>) {
1.448     albertel 11786: 	chomp($configline);
                   11787: 	if ($configline) {
1.742     raeburn  11788: 	    my ($short,@plain)=split(/:/,$configline);
                   11789:             %{$prp{$short}} = ();
                   11790: 	    if (@plain > 0) {
                   11791:                 $prp{$short}{'std'} = $plain[0];
                   11792:                 for (my $i=1; $i<@plain; $i++) {
                   11793:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11794:                 }
                   11795:             }
1.448     albertel 11796: 	}
1.135     www      11797:     }
1.448     albertel 11798:     close($config);
1.135     www      11799: }
                   11800: 
                   11801: # ---------------------------------------------------------- Read package table
                   11802: {
1.448     albertel 11803:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11804: 
                   11805:     while (my $configline=<$config>) {
1.483     albertel 11806: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11807: 	chomp($configline);
                   11808: 	my ($short,$plain)=split(/:/,$configline);
                   11809: 	my ($pack,$name)=split(/\&/,$short);
                   11810: 	if ($plain ne '') {
                   11811: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11812: 	    $packagetab{$short}=$plain; 
                   11813: 	}
1.11      www      11814:     }
1.448     albertel 11815:     close($config);
1.329     matthew  11816: }
                   11817: 
1.1073    raeburn  11818: # ---------------------------------------------------------- Read loncaparev table
                   11819: {
                   11820:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11821:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11822:             while (my $configline=<$config>) {
                   11823:                 chomp($configline);
                   11824:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11825:                 $loncaparevs{$hostid}=$loncaparev;
                   11826:             }
                   11827:             close($config);
                   11828:         }
                   11829:     }
                   11830: }
                   11831: 
1.1074    raeburn  11832: # ---------------------------------------------------------- Read serverhostID table
                   11833: {
                   11834:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11835:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11836:             while (my $configline=<$config>) {
                   11837:                 chomp($configline);
                   11838:                 my ($name,$id)=split(/:/,$configline);
                   11839:                 $serverhomeIDs{$name}=$id;
                   11840:             }
                   11841:             close($config);
                   11842:         }
                   11843:     }
                   11844: }
                   11845: 
1.1079    raeburn  11846: {
                   11847:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11848:     if (-e $file) {
                   11849:         my $parser = HTML::LCParser->new($file);
                   11850:         while (my $token = $parser->get_token()) {
                   11851:             if ($token->[0] eq 'S') {
                   11852:                 my $item = $token->[1];
                   11853:                 my $name = $token->[2]{'name'};
                   11854:                 my $value = $token->[2]{'value'};
                   11855:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11856:                     my $release = $parser->get_text();
                   11857:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11858:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11859:                 }
                   11860:             }
                   11861:         }
                   11862:     }
1.1073    raeburn  11863: }
                   11864: 
1.1138    raeburn  11865: # ---------------------------------------------------------- Read managers table
                   11866: {
                   11867:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11868:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11869:             while (my $configline=<$config>) {
                   11870:                 chomp($configline);
                   11871:                 next if ($configline =~ /^\#/);
                   11872:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11873:                     $managerstab{$configline} = 1;
                   11874:                 }
                   11875:             }
                   11876:             close($config);
                   11877:         }
                   11878:     }
                   11879: }
                   11880: 
1.329     matthew  11881: # ------------- set up temporary directory
                   11882: {
1.1117    foxr     11883:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11884: 
1.11      www      11885: }
                   11886: 
1.794     albertel 11887: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11888: 				'compress_threshold'=> 20_000,
                   11889:  			        });
1.185     www      11890: 
1.281     www      11891: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11892: $dumpcount=0;
1.958     www      11893: $locknum=0;
1.22      www      11894: 
1.163     harris41 11895: &logtouch();
1.672     albertel 11896: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11897: $readit=1;
1.564     albertel 11898:     {
                   11899: 	use integer;
                   11900: 	my $test=(2**32)+1;
1.568     albertel 11901: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11902: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11903:     }
1.195     www      11904: }
1.1       albertel 11905: }
1.179     www      11906: 
1.1       albertel 11907: 1;
1.191     harris41 11908: __END__
                   11909: 
1.243     albertel 11910: =pod
                   11911: 
1.191     harris41 11912: =head1 NAME
                   11913: 
1.243     albertel 11914: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11915: 
                   11916: =head1 SYNOPSIS
                   11917: 
1.243     albertel 11918: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11919: 
                   11920:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11921: 
1.243     albertel 11922: Common parameters:
                   11923: 
                   11924: =over 4
                   11925: 
                   11926: =item *
                   11927: 
                   11928: $uname : an internal username (if $cname expecting a course Id specifically)
                   11929: 
                   11930: =item *
                   11931: 
                   11932: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11933: 
                   11934: =item *
                   11935: 
                   11936: $symb : a resource instance identifier
                   11937: 
                   11938: =item *
                   11939: 
                   11940: $namespace : the name of a .db file that contains the data needed or
                   11941: being set.
                   11942: 
                   11943: =back
                   11944: 
1.394     bowersj2 11945: =head1 OVERVIEW
1.191     harris41 11946: 
1.394     bowersj2 11947: lonnet provides subroutines which interact with the
                   11948: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11949: about classes, users, and resources.
1.243     albertel 11950: 
                   11951: For many of these objects you can also use this to store data about
                   11952: them or modify them in various ways.
1.191     harris41 11953: 
1.394     bowersj2 11954: =head2 Symbs
1.191     harris41 11955: 
1.394     bowersj2 11956: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11957: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11958: map, the resource number of the resource in the map, and the URL of
                   11959: the resource itself. The latter is somewhat redundant, but might help
                   11960: if maps change.
                   11961: 
                   11962: An example is
                   11963: 
                   11964:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11965: 
                   11966: The respective map entry is
                   11967: 
                   11968:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11969:   title="Problem 2">
                   11970:  </resource>
                   11971: 
                   11972: Symbs are used by the random number generator, as well as to store and
                   11973: restore data specific to a certain instance of for example a problem.
                   11974: 
                   11975: =head2 Storing And Retrieving Data
                   11976: 
                   11977: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11978: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11979: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11980: is is the non-critical message twin of cstore. These functions are for
                   11981: handlers to store a perl hash to a user's permanent data space in an
                   11982: easy manner, and to retrieve it again on another call. It is expected
                   11983: that a handler would use this once at the beginning to retrieve data,
                   11984: and then again once at the end to send only the new data back.
                   11985: 
                   11986: The data is stored in the user's data directory on the user's
                   11987: homeserver under the ID of the course.
                   11988: 
                   11989: The hash that is returned by restore will have all of the previous
                   11990: value for all of the elements of the hash.
                   11991: 
                   11992: Example:
                   11993: 
                   11994:  #creating a hash
                   11995:  my %hash;
                   11996:  $hash{'foo'}='bar';
                   11997: 
                   11998:  #storing it
                   11999:  &Apache::lonnet::cstore(\%hash);
                   12000: 
                   12001:  #changing a value
                   12002:  $hash{'foo'}='notbar';
                   12003: 
                   12004:  #adding a new value
                   12005:  $hash{'bar'}='foo';
                   12006:  &Apache::lonnet::cstore(\%hash);
                   12007: 
                   12008:  #retrieving the hash
                   12009:  my %history=&Apache::lonnet::restore();
                   12010: 
                   12011:  #print the hash
                   12012:  foreach my $key (sort(keys(%history))) {
                   12013:    print("\%history{$key} = $history{$key}");
                   12014:  }
                   12015: 
                   12016: Will print out:
1.191     harris41 12017: 
1.394     bowersj2 12018:  %history{1:foo} = bar
                   12019:  %history{1:keys} = foo:timestamp
                   12020:  %history{1:timestamp} = 990455579
                   12021:  %history{2:bar} = foo
                   12022:  %history{2:foo} = notbar
                   12023:  %history{2:keys} = foo:bar:timestamp
                   12024:  %history{2:timestamp} = 990455580
                   12025:  %history{bar} = foo
                   12026:  %history{foo} = notbar
                   12027:  %history{timestamp} = 990455580
                   12028:  %history{version} = 2
                   12029: 
                   12030: Note that the special hash entries C<keys>, C<version> and
                   12031: C<timestamp> were added to the hash. C<version> will be equal to the
                   12032: total number of versions of the data that have been stored. The
                   12033: C<timestamp> attribute will be the UNIX time the hash was
                   12034: stored. C<keys> is available in every historical section to list which
                   12035: keys were added or changed at a specific historical revision of a
                   12036: hash.
                   12037: 
                   12038: B<Warning>: do not store the hash that restore returns directly. This
                   12039: will cause a mess since it will restore the historical keys as if the
                   12040: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12041: 
1.394     bowersj2 12042: Calling convention:
1.191     harris41 12043: 
1.394     bowersj2 12044:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12045:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12046: 
1.394     bowersj2 12047: For more detailed information, see lonnet specific documentation.
1.191     harris41 12048: 
1.394     bowersj2 12049: =head1 RETURN MESSAGES
1.191     harris41 12050: 
1.394     bowersj2 12051: =over 4
1.191     harris41 12052: 
1.394     bowersj2 12053: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12054: 
1.394     bowersj2 12055: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12056: when the connection is brought back up
1.191     harris41 12057: 
1.394     bowersj2 12058: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12059: for later delivery
1.191     harris41 12060: 
1.967     bisitz   12061: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12062: 
1.394     bowersj2 12063: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12064: that was requested
1.191     harris41 12065: 
1.243     albertel 12066: =back
1.191     harris41 12067: 
1.243     albertel 12068: =head1 PUBLIC SUBROUTINES
1.191     harris41 12069: 
1.243     albertel 12070: =head2 Session Environment Functions
1.191     harris41 12071: 
1.243     albertel 12072: =over 4
1.191     harris41 12073: 
1.394     bowersj2 12074: =item * 
                   12075: X<appenv()>
1.949     raeburn  12076: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12077: the user envirnoment file, and will be restored for each access this
1.620     albertel 12078: user makes during this session, also modifies the %env for the current
1.949     raeburn  12079: process. Optional rolesarrayref - if defined contains a reference to an array
                   12080: of roles which are exempt from the restriction on modifying user.role entries 
                   12081: in the user's environment.db and in %env.    
1.191     harris41 12082: 
                   12083: =item *
1.394     bowersj2 12084: X<delenv()>
1.987     raeburn  12085: B<delenv($delthis,$regexp)>: removes all items from the session
                   12086: environment file that begin with $delthis. If the 
                   12087: optional second arg - $regexp - is true, $delthis is treated as a 
                   12088: regular expression, otherwise \Q$delthis\E is used. 
                   12089: The values are also deleted from the current processes %env.
1.191     harris41 12090: 
1.795     albertel 12091: =item * get_env_multiple($name) 
                   12092: 
                   12093: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12094: values may be defined and end up as an array ref.
                   12095: 
                   12096: returns an array of values
                   12097: 
1.243     albertel 12098: =back
                   12099: 
                   12100: =head2 User Information
1.191     harris41 12101: 
1.243     albertel 12102: =over 4
1.191     harris41 12103: 
                   12104: =item *
1.394     bowersj2 12105: X<queryauthenticate()>
                   12106: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12107: authentication scheme
                   12108: 
                   12109: =item *
1.394     bowersj2 12110: X<authenticate()>
1.1073    raeburn  12111: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12112: authenticate user from domain's lib servers (first use the current
                   12113: one). C<$upass> should be the users password.
1.1073    raeburn  12114: $checkdefauth is optional (value is 1 if a check should be made to
                   12115:    authenticate user using default authentication method, and allow
                   12116:    account creation if username does not have account in the domain).
                   12117: $clientcancheckhost is optional (value is 1 if checking whether the
                   12118:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12119: 
                   12120: =item *
1.394     bowersj2 12121: X<homeserver()>
                   12122: B<homeserver($uname,$udom)>: find the server which has
                   12123: the user's directory and files (there must be only one), this caches
                   12124: the answer, and also caches if there is a borken connection.
1.191     harris41 12125: 
                   12126: =item *
1.394     bowersj2 12127: X<idget()>
                   12128: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12129: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12130: username, and only 1 username per ID in a specific domain) (returns
                   12131: hash: id=>name,id=>name)
1.191     harris41 12132: 
                   12133: =item *
1.394     bowersj2 12134: X<idrget()>
                   12135: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12136: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12137: 
                   12138: =item *
1.394     bowersj2 12139: X<idput()>
                   12140: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12141: 
                   12142: =item *
1.394     bowersj2 12143: X<rolesinit()>
1.1169    droeschl 12144: B<rolesinit($udom,$username)>: get user privileges.
                   12145: returns user role, first access and timer interval hashes
1.243     albertel 12146: 
                   12147: =item *
1.1171    droeschl 12148: X<privileged()>
                   12149: B<privileged($username,$domain)>: returns a true if user has a
                   12150: privileged and active role (i.e. su or dc), false otherwise.
                   12151: 
                   12152: =item *
1.551     albertel 12153: X<getsection()>
                   12154: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12155: course $cname, return section name/number or '' for "not in course"
                   12156: and '-1' for "no section"
                   12157: 
                   12158: =item *
1.394     bowersj2 12159: X<userenvironment()>
                   12160: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12161: passed in @what from the requested user's environment, returns a hash
                   12162: 
1.858     raeburn  12163: =item * 
                   12164: X<userlog_query()>
1.859     albertel 12165: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12166: activity.log file. %filters defines filters applied when parsing the
                   12167: log file. These can be start or end timestamps, or the type of action
                   12168: - log to look for Login or Logout events, check for Checkin or
                   12169: Checkout, role for role selection. The response is in the form
                   12170: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12171: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12172: 
1.243     albertel 12173: =back
                   12174: 
                   12175: =head2 User Roles
                   12176: 
                   12177: =over 4
                   12178: 
                   12179: =item *
                   12180: 
1.810     raeburn  12181: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12182:  F: full access
                   12183:  U,I,K: authentication modes (cxx only)
                   12184:  '': forbidden
                   12185:  1: user needs to choose course
                   12186:  2: browse allowed
1.766     albertel 12187:  A: passphrase authentication needed
1.243     albertel 12188: 
                   12189: =item *
                   12190: 
1.1192    raeburn  12191: constructaccess($url,$setpriv) : check for access to construction space URL
                   12192: 
                   12193: See if the owner domain and name in the URL match those in the
                   12194: expected environment.  If so, return three element list
                   12195: ($ownername,$ownerdomain,$ownerhome).
                   12196: 
                   12197: Otherwise return the null string.
                   12198: 
                   12199: If second argument 'setpriv' is true, it assigns the privileges,
                   12200: and returns the same three element list, unless the owner has
                   12201: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12202: in which case the null string is returned.
                   12203: 
                   12204: =item *
                   12205: 
1.243     albertel 12206: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12207: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12208: and course level
                   12209: 
                   12210: =item *
                   12211: 
1.988     raeburn  12212: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12213: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12214: $type is Course (default) or Community.
1.988     raeburn  12215: If $forcedefault evaluates to true, text returned will be default 
                   12216: text for $type. Otherwise, if this is a course, the text returned 
                   12217: will be a custom name for the role (if defined in the course's 
                   12218: environment).  If no custom name is defined the default is returned.
                   12219:    
1.832     raeburn  12220: =item *
                   12221: 
1.935     raeburn  12222: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12223: All arguments are optional. Returns a hash of a roles, either for
                   12224: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12225: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12226: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12227: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12228: For each key, value is set to colon-separated start and end times for
                   12229: the role.  If no username and domain are specified, will default to
1.934     raeburn  12230: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12231: of role statuses (active, future or previous), roles 
                   12232: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12233: to restrict the list of roles reported. If no array ref is 
                   12234: provided for types, will default to return only active roles.
1.834     albertel 12235: 
1.243     albertel 12236: =back
                   12237: 
                   12238: =head2 User Modification
                   12239: 
                   12240: =over 4
                   12241: 
                   12242: =item *
                   12243: 
1.957     raeburn  12244: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12245: user for the level given by URL.  Optional start and end dates (leave empty
                   12246: string or zero for "no date")
1.191     harris41 12247: 
                   12248: =item *
                   12249: 
1.243     albertel 12250: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12251: change a users, password, possible return values are: ok,
                   12252: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12253: refused
1.191     harris41 12254: 
                   12255: =item *
                   12256: 
1.243     albertel 12257: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12258: 
                   12259: =item *
                   12260: 
1.1058    raeburn  12261: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12262:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12263: 
                   12264: will update user information (firstname,middlename,lastname,generation,
                   12265: permanentemail), and if forceid is true, student/employee ID also.
                   12266: A user's institutional affiliation(s) can also be updated.
                   12267: User information fields will not be overwritten with empty entries 
                   12268: unless the field is included in the $candelete array reference.
                   12269: This array is included when a single user is modified via "Manage Users",
                   12270: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12271: 
                   12272: =item *
                   12273: 
1.286     matthew  12274: modifystudent
                   12275: 
1.957     raeburn  12276: modify a student's enrollment and identification information.
1.286     matthew  12277: The course id is resolved based on the current users environment.  
                   12278: This means the envoking user must be a course coordinator or otherwise
                   12279: associated with a course.
                   12280: 
1.297     matthew  12281: This call is essentially a wrapper for lonnet::modifyuser and
                   12282: lonnet::modify_student_enrollment
1.286     matthew  12283: 
                   12284: Inputs: 
                   12285: 
                   12286: =over 4
                   12287: 
1.957     raeburn  12288: =item B<$udom> Student's loncapa domain
1.286     matthew  12289: 
1.957     raeburn  12290: =item B<$uname> Student's loncapa login name
1.286     matthew  12291: 
1.964     bisitz   12292: =item B<$uid> Student/Employee ID
1.286     matthew  12293: 
1.957     raeburn  12294: =item B<$umode> Student's authentication mode
1.286     matthew  12295: 
1.957     raeburn  12296: =item B<$upass> Student's password
1.286     matthew  12297: 
1.957     raeburn  12298: =item B<$first> Student's first name
1.286     matthew  12299: 
1.957     raeburn  12300: =item B<$middle> Student's middle name
1.286     matthew  12301: 
1.957     raeburn  12302: =item B<$last> Student's last name
1.286     matthew  12303: 
1.957     raeburn  12304: =item B<$gene> Student's generation
1.286     matthew  12305: 
1.957     raeburn  12306: =item B<$usec> Student's section in course
1.286     matthew  12307: 
                   12308: =item B<$end> Unix time of the roles expiration
                   12309: 
                   12310: =item B<$start> Unix time of the roles start date
                   12311: 
                   12312: =item B<$forceid> If defined, allow $uid to be changed
                   12313: 
                   12314: =item B<$desiredhome> server to use as home server for student
                   12315: 
1.957     raeburn  12316: =item B<$email> Student's permanent e-mail address
                   12317: 
                   12318: =item B<$type> Type of enrollment (auto or manual)
                   12319: 
1.963     raeburn  12320: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12321: 
                   12322: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12323: 
1.963     raeburn  12324: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12325: 
1.963     raeburn  12326: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12327: 
1.963     raeburn  12328: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  12329: 
1.286     matthew  12330: =back
1.297     matthew  12331: 
                   12332: =item *
                   12333: 
                   12334: modify_student_enrollment
                   12335: 
                   12336: Change a students enrollment status in a class.  The environment variable
                   12337: 'role.request.course' must be defined for this function to proceed.
                   12338: 
                   12339: Inputs:
                   12340: 
                   12341: =over 4
                   12342: 
                   12343: =item $udom, students domain
                   12344: 
                   12345: =item $uname, students name
                   12346: 
                   12347: =item $uid, students user id
                   12348: 
                   12349: =item $first, students first name
                   12350: 
                   12351: =item $middle
                   12352: 
                   12353: =item $last
                   12354: 
                   12355: =item $gene
                   12356: 
                   12357: =item $usec
                   12358: 
                   12359: =item $end
                   12360: 
                   12361: =item $start
                   12362: 
1.957     raeburn  12363: =item $type
                   12364: 
                   12365: =item $locktype
                   12366: 
                   12367: =item $cid
                   12368: 
                   12369: =item $selfenroll
                   12370: 
                   12371: =item $context
                   12372: 
1.297     matthew  12373: =back
                   12374: 
1.191     harris41 12375: 
                   12376: =item *
                   12377: 
1.243     albertel 12378: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12379: custom role; give a custom role to a user for the level given by URL.  Specify
                   12380: name and domain of role author, and role name
1.191     harris41 12381: 
                   12382: =item *
                   12383: 
1.243     albertel 12384: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12385: 
                   12386: =item *
                   12387: 
1.243     albertel 12388: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12389: 
                   12390: =back
                   12391: 
                   12392: =head2 Course Infomation
                   12393: 
                   12394: =over 4
1.191     harris41 12395: 
                   12396: =item *
                   12397: 
1.1118    foxr     12398: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12399: specified course id, including all environment settings for the
                   12400: course, the description of the course will be in the hash under the
                   12401: key 'description'
1.191     harris41 12402: 
1.1118    foxr     12403: $options is an optional parameter that if supplied is a hash reference that controls
                   12404: what how this function works.  It has the following key/values:
                   12405: 
                   12406: =over 4
                   12407: 
                   12408: =item freshen_cache
                   12409: 
                   12410: If defined, and the environment cache for the course is valid, it is 
                   12411: returned in the returned hash.
                   12412: 
                   12413: =item one_time
                   12414: 
                   12415: If defined, the last cache time is set to _now_
                   12416: 
                   12417: =item user
                   12418: 
                   12419: If defined, the supplied username is used instead of the current user.
                   12420: 
                   12421: 
                   12422: =back
                   12423: 
1.191     harris41 12424: =item *
                   12425: 
1.624     albertel 12426: resdata($name,$domain,$type,@which) : request for current parameter
                   12427: setting for a specific $type, where $type is either 'course' or 'user',
                   12428: @what should be a list of parameters to ask about. This routine caches
                   12429: answers for 5 minutes.
1.243     albertel 12430: 
1.877     foxr     12431: =item *
                   12432: 
                   12433: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12434: data base, returning a hash that is keyed by the resource name and has
                   12435: values that are the resource value.  I believe that the timestamps and
                   12436: versions are also returned.
                   12437: 
                   12438: 
1.243     albertel 12439: =back
                   12440: 
                   12441: =head2 Course Modification
                   12442: 
                   12443: =over 4
1.191     harris41 12444: 
                   12445: =item *
                   12446: 
1.243     albertel 12447: writecoursepref($courseid,%prefs) : write preferences (environment
                   12448: database) for a course
1.191     harris41 12449: 
                   12450: =item *
                   12451: 
1.1011    raeburn  12452: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12453: 
                   12454: =item *
                   12455: 
1.1038    raeburn  12456: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12457: 
1.1167    droeschl 12458: =item *
                   12459: 
                   12460: is_course($courseid), is_course($cdom, $cnum)
                   12461: 
                   12462: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12463: two component version $cdom, $cnum. It checks if the specified course exists.
                   12464: 
                   12465: Returns:
                   12466:     undef if the course doesn't exist, otherwise
                   12467:     in scalar context the combined courseid.
                   12468:     in list context the two components of the course identifier, domain and 
                   12469:     courseid.    
                   12470: 
1.243     albertel 12471: =back
                   12472: 
                   12473: =head2 Resource Subroutines
                   12474: 
                   12475: =over 4
1.191     harris41 12476: 
                   12477: =item *
                   12478: 
1.243     albertel 12479: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12480: 
                   12481: =item *
                   12482: 
1.243     albertel 12483: repcopy($filename) : subscribes to the requested file, and attempts to
                   12484: replicate from the owning library server, Might return
1.607     raeburn  12485: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12486: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12487: resource. Expects the local filesystem pathname
                   12488: (/home/httpd/html/res/....)
                   12489: 
                   12490: =back
                   12491: 
                   12492: =head2 Resource Information
                   12493: 
                   12494: =over 4
1.191     harris41 12495: 
                   12496: =item *
                   12497: 
1.243     albertel 12498: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12499: a vairety of different possible values, $varname should be a request
                   12500: string, and the other parameters can be used to specify who and what
                   12501: one is asking about.
                   12502: 
                   12503: Possible values for $varname are environment.lastname (or other item
                   12504: from the envirnment hash), user.name (or someother aspect about the
                   12505: user), resource.0.maxtries (or some other part and parameter of a
                   12506: resource)
1.204     albertel 12507: 
                   12508: =item *
                   12509: 
1.243     albertel 12510: directcondval($number) : get current value of a condition; reads from a state
                   12511: string
1.204     albertel 12512: 
                   12513: =item *
                   12514: 
1.243     albertel 12515: condval($condidx) : value of condition index based on state
1.204     albertel 12516: 
                   12517: =item *
                   12518: 
1.243     albertel 12519: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12520: resource's metadata, $what should be either a specific key, or either
                   12521: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12522: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12523: 
                   12524: this function automatically caches all requests
1.191     harris41 12525: 
                   12526: =item *
                   12527: 
1.243     albertel 12528: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12529: network of library servers; returns file handle of where SQL and regex results
                   12530: will be stored for query
1.191     harris41 12531: 
                   12532: =item *
                   12533: 
1.243     albertel 12534: symbread($filename) : return symbolic list entry (filename argument optional);
                   12535: returns the data handle
1.191     harris41 12536: 
                   12537: =item *
                   12538: 
1.1190    raeburn  12539: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12540: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12541: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12542: on failure, user must be in a course, as it assumes the existence of
                   12543: the course initial hash, and uses $env('request.course.id'}.  The third
                   12544: arg is an optional reference to a scalar.  If this arg is passed in the 
                   12545: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12546: encrypted; otherwise it will be null.  
1.191     harris41 12547: 
                   12548: =item *
                   12549: 
1.243     albertel 12550: symbclean($symb) : removes versions numbers from a symb, returns the
                   12551: cleaned symb
1.191     harris41 12552: 
                   12553: =item *
                   12554: 
1.243     albertel 12555: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12556: course map, user must be in a course for it to work.
1.191     harris41 12557: 
                   12558: =item *
                   12559: 
1.243     albertel 12560: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12561: 
                   12562: =item *
                   12563: 
1.243     albertel 12564: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12565: a random seed, all arguments are optional, if they aren't sent it uses the
                   12566: environment to derive them. Note: if symb isn't sent and it can't get one
                   12567: from &symbread it will use the current time as its return value
1.191     harris41 12568: 
                   12569: =item *
                   12570: 
1.243     albertel 12571: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12572: unfakeable, receipt
1.191     harris41 12573: 
                   12574: =item *
                   12575: 
1.620     albertel 12576: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12577: 
                   12578: =item *
                   12579: 
1.243     albertel 12580: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12581: 
                   12582: =item *
                   12583: 
1.243     albertel 12584: 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 12585: 
                   12586: =item *
                   12587: 
1.243     albertel 12588: 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 12589: 
                   12590: =item *
                   12591: 
1.243     albertel 12592: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12593: 
                   12594: =item *
                   12595: 
1.243     albertel 12596: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12597: forcing spreadsheet to reevaluate the resource scores next time.
                   12598: 
                   12599: =back
                   12600: 
                   12601: =head2 Storing/Retreiving Data
                   12602: 
                   12603: =over 4
1.191     harris41 12604: 
                   12605: =item *
                   12606: 
1.243     albertel 12607: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12608: for this url; hashref needs to be given and should be a \%hashname; the
                   12609: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12610: be derived from the env
1.191     harris41 12611: 
                   12612: =item *
                   12613: 
1.243     albertel 12614: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12615: uses critical subroutine
1.191     harris41 12616: 
                   12617: =item *
                   12618: 
1.243     albertel 12619: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12620: all args are optional
1.191     harris41 12621: 
                   12622: =item *
                   12623: 
1.717     albertel 12624: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12625: dumps the complete (or key matching regexp) namespace into a hash
                   12626: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12627: normally &store()ed into
                   12628: 
                   12629: $range should be either an integer '100' (give me the first 100
                   12630:                                            matching records)
                   12631:               or be  two integers sperated by a - with no spaces
                   12632:                  '30-50' (give me the 30th through the 50th matching
                   12633:                           records)
                   12634: 
                   12635: 
                   12636: =item *
                   12637: 
                   12638: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12639: replaces a &store() version of data with a replacement set of data
                   12640: for a particular resource in a namespace passed in the $storehash hash 
                   12641: reference
                   12642: 
                   12643: =item *
                   12644: 
1.243     albertel 12645: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12646: works very similar to store/cstore, but all data is stored in a
                   12647: temporary location and can be reset using tmpreset, $storehash should
                   12648: be a hash reference, returns nothing on success
1.191     harris41 12649: 
                   12650: =item *
                   12651: 
1.243     albertel 12652: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12653: similar to restore, but all data is stored in a temporary location and
                   12654: can be reset using tmpreset. Returns a hash of values on success,
                   12655: error string otherwise.
1.191     harris41 12656: 
                   12657: =item *
                   12658: 
1.243     albertel 12659: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12660: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12661: 
                   12662: =item *
                   12663: 
1.243     albertel 12664: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12665: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12666: 
                   12667: =item *
                   12668: 
1.243     albertel 12669: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12670: namesp ($udom and $uname are optional)
1.191     harris41 12671: 
                   12672: =item *
                   12673: 
1.702     albertel 12674: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12675: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12676: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12677: 
1.702     albertel 12678: $range should be either an integer '100' (give me the first 100
                   12679:                                            matching records)
                   12680:               or be  two integers sperated by a - with no spaces
                   12681:                  '30-50' (give me the 30th through the 50th matching
                   12682:                           records)
1.449     matthew  12683: =item *
                   12684: 
                   12685: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12686: $store can be a scalar, an array reference, or if the amount to be 
                   12687: incremented is > 1, a hash reference.
                   12688: 
                   12689: ($udom and $uname are optional)
1.191     harris41 12690: 
                   12691: =item *
                   12692: 
1.243     albertel 12693: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12694: ($udom and $uname are optional)
1.191     harris41 12695: 
                   12696: =item *
                   12697: 
1.243     albertel 12698: cput($namespace,$storehash,$udom,$uname) : critical put
                   12699: ($udom and $uname are optional)
1.191     harris41 12700: 
                   12701: =item *
                   12702: 
1.748     albertel 12703: newput($namespace,$storehash,$udom,$uname) :
                   12704: 
                   12705: Attempts to store the items in the $storehash, but only if they don't
                   12706: currently exist, if this succeeds you can be certain that you have 
                   12707: successfully created a new key value pair in the $namespace db.
                   12708: 
                   12709: 
                   12710: Args:
                   12711:  $namespace: name of database to store values to
                   12712:  $storehash: hashref to store to the db
                   12713:  $udom: (optional) domain of user containing the db
                   12714:  $uname: (optional) name of user caontaining the db
                   12715: 
                   12716: Returns:
                   12717:  'ok' -> succeeded in storing all keys of $storehash
                   12718:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12719:                         least <key> already existed in the db (other
                   12720:                         requested keys may also already exist)
1.967     bisitz   12721:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12722:  'con_lost' -> unable to contact request server
                   12723:  'refused' -> action was not allowed by remote machine
                   12724: 
                   12725: 
                   12726: =item *
                   12727: 
1.243     albertel 12728: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12729: reference filled in from namesp (encrypts the return communication)
                   12730: ($udom and $uname are optional)
1.191     harris41 12731: 
                   12732: =item *
                   12733: 
1.243     albertel 12734: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12735: critical subroutine
                   12736: 
1.806     raeburn  12737: =item *
                   12738: 
1.860     raeburn  12739: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12740: array reference filled in from namespace found in domain level on either
                   12741: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12742: 
                   12743: =item *
                   12744: 
1.860     raeburn  12745: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12746: domain level either on specified domain server ($uhome) or primary domain 
                   12747: server ($udom and $uhome are optional)
1.806     raeburn  12748: 
1.943     raeburn  12749: =item * 
                   12750: 
                   12751: get_domain_defaults($target_domain) : returns hash with defaults for
                   12752: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12753: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12754: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12755: Values are retrieved from cache (if current), or from domain's configuration.db
                   12756: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12757: or lonTabs/domain.tab. 
                   12758: 
                   12759: %domdefaults = &get_auth_defaults($target_domain);
                   12760: 
1.243     albertel 12761: =back
                   12762: 
                   12763: =head2 Network Status Functions
                   12764: 
                   12765: =over 4
1.191     harris41 12766: 
                   12767: =item *
                   12768: 
1.1137    raeburn  12769: dirlist() : return directory list based on URI (first arg).
                   12770: 
                   12771: Inputs: 1 required, 5 optional.
                   12772: 
                   12773: =over
                   12774: 
                   12775: =item 
                   12776: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12777: 
                   12778: =item
                   12779: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12780: 
                   12781: =item
                   12782: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12783: 
                   12784: =item
                   12785: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12786: 
                   12787: =item
                   12788: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12789: 
                   12790: =item 
                   12791: $alternateRoot - path to prepend in place of path from $uri.
                   12792: 
                   12793: =back
                   12794: 
                   12795: Returns: Array of up to two items.
                   12796: 
                   12797: =over
                   12798: 
                   12799: a reference to an array of files/subdirectories
                   12800: 
                   12801: =over
                   12802: 
                   12803: Each element in the array of files/subdirectories is a & separated list of
                   12804: item name and the result of running stat on the item.  If dirlist was requested
                   12805: for a file instead of a directory, the item name will be ''. For a directory 
                   12806: listing, if the item is a metadata file, the element will end &N&M 
                   12807: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12808: default copyright set (1).  
                   12809: 
                   12810: =back
                   12811: 
                   12812: a scalar containing error condition (if encountered).
                   12813: 
                   12814: =over
                   12815: 
                   12816: =item 
                   12817: no_host (no homeserver identified for $username:$domain).
                   12818: 
                   12819: =item 
                   12820: no_such_host (server contacted for listing not identified as valid host).
                   12821: 
                   12822: =item 
                   12823: con_lost (connection to remote server failed).
                   12824: 
                   12825: =item 
                   12826: refused (invalid $username:$domain received on lond side).
                   12827: 
                   12828: =item 
                   12829: no_such_dir (directory at specified path on lond side does not exist). 
                   12830: 
                   12831: =item 
                   12832: empty (directory at specified path on lond side is empty).
                   12833: 
                   12834: =over
                   12835: 
                   12836: This is currently not encountered because the &ls3, &ls2, 
                   12837: &ls (_handler) routines on the lond side do not filter out
                   12838: . and .. from a directory listing. 
                   12839: 
                   12840: =back
                   12841: 
                   12842: =back
                   12843: 
                   12844: =back
1.191     harris41 12845: 
                   12846: =item *
                   12847: 
1.243     albertel 12848: spareserver() : find server with least workload from spare.tab
                   12849: 
1.986     foxr     12850: 
                   12851: =item *
                   12852: 
                   12853: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12854: if there is no corresponding loncapa host.
                   12855: 
1.243     albertel 12856: =back
                   12857: 
1.986     foxr     12858: 
1.243     albertel 12859: =head2 Apache Request
                   12860: 
                   12861: =over 4
1.191     harris41 12862: 
                   12863: =item *
                   12864: 
1.243     albertel 12865: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12866: localhost, posts hash
                   12867: 
                   12868: =back
                   12869: 
                   12870: =head2 Data to String to Data
                   12871: 
                   12872: =over 4
1.191     harris41 12873: 
                   12874: =item *
                   12875: 
1.243     albertel 12876: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12877: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12878: 
                   12879: =item *
                   12880: 
1.243     albertel 12881: hashref2str($hashref) : convert a hashref into a string complete with
                   12882: escaping and '=' and '&' separators, supports elements that are
                   12883: arrayrefs and hashrefs
1.191     harris41 12884: 
                   12885: =item *
                   12886: 
1.243     albertel 12887: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12888: with escaping and '&' separators, supports elements that are arrayrefs
                   12889: and hashrefs
1.191     harris41 12890: 
                   12891: =item *
                   12892: 
1.243     albertel 12893: str2hash($string) : convert string to hash using unescaping and
                   12894: splitting on '=' and '&', supports elements that are arrayrefs and
                   12895: hashrefs
1.191     harris41 12896: 
                   12897: =item *
                   12898: 
1.243     albertel 12899: str2array($string) : convert string to hash using unescaping and
                   12900: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12901: 
                   12902: =back
                   12903: 
                   12904: =head2 Logging Routines
                   12905: 
                   12906: 
                   12907: These routines allow one to make log messages in the lonnet.log and
                   12908: lonnet.perm logfiles.
1.191     harris41 12909: 
1.1119    foxr     12910: =over 4
                   12911: 
1.191     harris41 12912: =item *
                   12913: 
1.243     albertel 12914: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12915: 
                   12916: =item *
                   12917: 
1.243     albertel 12918: logthis() : append message to the normal lonnet.log file, it gets
                   12919: preiodically rolled over and deleted.
1.191     harris41 12920: 
                   12921: =item *
                   12922: 
1.243     albertel 12923: logperm() : append a permanent message to lonnet.perm.log, this log
                   12924: file never gets deleted by any automated portion of the system, only
                   12925: messages of critical importance should go in here.
                   12926: 
1.1119    foxr     12927: 
1.243     albertel 12928: =back
                   12929: 
                   12930: =head2 General File Helper Routines
                   12931: 
                   12932: =over 4
1.191     harris41 12933: 
                   12934: =item *
                   12935: 
1.481     raeburn  12936: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12937: (a) files in /uploaded
                   12938:   (i) If a local copy of the file exists - 
                   12939:       compares modification date of local copy with last-modified date for 
                   12940:       definitive version stored on home server for course. If local copy is 
                   12941:       stale, requests a new version from the home server and stores it. 
                   12942:       If the original has been removed from the home server, then local copy 
                   12943:       is unlinked.
                   12944:   (ii) If local copy does not exist -
                   12945:       requests the file from the home server and stores it. 
                   12946:   
                   12947:   If $caller is 'uploadrep':  
                   12948:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12949:     for request for files originally uploaded via DOCS. 
                   12950:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12951:   
                   12952:   Otherwise:
                   12953:      This indicates a call from the content generation phase of the request.
                   12954:      -  returns the entire contents of the file or -1.
                   12955:      
                   12956: (b) files in /res
                   12957:    - returns the entire contents of a file or -1; 
                   12958:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12959: 
1.712     albertel 12960: 
                   12961: =item *
                   12962: 
                   12963: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12964:                   reference
                   12965: 
                   12966: returns either a stat() list of data about the file or an empty list
                   12967: if the file doesn't exist or couldn't find out about it (connection
                   12968: problems or user unknown)
                   12969: 
1.191     harris41 12970: =item *
                   12971: 
1.243     albertel 12972: filelocation($dir,$file) : returns file system location of a file
                   12973: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12974: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12975: and a file of ../bob will become /a/bob)
1.191     harris41 12976: 
                   12977: =item *
                   12978: 
                   12979: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12980: filelocation except for hrefs
                   12981: 
                   12982: =item *
                   12983: 
                   12984: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12985: 
1.243     albertel 12986: =back
                   12987: 
1.608     albertel 12988: =head2 Usererfile file routines (/uploaded*)
                   12989: 
                   12990: =over 4
                   12991: 
                   12992: =item *
                   12993: 
                   12994: userfileupload(): main rotine for putting a file in a user or course's
                   12995:                   filespace, arguments are,
                   12996: 
1.620     albertel 12997:  formname - required - this is the name of the element in $env where the
1.608     albertel 12998:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12999:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13000:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13001:  context - if coursedoc, store the file in the course of the active role
                   13002:              of the current user; 
                   13003:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13004:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13005:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13006:          if undefined, it will be placed in "unknown"
                   13007: 
                   13008:  (This routine calls clean_filename() to remove any dangerous
                   13009:  characters from the filename, and then calls finuserfileupload() to
                   13010:  complete the transaction)
                   13011: 
                   13012:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13013:  and /adm/notfound.html if unsuccessful
                   13014: 
                   13015: =item *
                   13016: 
                   13017: clean_filename(): routine for cleaing a filename up for storage in
                   13018:                  userfile space, argument is:
                   13019: 
                   13020:  filename - proposed filename
                   13021: 
                   13022: returns: the new clean filename
                   13023: 
                   13024: =item *
                   13025: 
1.1090    raeburn  13026: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13027: userspace, probably shouldn't be called directly
                   13028: 
                   13029:   docuname: username or courseid of destination for the file
                   13030:   docudom: domain of user/course of destination for the file
                   13031:   formname: same as for userfileupload()
1.1090    raeburn  13032:   fname: filename (including subdirectories) for the file
                   13033:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13034:   allfiles: reference to hash used to store objects found by parser
                   13035:   codebase: reference to hash used for codebases of java objects found by parser
                   13036:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13037:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13038:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13039:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13040:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13041:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13042:   mimetype: reference to scalar to accommodate mime type determined
                   13043:             from File::MMagic if $parser = parse.
1.608     albertel 13044: 
                   13045:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13046:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13047:  was 'overwrite').
                   13048:  
1.608     albertel 13049: 
                   13050: =item *
                   13051: 
                   13052: renameuserfile(): renames an existing userfile to a new name
                   13053: 
                   13054:   Args:
                   13055:    docuname: username or courseid of destination for the file
                   13056:    docudom: domain of user/course of destination for the file
                   13057:    old: current file name (including any subdirs under userfiles)
                   13058:    new: desired file name (including any subdirs under userfiles)
                   13059: 
                   13060: =item *
                   13061: 
                   13062: mkdiruserfile(): creates a directory is a userfiles dir
                   13063: 
                   13064:   Args:
                   13065:    docuname: username or courseid of destination for the file
                   13066:    docudom: domain of user/course of destination for the file
                   13067:    dir: dir to create (including any subdirs under userfiles)
                   13068: 
                   13069: =item *
                   13070: 
                   13071: removeuserfile(): removes a file that exists in userfiles
                   13072: 
                   13073:   Args:
                   13074:    docuname: username or courseid of destination for the file
                   13075:    docudom: domain of user/course of destination for the file
                   13076:    fname: filname to delete (including any subdirs under userfiles)
                   13077: 
                   13078: =item *
                   13079: 
                   13080: removeuploadedurl(): convience function for removeuserfile()
                   13081: 
                   13082:   Args:
                   13083:    url:  a full /uploaded/... url to delete
                   13084: 
1.747     albertel 13085: =item * 
                   13086: 
                   13087: get_portfile_permissions():
                   13088:   Args:
                   13089:     domain: domain of user or course contain the portfolio files
                   13090:     user: name of user or num of course contain the portfolio files
                   13091:   Returns:
                   13092:     hashref of a dump of the proper file_permissions.db
                   13093:    
                   13094: 
                   13095: =item * 
                   13096: 
                   13097: get_access_controls():
                   13098: 
                   13099: Args:
                   13100:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13101:   group: (optional) the group you want the files associated with
                   13102:   file: (optional) the file you want access info on
                   13103: 
                   13104: Returns:
1.749     raeburn  13105:     a hash (keys are file names) of hashes containing
                   13106:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13107:         values are XML containing access control settings (see below) 
1.747     albertel 13108: 
                   13109: Internal notes:
                   13110: 
1.749     raeburn  13111:  access controls are stored in file_permissions.db as key=value pairs.
                   13112:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13113:         where scope -> public,guest,course,group,domains or users.
                   13114:               end -> UNIX time for end of access (0 -> no end date)
                   13115:               start -> UNIX time for start of access
                   13116: 
                   13117:     value -> XML description of access control
                   13118:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13119:             <start></start>
                   13120:             <end></end>
                   13121: 
                   13122:             <password></password>  for scope type = guest
                   13123: 
                   13124:             <domain></domain>     for scope type = course or group
                   13125:             <number></number>
                   13126:             <roles id="">
                   13127:              <role></role>
                   13128:              <access></access>
                   13129:              <section></section>
                   13130:              <group></group>
                   13131:             </roles>
                   13132: 
                   13133:             <dom></dom>         for scope type = domains
                   13134: 
                   13135:             <users>             for scope type = users
                   13136:              <user>
                   13137:               <uname></uname>
                   13138:               <udom></udom>
                   13139:              </user>
                   13140:             </users>
                   13141:            </scope> 
                   13142:               
                   13143:  Access data is also aggregated for each file in an additional key=value pair:
                   13144:  key -> path to file/file_name\0accesscontrol 
                   13145:  value -> reference to hash
                   13146:           hash contains key = value pairs
                   13147:           where key = uniqueID:scope_end_start
                   13148:                 value = UNIX time record was last updated
                   13149: 
                   13150:           Used to improve speed of look-ups of access controls for each file.  
                   13151:  
                   13152:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13153: 
                   13154: modify_access_controls():
                   13155: 
                   13156: Modifies access controls for a portfolio file
                   13157: Args
                   13158: 1. file name
                   13159: 2. reference to hash of required changes,
                   13160: 3. domain
                   13161: 4. username
                   13162:   where domain,username are the domain of the portfolio owner 
                   13163:   (either a user or a course) 
                   13164: 
                   13165: Returns:
                   13166: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13167: 2. result of deletions ('ok' or 'error', with error message).
                   13168: 3. reference to hash of any new or updated access controls.
                   13169: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13170:    key = integer (inbound ID)
                   13171:    value = uniqueID  
1.747     albertel 13172: 
1.608     albertel 13173: =back
                   13174: 
1.243     albertel 13175: =head2 HTTP Helper Routines
                   13176: 
                   13177: =over 4
                   13178: 
1.191     harris41 13179: =item *
                   13180: 
                   13181: escape() : unpack non-word characters into CGI-compatible hex codes
                   13182: 
                   13183: =item *
                   13184: 
                   13185: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13186: 
1.243     albertel 13187: =back
                   13188: 
                   13189: =head1 PRIVATE SUBROUTINES
                   13190: 
                   13191: =head2 Underlying communication routines (Shouldn't call)
                   13192: 
                   13193: =over 4
                   13194: 
                   13195: =item *
                   13196: 
                   13197: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13198: 
                   13199: =item *
                   13200: 
                   13201: reply() : uses subreply to send a message to remote machine, logs all failures
                   13202: 
                   13203: =item *
                   13204: 
                   13205: critical() : passes a critical message to another server; if cannot
                   13206: get through then place message in connection buffer directory and
                   13207: returns con_delayed, if incapable of saving message, returns
                   13208: con_failed
                   13209: 
                   13210: =item *
                   13211: 
                   13212: reconlonc() : tries to reconnect lonc client processes.
                   13213: 
                   13214: =back
                   13215: 
                   13216: =head2 Resource Access Logging
                   13217: 
                   13218: =over 4
                   13219: 
                   13220: =item *
                   13221: 
                   13222: flushcourselogs() : flush (save) buffer logs and access logs
                   13223: 
                   13224: =item *
                   13225: 
                   13226: courselog($what) : save message for course in hash
                   13227: 
                   13228: =item *
                   13229: 
                   13230: courseacclog($what) : save message for course using &courselog().  Perform
                   13231: special processing for specific resource types (problems, exams, quizzes, etc).
                   13232: 
1.191     harris41 13233: =item *
                   13234: 
                   13235: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13236: as a PerlChildExitHandler
1.243     albertel 13237: 
                   13238: =back
                   13239: 
                   13240: =head2 Other
                   13241: 
                   13242: =over 4
                   13243: 
                   13244: =item *
                   13245: 
                   13246: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13247: 
                   13248: =back
                   13249: 
                   13250: =cut
1.877     foxr     13251: 

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