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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1197  ! raeburn     4: # $Id: lonnet.pm,v 1.1196 2012/11/10 13:58:31 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: #
1.1196    raeburn  2656: #  input: six args -- filename (decluttered), course number, course domain,
                   2657: #                   url, symb (if registered) and group (if this is a group
                   2658: #                   item -- e.g., bulletin board, group page etc.).
                   2659: #  output: array of five scalars -- 
1.1193    raeburn  2660: #          $cfile -- url for file editing if editable on current server
                   2661: #          $home -- homeserver of resource (i.e., for author if published,
                   2662: #                                           or course if uploaded.).
                   2663: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2664: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2665: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2666: #
                   2667: 
                   2668: sub can_edit_resource {
1.1194    raeburn  2669:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2670:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2671: #
                   2672: # For aboutme pages user can only edit his/her own.
                   2673: #
                   2674:     if ($resurl =~ m{^/adm/($match_domain)/($match_username)/aboutme$}) {
                   2675:         my ($sdom,$sname) = ($1,$2);
                   2676:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2677:             $home = $env{'user.home'};
                   2678:             $cfile = $resurl;
                   2679:             if ($env{'form.forceedit'}) {
                   2680:                 $forceview = 1;
                   2681:             } else {
                   2682:                 $forceedit = 1;
                   2683:             }
                   2684:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2685:         } else {
                   2686:             return;
                   2687:         }
                   2688:     }
                   2689: 
                   2690:     if ($env{'request.course.id'}) {
                   2691:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2692:         if ($group ne '') {
                   2693: # if this is a group homepage or group bulletin board, check group privs
                   2694:             my $allowed = 0;
1.1197  ! raeburn  2695:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
        !          2696:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1194    raeburn  2697:                             ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2698:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2699:                     $allowed = 1;
                   2700:                 }
1.1197  ! raeburn  2701:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
        !          2702:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
        !          2703:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2704:                     $allowed = 1;
                   2705:                 }
                   2706:             }
                   2707:             if ($allowed) {
                   2708:                 $home=&homeserver($cnum,$cdom);
                   2709:                 if ($env{'form.forceedit'}) {
                   2710:                     $forceview = 1;
                   2711:                 } else {
                   2712:                     $forceedit = 1;
                   2713:                 }
                   2714:                 $cfile = $resurl;
                   2715:             } else {
                   2716:                 return;
                   2717:             }
                   2718:         } else {
                   2719: #
                   2720: # No edit allowed where CC has switched to student role.
                   2721: #
                   2722:             unless ($crsedit) {
                   2723:                 return;
                   2724:             }
                   2725:         }
                   2726:     }
                   2727: 
1.1193    raeburn  2728:     if ($file ne '') {
                   2729:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2730:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2731:                 $uploaded = 1;
                   2732:                 $incourse = 1;
1.1193    raeburn  2733:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2734:                     $cfile = &hreflocation('',$file);
1.1194    raeburn  2735:                     $forceedit = 1;
                   2736:                 }
                   2737:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2738:                 $incourse = 1;
                   2739:                 if ($env{'form.forceedit'}) {
                   2740:                     $forceview = 1;
                   2741:                 } else {
                   2742:                     $forceedit = 1;
                   2743:                 }
                   2744:                 $cfile = $resurl;
                   2745:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2746:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2747:                     $incourse = 1;
                   2748:                     if ($env{'form.forceedit'}) {
                   2749:                         $forceview = 1;
                   2750:                     } else {
                   2751:                         $forceedit = 1;
                   2752:                     }
                   2753:                     $cfile = $resurl;
                   2754:                 } elsif (($resurl eq '/res/lib/templates/simpleproblem.problem')) {
                   2755:                     $incourse = 1;
                   2756:                     $cfile = $resurl.'/smpedit';
                   2757:                 } elsif ($resurl =~ /ext/) {
                   2758:                     $incourse = 1;
                   2759:                     # is external
                   2760:                 }
                   2761:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2762:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2763:                 if (&is_on_map($template)) { 
                   2764:                     $incourse = 1;
                   2765:                     $forceview = 1;
                   2766:                     $cfile = $template;
1.1193    raeburn  2767:                 }
                   2768:             }
                   2769:         }
1.1194    raeburn  2770:         if ($uploaded || $incourse) {
                   2771:             $home=&homeserver($cnum,$cdom);
                   2772:         } else {
1.1193    raeburn  2773:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2774:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2775:             # Check that the user has permission to edit this resource
                   2776:             my $setpriv = 1;
                   2777:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2778:             if (defined($cfudom)) {
                   2779:                 $home=&homeserver($cfuname,$cfudom);
                   2780:                 $cfile=$file;
                   2781:             }
                   2782:         }
1.1194    raeburn  2783:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2784:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2785:             my @ids=&current_machine_ids();
                   2786:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2787:                 $switchserver=1;
                   2788:             }
                   2789:         }
                   2790:     }
1.1194    raeburn  2791:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2792: }
                   2793: 
                   2794: sub is_course_upload {
                   2795:     my ($file,$cnum,$cdom) = @_;
                   2796:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2797:     $uploadpath =~ s{^\/}{};
                   2798:     if (($file =~ m{^\Q$uploadpath\E/userfiles/docs/}) ||
                   2799:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/docs/})) {
                   2800:         return 1;
                   2801:     }
                   2802:     return;
                   2803: }
                   2804: 
1.1194    raeburn  2805: sub in_course {
1.1195    raeburn  2806:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2807:     if ($hideprivileged) {
                   2808:         my $skipuser;
                   2809:         if (&privileged($uname,$udom)) {
                   2810:             $skipuser = 1;
                   2811:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2812:             if ($coursehash{'nothideprivileged'}) {
                   2813:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2814:                     my $user;
                   2815:                     if ($item =~ /:/) {
                   2816:                         $user = $item;
                   2817:                     } else {
                   2818:                         $user = join(':',split(/[\@]/,$item));
                   2819:                     }
                   2820:                     if ($user eq $uname.':'.$udom) {
                   2821:                         undef($skipuser);
                   2822:                         last;
                   2823:                     }
                   2824:                 }
                   2825:             }
                   2826:             if ($skipuser) {
                   2827:                 return 0;
                   2828:             }
                   2829:         }
                   2830:     }
1.1194    raeburn  2831:     $type ||= 'any';
                   2832:     if (!defined($cdom) || !defined($cnum)) {
                   2833:         my $cid  = $env{'request.course.id'};
                   2834:         $cdom = $env{'course.'.$cid.'.domain'};
                   2835:         $cnum = $env{'course.'.$cid.'.num'};
                   2836:     }
                   2837:     my $typesref;
1.1195    raeburn  2838:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  2839:         $typesref = ['active','previous','future'];
                   2840:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2841:         $typesref = [$type];
                   2842:     }
                   2843:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2844:                               $typesref,undef,[$cdom]);
                   2845:     my ($tmp) = keys(%roles);
                   2846:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2847:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2848:     if (@course_roles > 0) {
                   2849:         return 1;
                   2850:     }
                   2851:     return 0;
                   2852: }
                   2853: 
1.478     albertel 2854: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2855: # input: action, courseID, current domain, intended
1.637     raeburn  2856: #        path to file, source of file, instruction to parse file for objects,
                   2857: #        ref to hash for embedded objects,
                   2858: #        ref to hash for codebase of java objects.
1.1095    raeburn  2859: #        reference to scalar to accommodate mime type determined
                   2860: #          from File::MMagic if $parser = parse.
1.637     raeburn  2861: #
1.485     raeburn  2862: # output: url to file (if action was uploaddoc), 
                   2863: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2864: #
1.478     albertel 2865: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2866: # course.
1.477     raeburn  2867: #
1.478     albertel 2868: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2869: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2870: #          course's home server.
1.477     raeburn  2871: #
1.478     albertel 2872: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2873: #          be copied from $source (current location) to 
                   2874: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2875: #         and will then be copied to
                   2876: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2877: #         course's home server.
1.485     raeburn  2878: #
1.481     raeburn  2879: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2880: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2881: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2882: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2883: #         in course's home server.
1.637     raeburn  2884: #
1.477     raeburn  2885: 
                   2886: sub process_coursefile {
1.1095    raeburn  2887:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2888:         $mimetype)=@_;
1.477     raeburn  2889:     my $fetchresult;
1.638     albertel 2890:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2891:     if ($action eq 'propagate') {
1.638     albertel 2892:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2893: 			     $home);
1.481     raeburn  2894:     } else {
1.477     raeburn  2895:         my $fpath = '';
                   2896:         my $fname = $file;
1.478     albertel 2897:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2898:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2899:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2900:         if ($action eq 'copy') {
                   2901:             if ($source eq '') {
                   2902:                 $fetchresult = 'no source file';
                   2903:                 return $fetchresult;
                   2904:             } else {
                   2905:                 my $destination = $filepath.'/'.$fname;
                   2906:                 rename($source,$destination);
                   2907:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2908:                                  $home);
1.481     raeburn  2909:             }
                   2910:         } elsif ($action eq 'uploaddoc') {
                   2911:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2912:             print $fh $env{'form.'.$source};
1.481     raeburn  2913:             close($fh);
1.637     raeburn  2914:             if ($parser eq 'parse') {
1.1024    raeburn  2915:                 my $mm = new File::MMagic;
1.1095    raeburn  2916:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2917:                 if ($type eq 'text/html') {
1.1024    raeburn  2918:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2919:                     unless ($parse_result eq 'ok') {
                   2920:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2921:                     }
1.637     raeburn  2922:                 }
1.1095    raeburn  2923:                 if (ref($mimetype)) {
                   2924:                     $$mimetype = $type;
                   2925:                 } 
1.637     raeburn  2926:             }
1.477     raeburn  2927:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2928:                                  $home);
1.481     raeburn  2929:             if ($fetchresult eq 'ok') {
                   2930:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2931:             } else {
                   2932:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2933:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2934:                 return '/adm/notfound.html';
                   2935:             }
1.477     raeburn  2936:         }
                   2937:     }
1.485     raeburn  2938:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2939:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2940:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2941:     }
                   2942:     return $fetchresult;
                   2943: }
                   2944: 
1.637     raeburn  2945: sub build_filepath {
                   2946:     my ($fpath) = @_;
                   2947:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2948:     unless ($fpath eq '') {
                   2949:         my @parts=split('/',$fpath);
                   2950:         foreach my $part (@parts) {
                   2951:             $filepath.= '/'.$part;
                   2952:             if ((-e $filepath)!=1) {
                   2953:                 mkdir($filepath,0777);
                   2954:             }
                   2955:         }
                   2956:     }
                   2957:     return $filepath;
                   2958: }
                   2959: 
                   2960: sub store_edited_file {
1.638     albertel 2961:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2962:     my $file = $primary_url;
                   2963:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2964:     my $fpath = '';
                   2965:     my $fname = $file;
                   2966:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2967:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2968:     my $filepath = &build_filepath($fpath);
                   2969:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2970:     print $fh $content;
                   2971:     close($fh);
1.638     albertel 2972:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2973:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2974: 			  $home);
1.637     raeburn  2975:     if ($$fetchresult eq 'ok') {
                   2976:         return '/uploaded/'.$fpath.'/'.$fname;
                   2977:     } else {
1.638     albertel 2978:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2979: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2980:         return '/adm/notfound.html';
                   2981:     }
                   2982: }
                   2983: 
1.531     albertel 2984: sub clean_filename {
1.831     albertel 2985:     my ($fname,$args)=@_;
1.315     www      2986: # Replace Windows backslashes by forward slashes
1.257     www      2987:     $fname=~s/\\/\//g;
1.831     albertel 2988:     if (!$args->{'keep_path'}) {
                   2989:         # Get rid of everything but the actual filename
                   2990: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2991:     }
1.315     www      2992: # Replace spaces by underscores
                   2993:     $fname=~s/\s+/\_/g;
                   2994: # Replace all other weird characters by nothing
1.831     albertel 2995:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2996: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2997: # numbers
                   2998:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2999:     return $fname;
                   3000: }
1.1051    raeburn  3001: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3002: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3003: # image with the same aspect ratio as the original, but with dimensions which do 
                   3004: # not exceed $resizewidth and $resizeheight.
                   3005:  
1.984     neumanie 3006: sub resizeImage {
1.1051    raeburn  3007:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3008:     my $ima = Image::Magick->new;
                   3009:     my $resized;
                   3010:     if (-e $img_path) {
                   3011:         $ima->Read($img_path);
                   3012:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3013:             my $width = $ima->Get('width');
                   3014:             my $height = $ima->Get('height');
                   3015:             if ($width > $resizewidth) {
                   3016: 	        my $factor = $width/$resizewidth;
                   3017:                 my $newheight = $height/$factor;
                   3018:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3019:                 $resized = 1;
                   3020:             }
                   3021:         }
                   3022:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3023:             my $width = $ima->Get('width');
                   3024:             my $height = $ima->Get('height');
                   3025:             if ($height > $resizeheight) {
                   3026:                 my $factor = $height/$resizeheight;
                   3027:                 my $newwidth = $width/$factor;
                   3028:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3029:                 $resized = 1;
                   3030:             }
                   3031:         }
                   3032:         if ($resized) {
                   3033:             $ima->Write($img_path);
                   3034:         }
                   3035:     }
                   3036:     return;
1.977     amueller 3037: }
                   3038: 
1.608     albertel 3039: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3040: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3041: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3042: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3043: #                                    canceloverwrite, or ''. 
                   3044: #                   if 'coursedoc': upload to the current course
                   3045: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3046: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3047: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3048: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3049: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3050: #        $allfiles - reference to hash for embedded objects
                   3051: #        $codebase - reference to hash for codebase of java objects
                   3052: #        $desuname - username for permanent storage of uploaded file
                   3053: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3054: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3055: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3056: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3057: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3058: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3059: #                    from File::MMagic.
1.858     raeburn  3060: # 
1.686     albertel 3061: # output: url of file in userspace, or error: <message> 
                   3062: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3063: 
1.531     albertel 3064: sub userfileupload {
1.1090    raeburn  3065:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3066:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3067:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3068:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3069:     $fname=&clean_filename($fname);
1.1090    raeburn  3070:     # See if there is anything left
1.257     www      3071:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3072:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3073:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3074:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3075:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3076:         my $now = time;
1.1090    raeburn  3077:         my $filepath;
1.1095    raeburn  3078:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3079:              $filepath = 'tmp/helprequests/'.$now;
                   3080:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3081:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3082:                          '_'.$env{'user.domain'}.'/pending';
                   3083:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3084:             my ($docuname,$docudom);
                   3085:             if ($destudom) {
                   3086:                 $docudom = $destudom;
                   3087:             } else {
                   3088:                 $docudom = $env{'user.domain'};
                   3089:             }
                   3090:             if ($destuname) {
                   3091:                 $docuname = $destuname;
                   3092:             } else {
                   3093:                 $docuname = $env{'user.name'};
                   3094:             }
                   3095:             if (exists($env{'form.group'})) {
                   3096:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3097:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3098:             }
                   3099:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3100:             if ($context eq 'canceloverwrite') {
                   3101:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3102:                 if (-e  $tempfile) {
                   3103:                     my @info = stat($tempfile);
                   3104:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3105:                         unlink($tempfile);
                   3106:                     }
                   3107:                 }
                   3108:                 return;
1.523     raeburn  3109:             }
                   3110:         }
1.1090    raeburn  3111:         # Create the directory if not present
1.741     raeburn  3112:         my @parts=split(/\//,$filepath);
                   3113:         my $fullpath = $perlvar{'lonDaemons'};
                   3114:         for (my $i=0;$i<@parts;$i++) {
                   3115:             $fullpath .= '/'.$parts[$i];
                   3116:             if ((-e $fullpath)!=1) {
                   3117:                 mkdir($fullpath,0777);
                   3118:             }
                   3119:         }
                   3120:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3121:         print $fh $env{'form.'.$formname};
                   3122:         close($fh);
1.1090    raeburn  3123:         if ($context eq 'existingfile') {
                   3124:             my @info = stat($fullpath.'/'.$fname);
                   3125:             return ($fullpath.'/'.$fname,$info[9]);
                   3126:         } else {
                   3127:             return $fullpath.'/'.$fname;
                   3128:         }
1.523     raeburn  3129:     }
1.995     raeburn  3130:     if ($subdir eq 'scantron') {
                   3131:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3132:     } else {
1.995     raeburn  3133:         $fname="$subdir/$fname";
                   3134:     }
1.1090    raeburn  3135:     if ($context eq 'coursedoc') {
1.638     albertel 3136: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3137: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3138:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3139:             return &finishuserfileupload($docuname,$docudom,
                   3140: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3141: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3142:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3143:         } else {
1.620     albertel 3144:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 3145:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3146: 				       $fname,$formname,$parser,
1.1095    raeburn  3147: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3148:         }
1.719     banghart 3149:     } elsif (defined($destuname)) {
                   3150:         my $docuname=$destuname;
                   3151:         my $docudom=$destudom;
1.860     raeburn  3152: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3153: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3154:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3155:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3156:     } else {
1.638     albertel 3157:         my $docuname=$env{'user.name'};
                   3158:         my $docudom=$env{'user.domain'};
1.714     raeburn  3159:         if (exists($env{'form.group'})) {
                   3160:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3161:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3162:         }
1.860     raeburn  3163: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3164: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3165:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3166:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3167:     }
1.271     www      3168: }
                   3169: 
                   3170: sub finishuserfileupload {
1.860     raeburn  3171:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3172:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3173:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3174:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3175:   
1.860     raeburn  3176:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3177:     $file=$fname;
                   3178:     if ($fname=~m|/|) {
                   3179:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3180: 	$path.=$fnamepath.'/';
                   3181:     }
1.259     www      3182:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3183:     my $count;
                   3184:     for ($count=4;$count<=$#parts;$count++) {
                   3185:         $filepath.="/$parts[$count]";
                   3186:         if ((-e $filepath)!=1) {
                   3187: 	    mkdir($filepath,0777);
                   3188:         }
                   3189:     }
1.984     neumanie 3190: 
1.258     www      3191: # Save the file
                   3192:     {
1.701     albertel 3193: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3194: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3195: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3196: 	    return '/adm/notfound.html';
                   3197: 	}
1.1090    raeburn  3198:         if ($context eq 'overwrite') {
1.1117    foxr     3199:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3200:             my $target = $filepath.'/'.$file;
                   3201:             if (-e $source) {
                   3202:                 my @info = stat($source);
                   3203:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3204:                     unless (&File::Copy::move($source,$target)) {
                   3205:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3206:                         return "Moving from $source failed";
                   3207:                     }
                   3208:                 } else {
                   3209:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3210:                 }
                   3211:             } else {
                   3212:                 return "Temporary file: $source missing";
                   3213:             }
                   3214:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3215: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3216: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3217: 	    return '/adm/notfound.html';
                   3218: 	}
1.570     albertel 3219: 	close(FH);
1.1051    raeburn  3220:         if ($resizewidth && $resizeheight) {
                   3221:             my $mm = new File::MMagic;
                   3222:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3223:             if ($mime_type =~ m{^image/}) {
                   3224: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3225:             }  
1.977     amueller 3226: 	}
1.258     www      3227:     }
1.1152    raeburn  3228:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3229:         if (ref($mimetype)) {
                   3230:             if ($$mimetype eq '') {
                   3231:                 my $mm = new File::MMagic;
                   3232:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3233:                 $$mimetype = $type;
                   3234:             }
                   3235:         }
                   3236:     }
1.637     raeburn  3237:     if ($parser eq 'parse') {
1.1152    raeburn  3238:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3239:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3240:                                                        $allfiles,$codebase);
                   3241:             unless ($parse_result eq 'ok') {
                   3242:                 &logthis('Failed to parse '.$filepath.$file.
                   3243: 	   	         ' for embedded media: '.$parse_result); 
                   3244:             }
1.637     raeburn  3245:         }
                   3246:     }
1.860     raeburn  3247:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3248:         my $input = $filepath.'/'.$file;
                   3249:         my $output = $filepath.'/'.'tn-'.$file;
                   3250:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3251:         system("convert -sample $thumbsize $input $output");
                   3252:         if (-e $filepath.'/'.'tn-'.$file) {
                   3253:             $fetchthumb  = 1; 
                   3254:         }
                   3255:     }
1.858     raeburn  3256:  
1.259     www      3257: # Notify homeserver to grep it
                   3258: #
1.984     neumanie 3259:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3260:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3261:     if ($fetchresult eq 'ok') {
1.860     raeburn  3262:         if ($fetchthumb) {
                   3263:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3264:             if ($thumbresult ne 'ok') {
                   3265:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3266:                          $docuhome.': '.$thumbresult);
                   3267:             }
                   3268:         }
1.259     www      3269: #
1.258     www      3270: # Return the URL to it
1.494     albertel 3271:         return '/uploaded/'.$path.$file;
1.263     www      3272:     } else {
1.494     albertel 3273:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3274: 		 ': '.$fetchresult);
1.263     www      3275:         return '/adm/notfound.html';
1.858     raeburn  3276:     }
1.493     albertel 3277: }
                   3278: 
1.637     raeburn  3279: sub extract_embedded_items {
1.961     raeburn  3280:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3281:     my @state = ();
1.1164    raeburn  3282:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3283:     my %javafiles = (
                   3284:                       codebase => '',
                   3285:                       code => '',
                   3286:                       archive => ''
                   3287:                     );
                   3288:     my %mediafiles = (
                   3289:                       src => '',
                   3290:                       movie => '',
                   3291:                      );
1.648     raeburn  3292:     my $p;
                   3293:     if ($content) {
                   3294:         $p = HTML::LCParser->new($content);
                   3295:     } else {
1.961     raeburn  3296:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3297:     }
1.641     albertel 3298:     while (my $t=$p->get_token()) {
1.640     albertel 3299: 	if ($t->[0] eq 'S') {
                   3300: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3301: 	    push(@state, $tagname);
1.648     raeburn  3302:             if (lc($tagname) eq 'allow') {
                   3303:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3304:             }
1.640     albertel 3305: 	    if (lc($tagname) eq 'img') {
                   3306: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3307: 	    }
1.886     albertel 3308: 	    if (lc($tagname) eq 'a') {
                   3309: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3310: 	    }
1.645     raeburn  3311:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3312:                 my $src;
1.645     raeburn  3313:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3314:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3315:                 } else {
1.1164    raeburn  3316:                     if ($attr->{'src'} ne '') {
                   3317:                         $src = $attr->{'src'};
                   3318:                         &add_filetype($allfiles,$src,'src');
                   3319:                     }
                   3320:                 }
                   3321:                 my $text = $p->get_trimmed_text();
                   3322:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3323:                     my @swfargs = split(/,/,$1);
                   3324:                     foreach my $item (@swfargs) {
                   3325:                         $item =~ s/["']//g;
                   3326:                         $item =~ s/^\s+//;
                   3327:                         $item =~ s/\s+$//;
                   3328:                     }
                   3329:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3330:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3331:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3332:                         } else {
                   3333:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3334:                         }
                   3335:                     }
1.645     raeburn  3336:                 }
                   3337:             }
                   3338:             if (lc($tagname) eq 'link') {
                   3339:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3340:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3341:                 }
                   3342:             }
1.640     albertel 3343: 	    if (lc($tagname) eq 'object' ||
                   3344: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3345: 		foreach my $item (keys(%javafiles)) {
                   3346: 		    $javafiles{$item} = '';
                   3347: 		}
1.1164    raeburn  3348:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3349:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3350:                 }
1.640     albertel 3351: 	    }
                   3352: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3353: 		my $name = lc($attr->{'name'});
                   3354: 		foreach my $item (keys(%javafiles)) {
                   3355: 		    if ($name eq $item) {
                   3356: 			$javafiles{$item} = $attr->{'value'};
                   3357: 			last;
                   3358: 		    }
                   3359: 		}
1.1164    raeburn  3360:                 my $pathfrom;
1.640     albertel 3361: 		foreach my $item (keys(%mediafiles)) {
                   3362: 		    if ($name eq $item) {
1.1164    raeburn  3363:                         $pathfrom = $attr->{'value'};
                   3364:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3365: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3366: 			last;
                   3367: 		    }
                   3368: 		}
1.1164    raeburn  3369:                 if ($name eq 'flashvars') {
                   3370:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3371:                 }
                   3372:                 if ($pathfrom ne '') {
                   3373:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3374:                                          $pathfrom);
                   3375:                 }
1.640     albertel 3376: 	    }
                   3377: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3378: 		foreach my $item (keys(%javafiles)) {
                   3379: 		    if ($attr->{$item}) {
                   3380: 			$javafiles{$item} = $attr->{$item};
                   3381: 			last;
                   3382: 		    }
                   3383: 		}
                   3384: 		foreach my $item (keys(%mediafiles)) {
                   3385: 		    if ($attr->{$item}) {
                   3386: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3387: 			last;
                   3388: 		    }
                   3389: 		}
1.1164    raeburn  3390:                 if (lc($tagname) eq 'embed') {
                   3391:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3392:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3393:                                              $attr->{'src'});
                   3394:                     }
                   3395:                 }
1.640     albertel 3396: 	    }
1.1164    raeburn  3397:             if ($t->[4] =~ m{/>$}) {
                   3398:                 pop(@state);  
                   3399:             }
1.640     albertel 3400: 	} elsif ($t->[0] eq 'E') {
                   3401: 	    my ($tagname) = ($t->[1]);
                   3402: 	    if ($javafiles{'codebase'} ne '') {
                   3403: 		$javafiles{'codebase'} .= '/';
                   3404: 	    }  
                   3405: 	    if (lc($tagname) eq 'applet' ||
                   3406: 		lc($tagname) eq 'object' ||
                   3407: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3408: 		) {
                   3409: 		foreach my $item (keys(%javafiles)) {
                   3410: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3411: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3412: 			&add_filetype($allfiles,$file,$item);
                   3413: 		    }
                   3414: 		}
                   3415: 	    } 
                   3416: 	    pop @state;
                   3417: 	}
                   3418:     }
1.1164    raeburn  3419:     foreach my $id (sort(keys(%flashvars))) {
                   3420:         if ($shockwave{$id} ne '') {
                   3421:             my @pairs = split(/\&/,$flashvars{$id});
                   3422:             foreach my $pair (@pairs) {
                   3423:                 my ($key,$value) = split(/\=/,$pair);
                   3424:                 if ($key eq 'thumb') {
                   3425:                     &add_filetype($allfiles,$value,$key);
                   3426:                 } elsif ($key eq 'content') {
                   3427:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3428:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3429:                     if ($ext ne '') {
                   3430:                         &add_filetype($allfiles,$path.$value,$ext);
                   3431:                     }
                   3432:                 }
                   3433:             }
                   3434:         }
                   3435:     }
1.637     raeburn  3436:     return 'ok';
                   3437: }
                   3438: 
1.639     albertel 3439: sub add_filetype {
                   3440:     my ($allfiles,$file,$type)=@_;
                   3441:     if (exists($allfiles->{$file})) {
                   3442: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3443: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3444: 	}
                   3445:     } else {
                   3446: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3447:     }
                   3448: }
                   3449: 
1.1164    raeburn  3450: sub embedded_dependency {
                   3451:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3452:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3453:         if (($identifier ne '') &&
                   3454:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3455:             ($pathfrom ne '')) {
                   3456:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3457:             foreach my $dep (@{$related->{$identifier}}) {
                   3458:                 &add_filetype($allfiles,$path.$dep,'object');
                   3459:             }
                   3460:         }
                   3461:     }
                   3462:     return;
                   3463: }
                   3464: 
1.493     albertel 3465: sub removeuploadedurl {
1.984     neumanie 3466:     my ($url)=@_;	
                   3467:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3468:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3469: }
                   3470: 
                   3471: sub removeuserfile {
                   3472:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3473:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3474:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3475:     if ($result eq 'ok') {	
1.798     raeburn  3476:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3477:             my $metafile = $fname.'.meta';
                   3478:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3479: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3480:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3481:             my $sqlresult = 
1.823     albertel 3482:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3483:                                         'portfolio_metadata',$group,
                   3484:                                         'delete');
1.798     raeburn  3485:         }
                   3486:     }
                   3487:     return $result;
1.257     www      3488: }
1.15      www      3489: 
1.530     albertel 3490: sub mkdiruserfile {
                   3491:     my ($docuname,$docudom,$dir)=@_;
                   3492:     my $home=&homeserver($docuname,$docudom);
                   3493:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3494: }
                   3495: 
1.531     albertel 3496: sub renameuserfile {
                   3497:     my ($docuname,$docudom,$old,$new)=@_;
                   3498:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3499:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3500:                         &escape("$old").':'.&escape("$new"),$home);
                   3501:     if ($result eq 'ok') {
                   3502:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3503:             my $oldmeta = $old.'.meta';
                   3504:             my $newmeta = $new.'.meta';
                   3505:             my $metaresult = 
                   3506:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3507: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3508:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3509:             my $sqlresult = 
1.823     albertel 3510:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3511:                                         'portfolio_metadata',$group,
                   3512:                                         'delete');
1.798     raeburn  3513:         }
                   3514:     }
                   3515:     return $result;
1.531     albertel 3516: }
                   3517: 
1.14      www      3518: # ------------------------------------------------------------------------- Log
                   3519: 
                   3520: sub log {
                   3521:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3522:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3523: }
                   3524: 
                   3525: # ------------------------------------------------------------------ Course Log
1.352     www      3526: #
                   3527: # This routine flushes several buffers of non-mission-critical nature
                   3528: #
1.157     www      3529: 
                   3530: sub flushcourselogs {
1.352     www      3531:     &logthis('Flushing log buffers');
                   3532: #
                   3533: # course logs
                   3534: # This is a log of all transactions in a course, which can be used
                   3535: # for data mining purposes
                   3536: #
                   3537: # It also collects the courseid database, which lists last transaction
                   3538: # times and course titles for all courseids
                   3539: #
                   3540:     my %courseidbuffer=();
1.921     raeburn  3541:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3542:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3543: 		          &escape($courselogs{$crsid}),
                   3544: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3545: 	    delete $courselogs{$crsid};
                   3546:         } else {
                   3547:             &logthis('Failed to flush log buffer for '.$crsid);
                   3548:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3549:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3550:                         " exceeded maximum size, deleting.</font>");
                   3551:                delete $courselogs{$crsid};
                   3552:             }
1.352     www      3553:         }
1.920     raeburn  3554:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3555:             'description' => $coursedescrbuf{$crsid},
                   3556:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3557:             'type'        => $coursetypebuf{$crsid},
                   3558:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3559:         };
1.191     harris41 3560:     }
1.352     www      3561: #
                   3562: # Write course id database (reverse lookup) to homeserver of courses 
                   3563: # Is used in pickcourse
                   3564: #
1.840     albertel 3565:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3566:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3567:                                     $courseidbuffer{$crs_home},
                   3568:                                     $crs_home,'timeonly');
1.352     www      3569:     }
                   3570: #
                   3571: # File accesses
                   3572: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3573: #
1.449     matthew  3574:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3575:         if ($entry =~ /___count$/) {
                   3576:             my ($dom,$name);
1.807     albertel 3577:             ($dom,$name,undef)=
1.811     albertel 3578: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3579:             if (! defined($dom) || $dom eq '' || 
                   3580:                 ! defined($name) || $name eq '') {
1.620     albertel 3581:                 my $cid = $env{'request.course.id'};
                   3582:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3583:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3584:             }
1.450     matthew  3585:             my $value = $accesshash{$entry};
                   3586:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3587:             my %temphash=($url => $value);
1.449     matthew  3588:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3589:             if ($result eq 'ok') {
                   3590:                 delete $accesshash{$entry};
                   3591:             }
                   3592:         } else {
1.811     albertel 3593:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3594:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3595:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3596:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3597:                 delete $accesshash{$entry};
                   3598:             }
1.185     www      3599:         }
1.191     harris41 3600:     }
1.352     www      3601: #
                   3602: # Roles
                   3603: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3604: #
1.800     albertel 3605:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3606:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3607: 	    split(/\:/,$entry);
                   3608:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3609:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3610:                 $rudom,$runame) eq 'ok') {
                   3611: 	    delete $userrolehash{$entry};
                   3612:         }
                   3613:     }
1.662     raeburn  3614: #
                   3615: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3616: #
                   3617:     my %domrolebuffer = ();
1.1000    raeburn  3618:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3619:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3620:         if ($domrolebuffer{$rudom}) {
                   3621:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3622:                       '='.&escape($domainrolehash{$entry});
                   3623:         } else {
                   3624:             $domrolebuffer{$rudom}.=&escape($entry).
                   3625:                       '='.&escape($domainrolehash{$entry});
                   3626:         }
                   3627:         delete $domainrolehash{$entry};
                   3628:     }
                   3629:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3630: 	my %servers = &get_servers($dom,'library');
                   3631: 	foreach my $tryserver (keys(%servers)) {
                   3632: 	    unless (&reply('domroleput:'.$dom.':'.
                   3633: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3634: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3635: 	    }
1.662     raeburn  3636:         }
                   3637:     }
1.186     www      3638:     $dumpcount++;
1.157     www      3639: }
                   3640: 
                   3641: sub courselog {
                   3642:     my $what=shift;
1.158     www      3643:     $what=time.':'.$what;
1.620     albertel 3644:     unless ($env{'request.course.id'}) { return ''; }
                   3645:     $coursedombuf{$env{'request.course.id'}}=
                   3646:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3647:     $coursenumbuf{$env{'request.course.id'}}=
                   3648:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3649:     $coursehombuf{$env{'request.course.id'}}=
                   3650:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3651:     $coursedescrbuf{$env{'request.course.id'}}=
                   3652:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3653:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3654:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3655:     $courseownerbuf{$env{'request.course.id'}}=
                   3656:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3657:     $coursetypebuf{$env{'request.course.id'}}=
                   3658:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3659:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3660: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3661:     } else {
1.620     albertel 3662: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3663:     }
1.620     albertel 3664:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3665: 	&flushcourselogs();
                   3666:     }
1.158     www      3667: }
                   3668: 
                   3669: sub courseacclog {
                   3670:     my $fnsymb=shift;
1.620     albertel 3671:     unless ($env{'request.course.id'}) { return ''; }
                   3672:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3673:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3674:         $what.=':POST';
1.583     matthew  3675:         # FIXME: Probably ought to escape things....
1.800     albertel 3676: 	foreach my $key (keys(%env)) {
                   3677:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3678:                 my $formitem = $1;
                   3679:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3680:                     $what.=':'.$formitem.'='.$env{$key};
                   3681:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3682:                     $what.=':'.$formitem.'='.$env{$key};
                   3683:                 }
1.158     www      3684:             }
1.191     harris41 3685:         }
1.583     matthew  3686:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3687:         # FIXME: We should not be depending on a form parameter that someone
                   3688:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3689:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3690:             $what.= ':POST';
                   3691:             # FIXME: Probably ought to escape things....
                   3692:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3693:                                  'crsdiscuss') {
1.620     albertel 3694:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3695:             }
                   3696:         }
1.158     www      3697:     }
                   3698:     &courselog($what);
1.149     www      3699: }
                   3700: 
1.185     www      3701: sub countacc {
                   3702:     my $url=&declutter(shift);
1.458     matthew  3703:     return if (! defined($url) || $url eq '');
1.620     albertel 3704:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3705: #
                   3706: # Mark that this url was used in this course
                   3707: #
1.620     albertel 3708:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3709: #
                   3710: # Increase the access count for this resource in this child process
                   3711: #
1.281     www      3712:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3713:     $accesshash{$key}++;
1.185     www      3714: }
1.349     www      3715: 
1.361     www      3716: sub linklog {
                   3717:     my ($from,$to)=@_;
                   3718:     $from=&declutter($from);
                   3719:     $to=&declutter($to);
                   3720:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3721:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3722: }
1.1160    www      3723: 
                   3724: sub statslog {
                   3725:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3726:     if ($users<2) { return; }
                   3727:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3728:             'course'       => $env{'request.course.id'},
                   3729:             'sections'     => '"all"',
                   3730:             'num_students' => $users,
                   3731:             'part'         => $part,
                   3732:             'symb'         => $symb,
                   3733:             'mean_tries'   => $av_attempts,
                   3734:             'deg_of_diff'  => $degdiff});
                   3735:     foreach my $key (keys(%dynstore)) {
                   3736:         $accesshash{$key}=$dynstore{$key};
                   3737:     }
                   3738: }
1.361     www      3739:   
1.349     www      3740: sub userrolelog {
                   3741:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3742:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3743:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3744:        $userrolehash
                   3745:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3746:                     =$tend.':'.$tstart;
1.662     raeburn  3747:     }
1.1169    droeschl 3748:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3749:        $userrolehash
                   3750:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3751:                     =$tend.':'.$tstart;
                   3752:     }
1.1169    droeschl 3753:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3754:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3755:        $domainrolehash
                   3756:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3757:                     = $tend.':'.$tstart;
                   3758:     }
1.351     www      3759: }
                   3760: 
1.957     raeburn  3761: sub courserolelog {
                   3762:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3763:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3764:         my $cdom = $1;
                   3765:         my $cnum = $2;
                   3766:         my $sec = $3;
                   3767:         my $namespace = 'rolelog';
                   3768:         my %storehash = (
                   3769:                            role    => $trole,
                   3770:                            start   => $tstart,
                   3771:                            end     => $tend,
                   3772:                            selfenroll => $selfenroll,
                   3773:                            context    => $context,
                   3774:                         );
                   3775:         if ($trole eq 'gr') {
                   3776:             $namespace = 'groupslog';
                   3777:             $storehash{'group'} = $sec;
                   3778:         } else {
                   3779:             $storehash{'section'} = $sec;
                   3780:         }
1.1188    raeburn  3781:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3782:                    $domain,$cnum,$cdom);
1.1184    raeburn  3783:         if (($trole ne 'st') || ($sec ne '')) {
                   3784:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3785:         }
                   3786:     }
                   3787:     return;
                   3788: }
                   3789: 
1.1184    raeburn  3790: sub domainrolelog {
                   3791:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3792:     if ($area =~ m{^/($match_domain)/$}) {
                   3793:         my $cdom = $1;
                   3794:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3795:         my $namespace = 'rolelog';
                   3796:         my %storehash = (
                   3797:                            role    => $trole,
                   3798:                            start   => $tstart,
                   3799:                            end     => $tend,
                   3800:                            context => $context,
                   3801:                         );
1.1188    raeburn  3802:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3803:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3804:     }
                   3805:     return;
                   3806: 
                   3807: }
                   3808: 
                   3809: sub coauthorrolelog {
                   3810:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3811:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3812:         my $audom = $1;
                   3813:         my $auname = $2;
                   3814:         my $namespace = 'rolelog';
                   3815:         my %storehash = (
                   3816:                            role    => $trole,
                   3817:                            start   => $tstart,
                   3818:                            end     => $tend,
                   3819:                            context => $context,
                   3820:                         );
1.1188    raeburn  3821:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3822:                    $domain,$auname,$audom);
1.1184    raeburn  3823:     }
                   3824:     return;
                   3825: }
                   3826: 
1.351     www      3827: sub get_course_adv_roles {
1.948     raeburn  3828:     my ($cid,$codes) = @_;
1.620     albertel 3829:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3830:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3831:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3832:     my %nothide=();
1.800     albertel 3833:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3834:         if ($user !~ /:/) {
                   3835: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3836:         } else {
                   3837:             $nothide{$user}=1;
                   3838:         }
1.470     www      3839:     }
1.351     www      3840:     my %returnhash=();
                   3841:     my %dumphash=
                   3842:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3843:     my $now=time;
1.997     raeburn  3844:     my %privileged;
1.1000    raeburn  3845:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3846: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3847:         if (($tstart) && ($tstart<0)) { next; }
                   3848:         if (($tend) && ($tend<$now)) { next; }
                   3849:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3850:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3851: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3852:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3853:             my %dompersonnel =
1.998     raeburn  3854:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3855:             $privileged{$domain} = {};
                   3856:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3857:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3858:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3859:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3860:                         $privileged{$udom}{$uname} = 1;
                   3861:                     }
                   3862:                 }
                   3863:             }
                   3864:         }
                   3865:         if ((exists($privileged{$domain}{$username})) && 
                   3866:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3867: 	if ($role eq 'cr') { next; }
1.948     raeburn  3868:         if ($codes) {
                   3869:             if ($section) { $role .= ':'.$section; }
                   3870:             if ($returnhash{$role}) {
                   3871:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3872:             } else {
                   3873:                 $returnhash{$role}=$username.':'.$domain;
                   3874:             }
1.351     www      3875:         } else {
1.988     raeburn  3876:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3877:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3878:             if ($returnhash{$key}) {
                   3879: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3880:             } else {
                   3881:                 $returnhash{$key}=$username.':'.$domain;
                   3882:             }
1.351     www      3883:         }
1.948     raeburn  3884:     }
1.400     www      3885:     return %returnhash;
                   3886: }
                   3887: 
                   3888: sub get_my_roles {
1.937     raeburn  3889:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3890:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3891:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3892:     my (%dumphash,%nothide);
1.1086    raeburn  3893:     if ($context eq 'userroles') {
1.1166    raeburn  3894:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3895:     } else {
                   3896:         %dumphash=
1.400     www      3897:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3898:         if ($hidepriv) {
                   3899:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3900:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3901:                 if ($user !~ /:/) {
                   3902:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3903:                 } else {
                   3904:                     $nothide{$user} = 1;
                   3905:                 }
                   3906:             }
                   3907:         }
1.858     raeburn  3908:     }
1.400     www      3909:     my %returnhash=();
                   3910:     my $now=time;
1.999     raeburn  3911:     my %privileged;
1.800     albertel 3912:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3913:         my ($role,$tend,$tstart);
                   3914:         if ($context eq 'userroles') {
1.1149    raeburn  3915:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3916: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3917:         } else {
                   3918:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3919:         }
1.400     www      3920:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3921:         my $status = 'active';
1.939     raeburn  3922:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3923:             $status = 'previous';
                   3924:         } 
                   3925:         if (($tstart) && ($now<$tstart)) {
                   3926:             $status = 'future';
                   3927:         }
                   3928:         if (ref($types) eq 'ARRAY') {
                   3929:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3930:                 next;
                   3931:             } 
                   3932:         } else {
                   3933:             if ($status ne 'active') {
                   3934:                 next;
                   3935:             }
                   3936:         }
1.867     raeburn  3937:         my ($rolecode,$username,$domain,$section,$area);
                   3938:         if ($context eq 'userroles') {
1.1186    raeburn  3939:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3940:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3941:         } else {
                   3942:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3943:         }
1.832     raeburn  3944:         if (ref($roledoms) eq 'ARRAY') {
                   3945:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3946:                 next;
                   3947:             }
                   3948:         }
                   3949:         if (ref($roles) eq 'ARRAY') {
                   3950:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3951:                 if ($role =~ /^cr\//) {
                   3952:                     if (!grep(/^cr$/,@{$roles})) {
                   3953:                         next;
                   3954:                     }
1.1104    raeburn  3955:                 } elsif ($role =~ /^gr\//) {
                   3956:                     if (!grep(/^gr$/,@{$roles})) {
                   3957:                         next;
                   3958:                     }
1.922     raeburn  3959:                 } else {
                   3960:                     next;
                   3961:                 }
1.832     raeburn  3962:             }
1.867     raeburn  3963:         }
1.937     raeburn  3964:         if ($hidepriv) {
1.999     raeburn  3965:             if ($context eq 'userroles') {
                   3966:                 if ((&privileged($username,$domain)) &&
                   3967:                     (!$nothide{$username.':'.$domain})) {
                   3968:                     next;
                   3969:                 }
                   3970:             } else {
                   3971:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3972:                     my %dompersonnel =
                   3973:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3974:                     $privileged{$domain} = {};
                   3975:                     if (keys(%dompersonnel)) {
                   3976:                         foreach my $server (keys(%dompersonnel)) {
                   3977:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3978:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3979:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3980:                                     $privileged{$udom}{$uname} = $trole;
                   3981:                                 }
                   3982:                             }
                   3983:                         }
                   3984:                     }
                   3985:                 }
                   3986:                 if (exists($privileged{$domain}{$username})) {
                   3987:                     if (!$nothide{$username.':'.$domain}) {
                   3988:                         next;
                   3989:                     }
                   3990:                 }
1.937     raeburn  3991:             }
                   3992:         }
1.933     raeburn  3993:         if ($withsec) {
                   3994:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3995:                 $tstart.':'.$tend;
                   3996:         } else {
                   3997:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3998:         }
1.832     raeburn  3999:     }
1.373     www      4000:     return %returnhash;
1.399     www      4001: }
                   4002: 
                   4003: # ----------------------------------------------------- Frontpage Announcements
                   4004: #
                   4005: #
                   4006: 
                   4007: sub postannounce {
                   4008:     my ($server,$text)=@_;
1.844     albertel 4009:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4010:     unless ($text=~/\w/) { $text=''; }
                   4011:     return &reply('setannounce:'.&escape($text),$server);
                   4012: }
                   4013: 
                   4014: sub getannounce {
1.448     albertel 4015: 
                   4016:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4017: 	my $announcement='';
1.800     albertel 4018: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4019: 	close($fh);
1.399     www      4020: 	if ($announcement=~/\w/) { 
                   4021: 	    return 
                   4022:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4023:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4024: 	} else {
                   4025: 	    return '';
                   4026: 	}
                   4027:     } else {
                   4028: 	return '';
                   4029:     }
1.351     www      4030: }
1.353     www      4031: 
                   4032: # ---------------------------------------------------------- Course ID routines
                   4033: # Deal with domain's nohist_courseid.db files
                   4034: #
                   4035: 
                   4036: sub courseidput {
1.921     raeburn  4037:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4038:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4039:     my $outcome;
                   4040:     if ($caller eq 'timeonly') {
                   4041:         my $cids = '';
                   4042:         foreach my $item (keys(%$storehash)) {
                   4043:             $cids.=&escape($item).'&';
                   4044:         }
                   4045:         $cids=~s/\&$//;
                   4046:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4047:                           $coursehome);       
                   4048:     } else {
                   4049:         my $items = '';
                   4050:         foreach my $item (keys(%$storehash)) {
                   4051:             $items.= &escape($item).'='.
                   4052:                      &freeze_escape($$storehash{$item}).'&';
                   4053:         }
                   4054:         $items=~s/\&$//;
                   4055:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4056:                           $coursehome);
1.918     raeburn  4057:     }
                   4058:     if ($outcome eq 'unknown_cmd') {
                   4059:         my $what;
                   4060:         foreach my $cid (keys(%$storehash)) {
                   4061:             $what .= &escape($cid).'=';
1.921     raeburn  4062:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4063:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4064:             }
                   4065:             $what =~ s/\:$/&/;
                   4066:         }
                   4067:         $what =~ s/\&$//;  
                   4068:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4069:     } else {
                   4070:         return $outcome;
                   4071:     }
1.353     www      4072: }
                   4073: 
                   4074: sub courseiddump {
1.921     raeburn  4075:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4076:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4077:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4078:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4079:     my $as_hash = 1;
                   4080:     my %returnhash;
                   4081:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4082:     my %libserv = &all_library();
                   4083:     foreach my $tryserver (keys(%libserv)) {
                   4084:         if ( (  $hostidflag == 1 
                   4085: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4086: 	     || (!defined($hostidflag)) ) {
                   4087: 
1.918     raeburn  4088: 	    if (($domfilter eq '') ||
                   4089: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4090:                 my $rep;
                   4091:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4092:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4093:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4094:                                 &escape($descfilter), &escape($instcodefilter), 
                   4095:                                 &escape($ownerfilter), &escape($coursefilter),
                   4096:                                 &escape($typefilter), &escape($regexp_ok), 
                   4097:                                 $as_hash, &escape($selfenrollonly), 
                   4098:                                 &escape($catfilter), $showhidden, $caller, 
                   4099:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4100:                                 &escape($createdbefore), &escape($createdafter), 
                   4101:                                 &escape($creationcontext), $domcloner)));
                   4102:                 } else {
                   4103:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4104:                              $sincefilter.':'.&escape($descfilter).':'.
                   4105:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4106:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4107:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4108:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4109:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4110:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4111:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4112:                              &escape($creationcontext).':'.$domcloner,
                   4113:                              $tryserver);
                   4114:                 }
                   4115:                      
1.918     raeburn  4116:                 my @pairs=split(/\&/,$rep);
                   4117:                 foreach my $item (@pairs) {
                   4118:                     my ($key,$value)=split(/\=/,$item,2);
                   4119:                     $key = &unescape($key);
                   4120:                     next if ($key =~ /^error: 2 /);
                   4121:                     my $result = &thaw_unescape($value);
                   4122:                     if (ref($result) eq 'HASH') {
                   4123:                         $returnhash{$key}=$result;
                   4124:                     } else {
1.921     raeburn  4125:                         my @responses = split(/:/,$value);
                   4126:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4127:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4128:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4129:                         }
1.1008    raeburn  4130:                     }
1.353     www      4131:                 }
                   4132:             }
                   4133:         }
                   4134:     }
                   4135:     return %returnhash;
                   4136: }
                   4137: 
1.1055    raeburn  4138: sub courselastaccess {
                   4139:     my ($cdom,$cnum,$hostidref) = @_;
                   4140:     my %returnhash;
                   4141:     if ($cdom && $cnum) {
                   4142:         my $chome = &homeserver($cnum,$cdom);
                   4143:         if ($chome ne 'no_host') {
                   4144:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4145:             &extract_lastaccess(\%returnhash,$rep);
                   4146:         }
                   4147:     } else {
                   4148:         if (!$cdom) { $cdom=''; }
                   4149:         my %libserv = &all_library();
                   4150:         foreach my $tryserver (keys(%libserv)) {
                   4151:             if (ref($hostidref) eq 'ARRAY') {
                   4152:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4153:             } 
                   4154:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4155:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4156:                 &extract_lastaccess(\%returnhash,$rep);
                   4157:             }
                   4158:         }
                   4159:     }
                   4160:     return %returnhash;
                   4161: }
                   4162: 
                   4163: sub extract_lastaccess {
                   4164:     my ($returnhash,$rep) = @_;
                   4165:     if (ref($returnhash) eq 'HASH') {
                   4166:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4167:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4168:                  $rep eq '') {
                   4169:             my @pairs=split(/\&/,$rep);
                   4170:             foreach my $item (@pairs) {
                   4171:                 my ($key,$value)=split(/\=/,$item,2);
                   4172:                 $key = &unescape($key);
                   4173:                 next if ($key =~ /^error: 2 /);
                   4174:                 $returnhash->{$key} = &thaw_unescape($value);
                   4175:             }
                   4176:         }
                   4177:     }
                   4178:     return;
                   4179: }
                   4180: 
1.658     raeburn  4181: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4182: 
                   4183: sub dcmailput {
1.685     raeburn  4184:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4185:     my $status = &Apache::lonnet::critical(
1.740     www      4186:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4187:        &escape($message),$server);
1.662     raeburn  4188:     return $status;
                   4189: }
                   4190: 
1.658     raeburn  4191: sub dcmaildump {
                   4192:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4193:     my %returnhash=();
1.846     albertel 4194: 
                   4195:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4196:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4197:                                                          &escape($enddate).':';
                   4198: 	my @esc_senders=map { &escape($_)} @$senders;
                   4199: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4200: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4201:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4202:             if (($key) && ($value)) {
                   4203:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4204:             }
                   4205:         }
                   4206:     }
                   4207:     return %returnhash;
                   4208: }
1.662     raeburn  4209: # ---------------------------------------------------------- Domain roles
                   4210: 
                   4211: sub get_domain_roles {
                   4212:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4213:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4214:         $startdate = '.';
                   4215:     }
1.1018    raeburn  4216:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4217:         $enddate = '.';
                   4218:     }
1.922     raeburn  4219:     my $rolelist;
                   4220:     if (ref($roles) eq 'ARRAY') {
                   4221:         $rolelist = join(':',@{$roles});
                   4222:     }
1.662     raeburn  4223:     my %personnel = ();
1.841     albertel 4224: 
                   4225:     my %servers = &get_servers($dom,'library');
                   4226:     foreach my $tryserver (keys(%servers)) {
                   4227: 	%{$personnel{$tryserver}}=();
                   4228: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4229: 					    &escape($startdate).':'.
                   4230: 					    &escape($enddate).':'.
                   4231: 					    &escape($rolelist), $tryserver))) {
                   4232: 	    my ($key,$value) = split(/\=/,$line,2);
                   4233: 	    if (($key) && ($value)) {
                   4234: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4235: 	    }
                   4236: 	}
1.662     raeburn  4237:     }
                   4238:     return %personnel;
                   4239: }
1.658     raeburn  4240: 
1.1057    www      4241: # ----------------------------------------------------------- Interval timing 
1.149     www      4242: 
1.1153    www      4243: {
                   4244: # Caches needed for speedup of navmaps
                   4245: # We don't want to cache this for very long at all (5 seconds at most)
                   4246: # 
                   4247: # The user for whom we cache
                   4248: my $cachedkey='';
                   4249: # The cached times for this user
                   4250: my %cachedtimes=();
                   4251: # When this was last done
                   4252: my $cachedtime=();
                   4253: 
                   4254: sub load_all_first_access {
1.1154    raeburn  4255:     my ($uname,$udom)=@_;
1.1156    www      4256:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4257:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4258:         return;
                   4259:     }
                   4260:     $cachedtime=time;
                   4261:     $cachedkey=$uname.':'.$udom;
                   4262:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4263: }
                   4264: 
1.504     albertel 4265: sub get_first_access {
1.1162    raeburn  4266:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4267:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4268:     if ($argsymb) { $symb=$argsymb; }
                   4269:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4270:     if ($argmap) { $map = $argmap; }
1.926     albertel 4271:     if ($type eq 'course') {
                   4272: 	$res='course';
                   4273:     } elsif ($type eq 'map') {
1.588     albertel 4274: 	$res=&symbread($map);
                   4275:     } else {
                   4276: 	$res=$symb;
                   4277:     }
1.1153    www      4278:     &load_all_first_access($uname,$udom);
                   4279:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4280: }
                   4281: 
                   4282: sub set_first_access {
1.1162    raeburn  4283:     my ($type,$interval)=@_;
1.790     albertel 4284:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4285:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4286:     if ($type eq 'course') {
                   4287: 	$res='course';
                   4288:     } elsif ($type eq 'map') {
1.588     albertel 4289: 	$res=&symbread($map);
                   4290:     } else {
                   4291: 	$res=$symb;
                   4292:     }
1.1153    www      4293:     $cachedkey='';
1.1162    raeburn  4294:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4295:     if (!$firstaccess) {
1.1162    raeburn  4296:         my $start = time;
                   4297: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4298:                           $udom,$uname);
                   4299:         if ($putres eq 'ok') {
                   4300:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4301:                  $udom,$uname); 
                   4302:             &appenv(
                   4303:                      {
                   4304:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4305:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4306:                      }
                   4307:                   );
                   4308:         }
                   4309:         return $putres;
1.505     albertel 4310:     }
                   4311:     return 'already_set';
1.504     albertel 4312: }
1.1153    www      4313: }
1.110     www      4314: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4315: 
                   4316: sub expirespread {
                   4317:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4318:     my $cid=$env{'request.course.id'}; 
1.110     www      4319:     if ($cid) {
                   4320:        my $now=time;
                   4321:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4322:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4323:                             $env{'course.'.$cid.'.num'}.
1.110     www      4324: 	        	    ':nohist_expirationdates:'.
                   4325:                             &escape($key).'='.$now,
1.620     albertel 4326:                             $env{'course.'.$cid.'.home'})
1.110     www      4327:     }
                   4328:     return 'ok';
1.14      www      4329: }
                   4330: 
1.109     www      4331: # ----------------------------------------------------- Devalidate Spreadsheets
                   4332: 
                   4333: sub devalidate {
1.325     www      4334:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4335:     my $cid=$env{'request.course.id'}; 
1.109     www      4336:     if ($cid) {
1.391     matthew  4337:         # delete the stored spreadsheets for
                   4338:         # - the student level sheet of this user in course's homespace
                   4339:         # - the assessment level sheet for this resource 
                   4340:         #   for this user in user's homespace
1.553     albertel 4341: 	# - current conditional state info
1.325     www      4342: 	my $key=$uname.':'.$udom.':';
1.109     www      4343:         my $status=
1.299     matthew  4344: 	    &del('nohist_calculatedsheets',
1.391     matthew  4345: 		 [$key.'studentcalc:'],
1.620     albertel 4346: 		 $env{'course.'.$cid.'.domain'},
                   4347: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4348: 		.' '.
                   4349: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4350: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4351:         unless ($status eq 'ok ok') {
                   4352:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4353:                     $uname.' at '.$udom.' for '.
1.109     www      4354: 		    $symb.': '.$status);
1.133     albertel 4355:         }
1.553     albertel 4356: 	&delenv('user.state.'.$cid);
1.109     www      4357:     }
                   4358: }
                   4359: 
1.265     albertel 4360: sub get_scalar {
                   4361:     my ($string,$end) = @_;
                   4362:     my $value;
                   4363:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4364: 	$value = $1;
                   4365:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4366: 	$value = $1;
                   4367:     }
                   4368:     return &unescape($value);
                   4369: }
                   4370: 
                   4371: sub array2str {
                   4372:   my (@array) = @_;
                   4373:   my $result=&arrayref2str(\@array);
                   4374:   $result=~s/^__ARRAY_REF__//;
                   4375:   $result=~s/__END_ARRAY_REF__$//;
                   4376:   return $result;
                   4377: }
                   4378: 
1.204     albertel 4379: sub arrayref2str {
                   4380:   my ($arrayref) = @_;
1.265     albertel 4381:   my $result='__ARRAY_REF__';
1.204     albertel 4382:   foreach my $elem (@$arrayref) {
1.265     albertel 4383:     if(ref($elem) eq 'ARRAY') {
                   4384:       $result.=&arrayref2str($elem).'&';
                   4385:     } elsif(ref($elem) eq 'HASH') {
                   4386:       $result.=&hashref2str($elem).'&';
                   4387:     } elsif(ref($elem)) {
                   4388:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4389:     } else {
                   4390:       $result.=&escape($elem).'&';
                   4391:     }
                   4392:   }
                   4393:   $result=~s/\&$//;
1.265     albertel 4394:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4395:   return $result;
                   4396: }
                   4397: 
1.168     albertel 4398: sub hash2str {
1.204     albertel 4399:   my (%hash) = @_;
                   4400:   my $result=&hashref2str(\%hash);
1.265     albertel 4401:   $result=~s/^__HASH_REF__//;
                   4402:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4403:   return $result;
                   4404: }
                   4405: 
                   4406: sub hashref2str {
                   4407:   my ($hashref)=@_;
1.265     albertel 4408:   my $result='__HASH_REF__';
1.800     albertel 4409:   foreach my $key (sort(keys(%$hashref))) {
                   4410:     if (ref($key) eq 'ARRAY') {
                   4411:       $result.=&arrayref2str($key).'=';
                   4412:     } elsif (ref($key) eq 'HASH') {
                   4413:       $result.=&hashref2str($key).'=';
                   4414:     } elsif (ref($key)) {
1.265     albertel 4415:       $result.='=';
1.800     albertel 4416:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4417:     } else {
1.1132    raeburn  4418: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4419:     }
                   4420: 
1.800     albertel 4421:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4422:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4423:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4424:       $result.=&hashref2str($hashref->{$key}).'&';
                   4425:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4426:        $result.='&';
1.800     albertel 4427:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4428:     } else {
1.800     albertel 4429:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4430:     }
                   4431:   }
1.168     albertel 4432:   $result=~s/\&$//;
1.265     albertel 4433:   $result .= '__END_HASH_REF__';
1.168     albertel 4434:   return $result;
                   4435: }
                   4436: 
                   4437: sub str2hash {
1.265     albertel 4438:     my ($string)=@_;
                   4439:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4440:     return %$hash;
                   4441: }
                   4442: 
                   4443: sub str2hashref {
1.168     albertel 4444:   my ($string) = @_;
1.265     albertel 4445: 
                   4446:   my %hash;
                   4447: 
                   4448:   if($string !~ /^__HASH_REF__/) {
                   4449:       if (! ($string eq '' || !defined($string))) {
                   4450: 	  $hash{'error'}='Not hash reference';
                   4451:       }
                   4452:       return (\%hash, $string);
                   4453:   }
                   4454: 
                   4455:   $string =~ s/^__HASH_REF__//;
                   4456: 
                   4457:   while($string !~ /^__END_HASH_REF__/) {
                   4458:       #key
                   4459:       my $key='';
                   4460:       if($string =~ /^__HASH_REF__/) {
                   4461:           ($key, $string)=&str2hashref($string);
                   4462:           if(defined($key->{'error'})) {
                   4463:               $hash{'error'}='Bad data';
                   4464:               return (\%hash, $string);
                   4465:           }
                   4466:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4467:           ($key, $string)=&str2arrayref($string);
                   4468:           if($key->[0] eq 'Array reference error') {
                   4469:               $hash{'error'}='Bad data';
                   4470:               return (\%hash, $string);
                   4471:           }
                   4472:       } else {
                   4473:           $string =~ s/^(.*?)=//;
1.267     albertel 4474: 	  $key=&unescape($1);
1.265     albertel 4475:       }
                   4476:       $string =~ s/^=//;
                   4477: 
                   4478:       #value
                   4479:       my $value='';
                   4480:       if($string =~ /^__HASH_REF__/) {
                   4481:           ($value, $string)=&str2hashref($string);
                   4482:           if(defined($value->{'error'})) {
                   4483:               $hash{'error'}='Bad data';
                   4484:               return (\%hash, $string);
                   4485:           }
                   4486:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4487:           ($value, $string)=&str2arrayref($string);
                   4488:           if($value->[0] eq 'Array reference error') {
                   4489:               $hash{'error'}='Bad data';
                   4490:               return (\%hash, $string);
                   4491:           }
                   4492:       } else {
                   4493: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4494:       }
                   4495:       $string =~ s/^&//;
                   4496: 
                   4497:       $hash{$key}=$value;
1.204     albertel 4498:   }
1.265     albertel 4499: 
                   4500:   $string =~ s/^__END_HASH_REF__//;
                   4501: 
                   4502:   return (\%hash, $string);
1.204     albertel 4503: }
                   4504: 
                   4505: sub str2array {
1.265     albertel 4506:     my ($string)=@_;
                   4507:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4508:     return @$array;
                   4509: }
                   4510: 
                   4511: sub str2arrayref {
1.204     albertel 4512:   my ($string) = @_;
1.265     albertel 4513:   my @array;
                   4514: 
                   4515:   if($string !~ /^__ARRAY_REF__/) {
                   4516:       if (! ($string eq '' || !defined($string))) {
                   4517: 	  $array[0]='Array reference error';
                   4518:       }
                   4519:       return (\@array, $string);
                   4520:   }
                   4521: 
                   4522:   $string =~ s/^__ARRAY_REF__//;
                   4523: 
                   4524:   while($string !~ /^__END_ARRAY_REF__/) {
                   4525:       my $value='';
                   4526:       if($string =~ /^__HASH_REF__/) {
                   4527:           ($value, $string)=&str2hashref($string);
                   4528:           if(defined($value->{'error'})) {
                   4529:               $array[0] ='Array reference error';
                   4530:               return (\@array, $string);
                   4531:           }
                   4532:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4533:           ($value, $string)=&str2arrayref($string);
                   4534:           if($value->[0] eq 'Array reference error') {
                   4535:               $array[0] ='Array reference error';
                   4536:               return (\@array, $string);
                   4537:           }
                   4538:       } else {
                   4539: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4540:       }
                   4541:       $string =~ s/^&//;
                   4542: 
                   4543:       push(@array, $value);
1.191     harris41 4544:   }
1.265     albertel 4545: 
                   4546:   $string =~ s/^__END_ARRAY_REF__//;
                   4547: 
                   4548:   return (\@array, $string);
1.168     albertel 4549: }
                   4550: 
1.167     albertel 4551: # -------------------------------------------------------------------Temp Store
                   4552: 
1.168     albertel 4553: sub tmpreset {
                   4554:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4555:   if (!$symb) {
                   4556:     $symb=&symbread();
1.620     albertel 4557:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4558:   }
                   4559:   $symb=escape($symb);
                   4560: 
1.620     albertel 4561:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4562:   $namespace=~s/\//\_/g;
                   4563:   $namespace=~s/\W//g;
                   4564: 
1.620     albertel 4565:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4566:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4567:   if ($domain eq 'public' && $stuname eq 'public') {
                   4568:       $stuname=$ENV{'REMOTE_ADDR'};
                   4569:   }
1.1117    foxr     4570:   my $path=LONCAPA::tempdir();
1.168     albertel 4571:   my %hash;
                   4572:   if (tie(%hash,'GDBM_File',
                   4573: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4574: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4575:     foreach my $key (keys(%hash)) {
1.180     albertel 4576:       if ($key=~ /:$symb/) {
1.168     albertel 4577: 	delete($hash{$key});
                   4578:       }
                   4579:     }
                   4580:   }
                   4581: }
                   4582: 
1.167     albertel 4583: sub tmpstore {
1.168     albertel 4584:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4585: 
                   4586:   if (!$symb) {
                   4587:     $symb=&symbread();
1.620     albertel 4588:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4589:   }
                   4590:   $symb=escape($symb);
                   4591: 
                   4592:   if (!$namespace) {
                   4593:     # I don't think we would ever want to store this for a course.
                   4594:     # it seems this will only be used if we don't have a course.
1.620     albertel 4595:     #$namespace=$env{'request.course.id'};
1.168     albertel 4596:     #if (!$namespace) {
1.620     albertel 4597:       $namespace=$env{'request.state'};
1.168     albertel 4598:     #}
                   4599:   }
                   4600:   $namespace=~s/\//\_/g;
                   4601:   $namespace=~s/\W//g;
1.620     albertel 4602:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4603:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4604:   if ($domain eq 'public' && $stuname eq 'public') {
                   4605:       $stuname=$ENV{'REMOTE_ADDR'};
                   4606:   }
1.168     albertel 4607:   my $now=time;
                   4608:   my %hash;
1.1117    foxr     4609:   my $path=LONCAPA::tempdir();
1.168     albertel 4610:   if (tie(%hash,'GDBM_File',
                   4611: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4612: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4613:     $hash{"version:$symb"}++;
                   4614:     my $version=$hash{"version:$symb"};
                   4615:     my $allkeys=''; 
                   4616:     foreach my $key (keys(%$storehash)) {
                   4617:       $allkeys.=$key.':';
1.591     albertel 4618:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4619:     }
                   4620:     $hash{"$version:$symb:timestamp"}=$now;
                   4621:     $allkeys.='timestamp';
                   4622:     $hash{"$version:keys:$symb"}=$allkeys;
                   4623:     if (untie(%hash)) {
                   4624:       return 'ok';
                   4625:     } else {
                   4626:       return "error:$!";
                   4627:     }
                   4628:   } else {
                   4629:     return "error:$!";
                   4630:   }
                   4631: }
1.167     albertel 4632: 
1.168     albertel 4633: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4634: 
1.168     albertel 4635: sub tmprestore {
                   4636:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4637: 
1.168     albertel 4638:   if (!$symb) {
                   4639:     $symb=&symbread();
1.620     albertel 4640:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4641:   }
                   4642:   $symb=escape($symb);
                   4643: 
1.620     albertel 4644:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4645: 
1.620     albertel 4646:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4647:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4648:   if ($domain eq 'public' && $stuname eq 'public') {
                   4649:       $stuname=$ENV{'REMOTE_ADDR'};
                   4650:   }
1.168     albertel 4651:   my %returnhash;
                   4652:   $namespace=~s/\//\_/g;
                   4653:   $namespace=~s/\W//g;
                   4654:   my %hash;
1.1117    foxr     4655:   my $path=LONCAPA::tempdir();
1.168     albertel 4656:   if (tie(%hash,'GDBM_File',
                   4657: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4658: 	  &GDBM_READER(),0640)) {
1.168     albertel 4659:     my $version=$hash{"version:$symb"};
                   4660:     $returnhash{'version'}=$version;
                   4661:     my $scope;
                   4662:     for ($scope=1;$scope<=$version;$scope++) {
                   4663:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4664:       my @keys=split(/:/,$vkeys);
                   4665:       my $key;
                   4666:       $returnhash{"$scope:keys"}=$vkeys;
                   4667:       foreach $key (@keys) {
1.591     albertel 4668: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4669: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4670:       }
                   4671:     }
1.168     albertel 4672:     if (!(untie(%hash))) {
                   4673:       return "error:$!";
                   4674:     }
                   4675:   } else {
                   4676:     return "error:$!";
                   4677:   }
                   4678:   return %returnhash;
1.167     albertel 4679: }
                   4680: 
1.9       www      4681: # ----------------------------------------------------------------------- Store
                   4682: 
                   4683: sub store {
1.124     www      4684:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4685:     my $home='';
                   4686: 
1.168     albertel 4687:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4688: 
1.213     www      4689:     $symb=&symbclean($symb);
1.122     albertel 4690:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4691: 
1.620     albertel 4692:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4693:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4694: 
                   4695:     &devalidate($symb,$stuname,$domain);
1.109     www      4696: 
                   4697:     $symb=escape($symb);
1.187     www      4698:     if (!$namespace) { 
1.620     albertel 4699:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4700:           return ''; 
                   4701:        } 
                   4702:     }
1.620     albertel 4703:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4704: 
                   4705:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4706:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4707: 
1.12      www      4708:     my $namevalue='';
1.800     albertel 4709:     foreach my $key (keys(%$storehash)) {
                   4710:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4711:     }
1.12      www      4712:     $namevalue=~s/\&$//;
1.187     www      4713:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4714:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4715: }
                   4716: 
1.47      www      4717: # -------------------------------------------------------------- Critical Store
                   4718: 
                   4719: sub cstore {
1.124     www      4720:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4721:     my $home='';
                   4722: 
1.168     albertel 4723:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4724: 
1.213     www      4725:     $symb=&symbclean($symb);
1.122     albertel 4726:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4727: 
1.620     albertel 4728:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4729:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4730: 
                   4731:     &devalidate($symb,$stuname,$domain);
1.109     www      4732: 
                   4733:     $symb=escape($symb);
1.187     www      4734:     if (!$namespace) { 
1.620     albertel 4735:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4736:           return ''; 
                   4737:        } 
                   4738:     }
1.620     albertel 4739:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4740: 
                   4741:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4742:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4743: 
1.47      www      4744:     my $namevalue='';
1.800     albertel 4745:     foreach my $key (keys(%$storehash)) {
                   4746:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4747:     }
1.47      www      4748:     $namevalue=~s/\&$//;
1.187     www      4749:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4750:     return critical
                   4751:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4752: }
                   4753: 
1.9       www      4754: # --------------------------------------------------------------------- Restore
                   4755: 
                   4756: sub restore {
1.124     www      4757:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4758:     my $home='';
                   4759: 
1.168     albertel 4760:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4761: 
1.122     albertel 4762:     if (!$symb) {
                   4763:       unless ($symb=escape(&symbread())) { return ''; }
                   4764:     } else {
1.213     www      4765:       $symb=&escape(&symbclean($symb));
1.122     albertel 4766:     }
1.188     www      4767:     if (!$namespace) { 
1.620     albertel 4768:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4769:           return ''; 
                   4770:        } 
                   4771:     }
1.620     albertel 4772:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4773:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4774:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4775:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4776: 
1.12      www      4777:     my %returnhash=();
1.800     albertel 4778:     foreach my $line (split(/\&/,$answer)) {
                   4779: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4780:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4781:     }
1.75      www      4782:     my $version;
                   4783:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4784:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4785:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4786:        }
1.75      www      4787:     }
1.13      www      4788:     return %returnhash;
1.34      www      4789: }
                   4790: 
                   4791: # ---------------------------------------------------------- Course Description
1.1118    foxr     4792: #
                   4793: #  
1.34      www      4794: 
                   4795: sub coursedescription {
1.731     albertel 4796:     my ($courseid,$args)=@_;
1.34      www      4797:     $courseid=~s/^\///;
1.49      www      4798:     $courseid=~s/\_/\//g;
1.34      www      4799:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4800:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4801:     my $normalid=$cdomain.'_'.$cnum;
                   4802:     # need to always cache even if we get errors otherwise we keep 
                   4803:     # trying and trying and trying to get the course description.
                   4804:     my %envhash=();
                   4805:     my %returnhash=();
1.731     albertel 4806:     
                   4807:     my $expiretime=600;
                   4808:     if ($env{'request.course.id'} eq $normalid) {
                   4809: 	$expiretime=120;
                   4810:     }
                   4811: 
                   4812:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4813:     if (!$args->{'freshen_cache'}
                   4814: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4815: 	foreach my $key (keys(%env)) {
                   4816: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4817: 	    my ($setting) = $1;
                   4818: 	    $returnhash{$setting} = $env{$key};
                   4819: 	}
                   4820: 	return %returnhash;
                   4821:     }
                   4822: 
1.1118    foxr     4823:     # get the data again
                   4824: 
1.731     albertel 4825:     if (!$args->{'one_time'}) {
                   4826: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4827:     }
1.811     albertel 4828: 
1.34      www      4829:     if ($chome ne 'no_host') {
1.302     albertel 4830:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4831:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4832: 	   my $username = $env{'user.name'}; # Defult username
                   4833: 	   if(defined $args->{'user'}) {
                   4834: 	       $username = $args->{'user'};
                   4835: 	   }
1.129     albertel 4836:            $returnhash{'home'}= $chome;
                   4837: 	   $returnhash{'domain'} = $cdomain;
                   4838: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4839:            if (!defined($returnhash{'type'})) {
                   4840:                $returnhash{'type'} = 'Course';
                   4841:            }
1.130     albertel 4842:            while (my ($name,$value) = each %returnhash) {
1.53      www      4843:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4844:            }
1.270     www      4845:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4846:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4847: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4848:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4849:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4850:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4851:        }
                   4852:     }
1.731     albertel 4853:     if (!$args->{'one_time'}) {
1.949     raeburn  4854: 	&appenv(\%envhash);
1.731     albertel 4855:     }
1.302     albertel 4856:     return %returnhash;
1.461     www      4857: }
                   4858: 
1.1080    raeburn  4859: sub update_released_required {
                   4860:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4861:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4862:         $cid = $env{'request.course.id'};
                   4863:         $cdom = $env{'course.'.$cid.'.domain'};
                   4864:         $cnum = $env{'course.'.$cid.'.num'};
                   4865:         $chome = $env{'course.'.$cid.'.home'};
                   4866:     }
                   4867:     if ($needsrelease) {
                   4868:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4869:         my $needsupdate;
                   4870:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4871:             $needsupdate = 1;
                   4872:         } else {
                   4873:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4874:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4875:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4876:                 $needsupdate = 1;
                   4877:             }
                   4878:         }
                   4879:         if ($needsupdate) {
                   4880:             my %needshash = (
                   4881:                              'internal.releaserequired' => $needsrelease,
                   4882:                             );
                   4883:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4884:             if ($putresult eq 'ok') {
                   4885:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4886:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4887:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4888:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4889:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4890:                 }
                   4891:             }
                   4892:         }
                   4893:     }
                   4894:     return;
                   4895: }
                   4896: 
1.461     www      4897: # -------------------------------------------------See if a user is privileged
                   4898: 
                   4899: sub privileged {
                   4900:     my ($username,$domain)=@_;
1.1170    droeschl 4901: 
                   4902:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4903:     my $now = time;
                   4904: 
                   4905:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4906:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4907:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4908:                 return 1 unless ($tend && $tend < $now) 
                   4909:                     or ($tstart && $tstart > $now);
                   4910:             }
1.461     www      4911: 	}
1.1170    droeschl 4912: 
1.461     www      4913:     return 0;
1.9       www      4914: }
1.1       albertel 4915: 
1.103     harris41 4916: # -------------------------------------------------------- Get user privileges
1.11      www      4917: 
                   4918: sub rolesinit {
1.1169    droeschl 4919:     my ($domain, $username) = @_;
                   4920:     my %userroles = ('user.login.time' => time);
                   4921:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4922: 
                   4923:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4924:     # also, blocking can be triggered by an activating timer
                   4925:     # it's saved in the user's %env.
                   4926:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4927:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4928:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4929:         %timerintchk, %timerintenv);
                   4930: 
1.1162    raeburn  4931:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4932:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4933:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4934:     }
1.1169    droeschl 4935: 
1.1162    raeburn  4936:     foreach my $key (keys(%timerinterval)) {
                   4937:         my ($cid,$rest) = split(/\0/,$key);
                   4938:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4939:     }
1.1169    droeschl 4940: 
1.11      www      4941:     my %allroles=();
1.1162    raeburn  4942:     my %allgroups=();
1.11      www      4943: 
1.1169    droeschl 4944:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4945:         my $role = $rolesdump{$area};
                   4946:         $area =~ s/\_\w\w$//;
                   4947: 
                   4948:         my ($trole, $tend, $tstart, $group_privs);
                   4949: 
                   4950:         if ($role =~ /^cr/) {
                   4951:         # Custom role, defined by a user 
                   4952:         # e.g., user.role.cr/msu/smith/mynewrole
                   4953:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4954:                 $trole = $1;
                   4955:                 ($tend, $tstart) = split('_', $2);
                   4956:             } else {
                   4957:                 $trole = $role;
                   4958:             }
                   4959:         } elsif ($role =~ m|^gr/|) {
                   4960:         # Role of member in a group, defined within a course/community
                   4961:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4962:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4963:             next if $tstart eq '-1';
                   4964:             ($trole, $group_privs) = split(/\//, $trole);
                   4965:             $group_privs = &unescape($group_privs);
                   4966:         } else {
                   4967:         # Just a normal role, defined in roles.tab
                   4968:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4969:         }
                   4970: 
                   4971:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4972:                  $username);
                   4973:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4974: 
                   4975:         # role expired or not available yet?
                   4976:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4977:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4978: 
                   4979:         next if $area eq '' or $trole eq '';
                   4980: 
                   4981:         my $spec = "$trole.$area";
                   4982:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4983: 
                   4984:         if ($trole =~ /^cr\//) {
                   4985:         # Custom role, defined by a user
                   4986:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4987:         } elsif ($trole eq 'gr') {
                   4988:         # Role of a member in a group, defined within a course/community
                   4989:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4990:             next;
                   4991:         } else {
                   4992:         # Normal role, defined in roles.tab
                   4993:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4994:         }
                   4995: 
                   4996:         my $cid = $tdomain.'_'.$trest;
                   4997:         unless ($firstaccchk{$cid}) {
                   4998:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4999:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5000:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5001:                         $coursetimerstarts{$cid}{$item}; 
                   5002:                 }
                   5003:             }
                   5004:             $firstaccchk{$cid} = 1;
                   5005:         }
                   5006:         unless ($timerintchk{$cid}) {
                   5007:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5008:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5009:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5010:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5011:                 }
1.12      www      5012:             }
1.1169    droeschl 5013:             $timerintchk{$cid} = 1;
1.191     harris41 5014:         }
1.11      www      5015:     }
1.1169    droeschl 5016: 
                   5017:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5018:         \%allroles, \%allgroups);
                   5019:     $env{'user.adv'} = $userroles{'user.adv'};
                   5020: 
1.1162    raeburn  5021:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5022: }
                   5023: 
1.567     raeburn  5024: sub set_arearole {
                   5025:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   5026: # log the associated role with the area
                   5027:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 5028:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5029: }
                   5030: 
                   5031: sub custom_roleprivs {
                   5032:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5033:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5034:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5035:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5036:         my ($rdummy,$roledef)=
                   5037:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5038:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5039:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5040:             if (defined($syspriv)) {
1.1043    raeburn  5041:                 if ($trest =~ /^$match_community$/) {
                   5042:                     $syspriv =~ s/bre\&S//; 
                   5043:                 }
1.567     raeburn  5044:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5045:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5046:             }
                   5047:             if ($tdomain ne '') {
                   5048:                 if (defined($dompriv)) {
                   5049:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5050:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5051:                 }
                   5052:                 if (($trest ne '') && (defined($coursepriv))) {
                   5053:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5054:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5055:                 }
                   5056:             }
                   5057:         }
                   5058:     }
                   5059: }
                   5060: 
1.678     raeburn  5061: sub group_roleprivs {
                   5062:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5063:     my $access = 1;
                   5064:     my $now = time;
                   5065:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5066:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5067:     if ($access) {
1.811     albertel 5068:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5069:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5070:     }
                   5071: }
1.567     raeburn  5072: 
                   5073: sub standard_roleprivs {
                   5074:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5075:     if (defined($pr{$trole.':s'})) {
                   5076:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5077:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5078:     }
                   5079:     if ($tdomain ne '') {
                   5080:         if (defined($pr{$trole.':d'})) {
                   5081:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5082:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5083:         }
                   5084:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5085:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5086:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5087:         }
                   5088:     }
                   5089: }
                   5090: 
                   5091: sub set_userprivs {
1.1064    raeburn  5092:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5093:     my $author=0;
                   5094:     my $adv=0;
1.678     raeburn  5095:     my %grouproles = ();
                   5096:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5097:         my @groupkeys; 
1.1000    raeburn  5098:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5099:             push(@groupkeys,$role);
                   5100:         }
                   5101:         if (ref($groups_roles) eq 'HASH') {
                   5102:             foreach my $key (keys(%{$groups_roles})) {
                   5103:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5104:                     push(@groupkeys,$key);
                   5105:                 }
                   5106:             }
                   5107:         }
                   5108:         if (@groupkeys > 0) {
                   5109:             foreach my $role (@groupkeys) {
                   5110:                 my ($trole,$area,$sec,$extendedarea);
                   5111:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5112:                     $trole = $1;
                   5113:                     $area = $2;
                   5114:                     $sec = $3;
                   5115:                     $extendedarea = $area.$sec;
                   5116:                     if (exists($$allgroups{$area})) {
                   5117:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5118:                             my $spec = $trole.'.'.$extendedarea;
                   5119:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5120:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5121:                         }
1.678     raeburn  5122:                     }
                   5123:                 }
                   5124:             }
                   5125:         }
                   5126:     }
1.800     albertel 5127:     foreach my $group (keys(%grouproles)) {
                   5128:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5129:     }
1.800     albertel 5130:     foreach my $role (keys(%{$allroles})) {
                   5131:         my %thesepriv;
1.941     raeburn  5132:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5133:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5134:             if ($item ne '') {
                   5135:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5136:                 if ($restrictions eq '') {
                   5137:                     $thesepriv{$privilege}='F';
                   5138:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5139:                     $thesepriv{$privilege}.=$restrictions;
                   5140:                 }
                   5141:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5142:             }
                   5143:         }
                   5144:         my $thesestr='';
1.1104    raeburn  5145:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5146: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5147: 	}
                   5148:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5149:     }
                   5150:     return ($author,$adv);
                   5151: }
                   5152: 
1.994     raeburn  5153: sub role_status {
1.1104    raeburn  5154:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5155:     my @pwhere = ();
                   5156:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5157:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5158:         unless (!defined($$role) || $$role eq '') {
                   5159:             $$where=join('.',@pwhere);
                   5160:             $$trolecode=$$role.'.'.$$where;
                   5161:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5162:             $$tstatus='is';
1.1104    raeburn  5163:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5164:                 $$tstatus='future';
1.1034    raeburn  5165:                 if ($$tstart<$now) {
                   5166:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5167:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5168:                             my (%allroles,%allgroups,$group_privs,
                   5169:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5170:                             my %userroles = (
                   5171:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5172:                             );
1.1064    raeburn  5173:                             @rolecodes = ('cm'); 
1.1002    raeburn  5174:                             my $spec=$$role.'.'.$$where;
                   5175:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5176:                             if ($$role =~ /^cr\//) {
                   5177:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5178:                                 push(@rolecodes,'cr');
1.1002    raeburn  5179:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5180:                                 push(@rolecodes,$$role);
1.1002    raeburn  5181:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5182:                                                     $env{'user.name'});
1.1064    raeburn  5183:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5184:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5185:                                 $group_privs = &unescape($group_privs);
                   5186:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5187:                                 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  5188:                                 &get_groups_roles($tdomain,$trest,
                   5189:                                                   \%course_roles,\@rolecodes,
                   5190:                                                   \%groups_roles);
1.1002    raeburn  5191:                             } else {
1.1064    raeburn  5192:                                 push(@rolecodes,$$role);
1.1002    raeburn  5193:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5194:                             }
1.1064    raeburn  5195:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5196:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5197:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5198:                         }
                   5199:                     }
1.1034    raeburn  5200:                     $$tstatus = 'is';
1.1002    raeburn  5201:                 }
1.994     raeburn  5202:             }
                   5203:             if ($$tend) {
1.1104    raeburn  5204:                 if ($$tend<$update) {
1.994     raeburn  5205:                     $$tstatus='expired';
                   5206:                 } elsif ($$tend<$now) {
                   5207:                     $$tstatus='will_not';
                   5208:                 }
                   5209:             }
                   5210:         }
                   5211:     }
                   5212: }
                   5213: 
1.1104    raeburn  5214: sub get_groups_roles {
                   5215:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5216:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5217:                   (ref($rolecodes) eq 'ARRAY') && 
                   5218:                   (ref($groups_roles) eq 'HASH')); 
                   5219:     if (keys(%{$cdom_courseroles}) > 0) {
                   5220:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5221:         if ($cdom ne '' && $cnum ne '') {
                   5222:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5223:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5224:                     my $crsrole = $1;
                   5225:                     my $crssec = $2;
                   5226:                     if ($crsrole =~ /^cr/) {
                   5227:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5228:                             push(@{$rolecodes},'cr');
                   5229:                         }
                   5230:                     } else {
                   5231:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5232:                             push(@{$rolecodes},$crsrole);
                   5233:                         }
                   5234:                     }
                   5235:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5236:                     if ($crssec ne '') {
                   5237:                         $rolekey .= "/$crssec";
                   5238:                     }
                   5239:                     $rolekey .= './';
                   5240:                     $groups_roles->{$rolekey} = $rolecodes;
                   5241:                 }
                   5242:             }
                   5243:         }
                   5244:     }
                   5245:     return;
                   5246: }
                   5247: 
                   5248: sub delete_env_groupprivs {
                   5249:     my ($where,$courseroles,$possroles) = @_;
                   5250:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5251:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5252:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5253:         %{$courseroles->{$udom}} =
                   5254:             &get_my_roles('','','userroles',['active'],
                   5255:                           $possroles,[$udom],1);
                   5256:     }
                   5257:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5258:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5259:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5260:             my $area = '/'.$cdom.'/'.$cnum;
                   5261:             my $privkey = "user.priv.$crsrole.$area";
                   5262:             if ($crssec ne '') {
                   5263:                 $privkey .= '/'.$crssec;
                   5264:             }
                   5265:             $privkey .= ".$area/$group";
                   5266:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5267:         }
                   5268:     }
                   5269:     return;
                   5270: }
                   5271: 
1.994     raeburn  5272: sub check_adhoc_privs {
1.1104    raeburn  5273:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5274:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5275:     my $setprivs;
1.994     raeburn  5276:     if ($env{$cckey}) {
                   5277:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5278:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5279:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5280:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5281:             $setprivs = 1;
1.994     raeburn  5282:         }
                   5283:     } else {
1.1088    raeburn  5284:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5285:         $setprivs = 1;
1.994     raeburn  5286:     }
1.1185    raeburn  5287:     return $setprivs;
1.994     raeburn  5288: }
                   5289: 
                   5290: sub set_adhoc_privileges {
                   5291: # role can be cc or ca
1.1088    raeburn  5292:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5293:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5294:     my $spec = $role.'.'.$area;
                   5295:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5296:                                   $env{'user.name'});
                   5297:     my %ccrole = ();
                   5298:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5299:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5300:     &appenv(\%userroles,[$role,'cm']);
                   5301:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5302:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5303:         &appenv( {'request.role'        => $spec,
                   5304:                   'request.role.domain' => $dcdom,
                   5305:                   'request.course.sec'  => ''
                   5306:                  }
                   5307:                );
                   5308:         my $tadv=0;
                   5309:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5310:         &appenv({'request.role.adv'    => $tadv});
                   5311:     }
1.994     raeburn  5312: }
                   5313: 
1.12      www      5314: # --------------------------------------------------------------- get interface
                   5315: 
                   5316: sub get {
1.131     albertel 5317:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5318:    my $items='';
1.800     albertel 5319:    foreach my $item (@$storearr) {
                   5320:        $items.=&escape($item).'&';
1.191     harris41 5321:    }
1.12      www      5322:    $items=~s/\&$//;
1.620     albertel 5323:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5324:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5325:    my $uhome=&homeserver($uname,$udomain);
                   5326: 
1.133     albertel 5327:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5328:    my @pairs=split(/\&/,$rep);
1.273     albertel 5329:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5330:      return @pairs;
                   5331:    }
1.15      www      5332:    my %returnhash=();
1.42      www      5333:    my $i=0;
1.800     albertel 5334:    foreach my $item (@$storearr) {
                   5335:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5336:       $i++;
1.191     harris41 5337:    }
1.15      www      5338:    return %returnhash;
1.27      www      5339: }
                   5340: 
                   5341: # --------------------------------------------------------------- del interface
                   5342: 
                   5343: sub del {
1.133     albertel 5344:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5345:    my $items='';
1.800     albertel 5346:    foreach my $item (@$storearr) {
                   5347:        $items.=&escape($item).'&';
1.191     harris41 5348:    }
1.984     neumanie 5349: 
1.27      www      5350:    $items=~s/\&$//;
1.620     albertel 5351:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5352:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5353:    my $uhome=&homeserver($uname,$udomain);
                   5354:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5355: }
                   5356: 
                   5357: # -------------------------------------------------------------- dump interface
                   5358: 
1.1180    droeschl 5359: sub unserialize {
                   5360:     my ($rep, $escapedkeys) = @_;
                   5361: 
                   5362:     return {} if $rep =~ /^error/;
                   5363: 
                   5364:     my %returnhash=();
                   5365: 	foreach my $item (split /\&/, $rep) {
                   5366: 	    my ($key, $value) = split(/=/, $item, 2);
                   5367: 	    $key = unescape($key) unless $escapedkeys;
                   5368: 	    next if $key =~ /^error: 2 /;
                   5369: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5370: 	}
                   5371:     #return %returnhash;
                   5372:     return \%returnhash;
                   5373: }        
                   5374: 
                   5375: # see Lond::dump_with_regexp
                   5376: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5377: sub dump {
1.1180    droeschl 5378:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5379:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5380:     if (!$uname) { $uname=$env{'user.name'}; }
                   5381:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5382: 
1.1180    droeschl 5383:     my $reply;
                   5384:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5385:         # user is hosted on this machine
                   5386:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
                   5387:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5388:         return %{unserialize($reply, $escapedkeys)};
                   5389:     }
1.755     albertel 5390:     if ($regexp) {
                   5391: 	$regexp=&escape($regexp);
                   5392:     } else {
                   5393: 	$regexp='.';
                   5394:     }
1.1166    raeburn  5395:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5396:     my @pairs=split(/\&/,$rep);
                   5397:     my %returnhash=();
1.1098    foxr     5398:     if (!($rep =~ /^error/ )) {
                   5399: 	foreach my $item (@pairs) {
                   5400: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5401:         $key = unescape($key) unless $escapedkeys;
                   5402:         #$key = &unescape($key);
1.1098    foxr     5403: 	    next if ($key =~ /^error: 2 /);
                   5404: 	    $returnhash{$key}=&thaw_unescape($value);
                   5405: 	}
1.755     albertel 5406:     }
                   5407:     return %returnhash;
1.407     www      5408: }
                   5409: 
1.1098    foxr     5410: 
1.717     albertel 5411: # --------------------------------------------------------- dumpstore interface
                   5412: 
                   5413: sub dumpstore {
                   5414:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5415:    # same as dump but keys must be escaped. They may contain colon separated
                   5416:    # lists of values that may themself contain colons (e.g. symbs).
                   5417:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5418: }
                   5419: 
1.407     www      5420: # -------------------------------------------------------------- keys interface
                   5421: 
                   5422: sub getkeys {
                   5423:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5424:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5425:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5426:    my $uhome=&homeserver($uname,$udomain);
                   5427:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5428:    my @keyarray=();
1.800     albertel 5429:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5430:       next if ($key =~ /^error: 2 /);
1.800     albertel 5431:       push(@keyarray,&unescape($key));
1.407     www      5432:    }
                   5433:    return @keyarray;
1.318     matthew  5434: }
                   5435: 
1.319     matthew  5436: # --------------------------------------------------------------- currentdump
                   5437: sub currentdump {
1.328     matthew  5438:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5439:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5440:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5441:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5442:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5443:    my $rep;
                   5444: 
                   5445:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5446:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5447:                    $courseid)));
                   5448:    } else {
                   5449:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5450:    }
                   5451: 
1.318     matthew  5452:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5453:    #
1.318     matthew  5454:    my %returnhash=();
1.319     matthew  5455:    #
                   5456:    if ($rep eq "unknown_cmd") { 
                   5457:        # an old lond will not know currentdump
                   5458:        # Do a dump and make it look like a currentdump
1.822     albertel 5459:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5460:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5461:        my %hash = @tmp;
                   5462:        @tmp=();
1.424     matthew  5463:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5464:    } else {
                   5465:        my @pairs=split(/\&/,$rep);
1.800     albertel 5466:        foreach my $pair (@pairs) {
                   5467:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5468:            my ($symb,$param) = split(/:/,$key);
                   5469:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5470:                                                         &thaw_unescape($value);
1.319     matthew  5471:        }
1.191     harris41 5472:    }
1.12      www      5473:    return %returnhash;
1.424     matthew  5474: }
                   5475: 
                   5476: sub convert_dump_to_currentdump{
                   5477:     my %hash = %{shift()};
                   5478:     my %returnhash;
                   5479:     # Code ripped from lond, essentially.  The only difference
                   5480:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5481:     # we might run in to problems with parameter names =~ /^v\./
                   5482:     while (my ($key,$value) = each(%hash)) {
                   5483:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5484: 	$symb  = &unescape($symb);
                   5485: 	$param = &unescape($param);
1.424     matthew  5486:         next if ($v eq 'version' || $symb eq 'keys');
                   5487:         next if (exists($returnhash{$symb}) &&
                   5488:                  exists($returnhash{$symb}->{$param}) &&
                   5489:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5490:         $returnhash{$symb}->{$param}=$value;
                   5491:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5492:     }
                   5493:     #
                   5494:     # Remove all of the keys in the hashes which keep track of
                   5495:     # the version of the parameter.
                   5496:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5497:         # use a foreach because we are going to delete from the hash.
                   5498:         foreach my $key (keys(%$param_hash)) {
                   5499:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5500:         }
                   5501:     }
                   5502:     return \%returnhash;
1.12      www      5503: }
                   5504: 
1.627     albertel 5505: # ------------------------------------------------------ critical inc interface
                   5506: 
                   5507: sub cinc {
                   5508:     return &inc(@_,'critical');
                   5509: }
                   5510: 
1.449     matthew  5511: # --------------------------------------------------------------- inc interface
                   5512: 
                   5513: sub inc {
1.627     albertel 5514:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5515:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5516:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5517:     my $uhome=&homeserver($uname,$udomain);
                   5518:     my $items='';
                   5519:     if (! ref($store)) {
                   5520:         # got a single value, so use that instead
                   5521:         $items = &escape($store).'=&';
                   5522:     } elsif (ref($store) eq 'SCALAR') {
                   5523:         $items = &escape($$store).'=&';        
                   5524:     } elsif (ref($store) eq 'ARRAY') {
                   5525:         $items = join('=&',map {&escape($_);} @{$store});
                   5526:     } elsif (ref($store) eq 'HASH') {
                   5527:         while (my($key,$value) = each(%{$store})) {
                   5528:             $items.= &escape($key).'='.&escape($value).'&';
                   5529:         }
                   5530:     }
                   5531:     $items=~s/\&$//;
1.627     albertel 5532:     if ($critical) {
                   5533: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5534:     } else {
                   5535: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5536:     }
1.449     matthew  5537: }
                   5538: 
1.12      www      5539: # --------------------------------------------------------------- put interface
                   5540: 
                   5541: sub put {
1.134     albertel 5542:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5543:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5544:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5545:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5546:    my $items='';
1.800     albertel 5547:    foreach my $item (keys(%$storehash)) {
                   5548:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5549:    }
1.12      www      5550:    $items=~s/\&$//;
1.134     albertel 5551:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5552: }
                   5553: 
1.631     albertel 5554: # ------------------------------------------------------------ newput interface
                   5555: 
                   5556: sub newput {
                   5557:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5558:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5559:    if (!$uname) { $uname=$env{'user.name'}; }
                   5560:    my $uhome=&homeserver($uname,$udomain);
                   5561:    my $items='';
                   5562:    foreach my $key (keys(%$storehash)) {
                   5563:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5564:    }
                   5565:    $items=~s/\&$//;
                   5566:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5567: }
                   5568: 
                   5569: # ---------------------------------------------------------  putstore interface
                   5570: 
1.524     raeburn  5571: sub putstore {
1.715     albertel 5572:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5573:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5574:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5575:    my $uhome=&homeserver($uname,$udomain);
                   5576:    my $items='';
1.715     albertel 5577:    foreach my $key (keys(%$storehash)) {
                   5578:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5579:    }
1.715     albertel 5580:    $items=~s/\&$//;
1.716     albertel 5581:    my $esc_symb=&escape($symb);
                   5582:    my $esc_v=&escape($version);
1.715     albertel 5583:    my $reply =
1.716     albertel 5584:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5585: 	      $uhome);
                   5586:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5587:        # gfall back to way things use to be done
1.715     albertel 5588:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5589: 			    $uname);
1.524     raeburn  5590:    }
1.715     albertel 5591:    return $reply;
                   5592: }
                   5593: 
                   5594: sub old_putstore {
1.716     albertel 5595:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5596:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5597:     if (!$uname) { $uname=$env{'user.name'}; }
                   5598:     my $uhome=&homeserver($uname,$udomain);
                   5599:     my %newstorehash;
1.800     albertel 5600:     foreach my $item (keys(%$storehash)) {
                   5601: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5602: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5603:     }
                   5604:     my $items='';
                   5605:     my %allitems = ();
1.800     albertel 5606:     foreach my $item (keys(%newstorehash)) {
                   5607: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5608: 	    my $key = $1.':keys:'.$2;
                   5609: 	    $allitems{$key} .= $3.':';
                   5610: 	}
1.800     albertel 5611: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5612:     }
1.800     albertel 5613:     foreach my $item (keys(%allitems)) {
                   5614: 	$allitems{$item} =~ s/\:$//;
                   5615: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5616:     }
                   5617:     $items=~s/\&$//;
                   5618:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5619: }
                   5620: 
1.47      www      5621: # ------------------------------------------------------ critical put interface
                   5622: 
                   5623: sub cput {
1.134     albertel 5624:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5625:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5626:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5627:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5628:    my $items='';
1.800     albertel 5629:    foreach my $item (keys(%$storehash)) {
                   5630:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5631:    }
1.47      www      5632:    $items=~s/\&$//;
1.134     albertel 5633:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5634: }
                   5635: 
                   5636: # -------------------------------------------------------------- eget interface
                   5637: 
                   5638: sub eget {
1.133     albertel 5639:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5640:    my $items='';
1.800     albertel 5641:    foreach my $item (@$storearr) {
                   5642:        $items.=&escape($item).'&';
1.191     harris41 5643:    }
1.12      www      5644:    $items=~s/\&$//;
1.620     albertel 5645:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5646:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5647:    my $uhome=&homeserver($uname,$udomain);
                   5648:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5649:    my @pairs=split(/\&/,$rep);
                   5650:    my %returnhash=();
1.42      www      5651:    my $i=0;
1.800     albertel 5652:    foreach my $item (@$storearr) {
                   5653:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5654:       $i++;
1.191     harris41 5655:    }
1.12      www      5656:    return %returnhash;
                   5657: }
                   5658: 
1.667     albertel 5659: # ------------------------------------------------------------ tmpput interface
                   5660: sub tmpput {
1.802     raeburn  5661:     my ($storehash,$server,$context)=@_;
1.667     albertel 5662:     my $items='';
1.800     albertel 5663:     foreach my $item (keys(%$storehash)) {
                   5664: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5665:     }
                   5666:     $items=~s/\&$//;
1.802     raeburn  5667:     if (defined($context)) {
                   5668:         $items .= ':'.&escape($context);
                   5669:     }
1.667     albertel 5670:     return &reply("tmpput:$items",$server);
                   5671: }
                   5672: 
                   5673: # ------------------------------------------------------------ tmpget interface
                   5674: sub tmpget {
1.688     albertel 5675:     my ($token,$server)=@_;
                   5676:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5677:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5678:     my %returnhash;
                   5679:     foreach my $item (split(/\&/,$rep)) {
                   5680: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5681:         next if ($key =~ /^error: 2 /);
1.667     albertel 5682: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5683:     }
                   5684:     return %returnhash;
                   5685: }
                   5686: 
1.1113    raeburn  5687: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5688: sub tmpdel {
                   5689:     my ($token,$server)=@_;
                   5690:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5691:     return &reply("tmpdel:$token",$server);
                   5692: }
                   5693: 
1.765     albertel 5694: # -------------------------------------------------- portfolio access checking
                   5695: 
                   5696: sub portfolio_access {
1.766     albertel 5697:     my ($requrl) = @_;
1.765     albertel 5698:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5699:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5700:     if ($result) {
                   5701:         my %setters;
                   5702:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5703:             my ($startblock,$endblock) =
                   5704:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5705:             if ($startblock && $endblock) {
                   5706:                 return 'B';
                   5707:             }
                   5708:         } else {
                   5709:             my ($startblock,$endblock) =
                   5710:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5711:             if ($startblock && $endblock) {
                   5712:                 return 'B';
                   5713:             }
                   5714:         }
                   5715:     }
1.765     albertel 5716:     if ($result eq 'ok') {
1.766     albertel 5717:        return 'F';
1.765     albertel 5718:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5719:        return 'A';
1.765     albertel 5720:     }
1.766     albertel 5721:     return '';
1.765     albertel 5722: }
                   5723: 
                   5724: sub get_portfolio_access {
1.767     albertel 5725:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5726: 
                   5727:     if (!ref($access_hash)) {
                   5728: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5729: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5730: 						   $file_name);
                   5731: 	$access_hash = $access_controls{$file_name};
                   5732:     }
                   5733: 
1.765     albertel 5734:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5735:     my $now = time;
                   5736:     if (ref($access_hash) eq 'HASH') {
                   5737:         foreach my $key (keys(%{$access_hash})) {
                   5738:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5739:             if ($start > $now) {
                   5740:                 next;
                   5741:             }
                   5742:             if ($end && $end<$now) {
                   5743:                 next;
                   5744:             }
                   5745:             if ($scope eq 'public') {
                   5746:                 $public = $key;
                   5747:                 last;
                   5748:             } elsif ($scope eq 'guest') {
                   5749:                 $guest = $key;
                   5750:             } elsif ($scope eq 'domains') {
                   5751:                 push(@domains,$key);
                   5752:             } elsif ($scope eq 'users') {
                   5753:                 push(@users,$key);
                   5754:             } elsif ($scope eq 'course') {
                   5755:                 push(@courses,$key);
                   5756:             } elsif ($scope eq 'group') {
                   5757:                 push(@groups,$key);
                   5758:             }
                   5759:         }
                   5760:         if ($public) {
                   5761:             return 'ok';
                   5762:         }
                   5763:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5764:             if ($guest) {
                   5765:                 return $guest;
                   5766:             }
                   5767:         } else {
                   5768:             if (@domains > 0) {
                   5769:                 foreach my $domkey (@domains) {
                   5770:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5771:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5772:                             return 'ok';
                   5773:                         }
                   5774:                     }
                   5775:                 }
                   5776:             }
                   5777:             if (@users > 0) {
                   5778:                 foreach my $userkey (@users) {
1.865     raeburn  5779:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5780:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5781:                             if (ref($item) eq 'HASH') {
                   5782:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5783:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5784:                                     return 'ok';
                   5785:                                 }
                   5786:                             }
                   5787:                         }
                   5788:                     } 
1.765     albertel 5789:                 }
                   5790:             }
                   5791:             my %roleshash;
                   5792:             my @courses_and_groups = @courses;
                   5793:             push(@courses_and_groups,@groups); 
                   5794:             if (@courses_and_groups > 0) {
                   5795:                 my (%allgroups,%allroles); 
                   5796:                 my ($start,$end,$role,$sec,$group);
                   5797:                 foreach my $envkey (%env) {
1.1060    raeburn  5798:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5799:                         my $cid = $2.'_'.$3; 
                   5800:                         if ($1 eq 'gr') {
                   5801:                             $group = $4;
                   5802:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5803:                         } else {
                   5804:                             if ($4 eq '') {
                   5805:                                 $sec = 'none';
                   5806:                             } else {
                   5807:                                 $sec = $4;
                   5808:                             }
                   5809:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5810:                         }
1.811     albertel 5811:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5812:                         my $cid = $2.'_'.$3;
                   5813:                         if ($4 eq '') {
                   5814:                             $sec = 'none';
                   5815:                         } else {
                   5816:                             $sec = $4;
                   5817:                         }
                   5818:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5819:                     }
                   5820:                 }
                   5821:                 if (keys(%allroles) == 0) {
                   5822:                     return;
                   5823:                 }
                   5824:                 foreach my $key (@courses_and_groups) {
                   5825:                     my %content = %{$$access_hash{$key}};
                   5826:                     my $cnum = $content{'number'};
                   5827:                     my $cdom = $content{'domain'};
                   5828:                     my $cid = $cdom.'_'.$cnum;
                   5829:                     if (!exists($allroles{$cid})) {
                   5830:                         next;
                   5831:                     }    
                   5832:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5833:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5834:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5835:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5836:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5837:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5838:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5839:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5840:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5841:                                         if (grep/^all$/,@sections) {
                   5842:                                             return 'ok';
                   5843:                                         } else {
                   5844:                                             if (grep/^$sec$/,@sections) {
                   5845:                                                 return 'ok';
                   5846:                                             }
                   5847:                                         }
                   5848:                                     }
                   5849:                                 }
                   5850:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5851:                                     if (grep/^none$/,@groups) {
                   5852:                                         return 'ok';
                   5853:                                     }
                   5854:                                 } else {
                   5855:                                     if (grep/^all$/,@groups) {
                   5856:                                         return 'ok';
                   5857:                                     } 
                   5858:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5859:                                         if (grep/^$group$/,@groups) {
                   5860:                                             return 'ok';
                   5861:                                         }
                   5862:                                     }
                   5863:                                 } 
                   5864:                             }
                   5865:                         }
                   5866:                     }
                   5867:                 }
                   5868:             }
                   5869:             if ($guest) {
                   5870:                 return $guest;
                   5871:             }
                   5872:         }
                   5873:     }
                   5874:     return;
                   5875: }
                   5876: 
                   5877: sub course_group_datechecker {
                   5878:     my ($dates,$now,$status) = @_;
                   5879:     my ($start,$end) = split(/\./,$dates);
                   5880:     if (!$start && !$end) {
                   5881:         return 'ok';
                   5882:     }
                   5883:     if (grep/^active$/,@{$status}) {
                   5884:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5885:             return 'ok';
                   5886:         }
                   5887:     }
                   5888:     if (grep/^previous$/,@{$status}) {
                   5889:         if ($end > $now ) {
                   5890:             return 'ok';
                   5891:         }
                   5892:     }
                   5893:     if (grep/^future$/,@{$status}) {
                   5894:         if ($start > $now) {
                   5895:             return 'ok';
                   5896:         }
                   5897:     }
                   5898:     return; 
                   5899: }
                   5900: 
                   5901: sub parse_portfolio_url {
                   5902:     my ($url) = @_;
                   5903: 
                   5904:     my ($type,$udom,$unum,$group,$file_name);
                   5905:     
1.823     albertel 5906:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5907: 	$type = 1;
                   5908:         $udom = $1;
                   5909:         $unum = $2;
                   5910:         $file_name = $3;
1.823     albertel 5911:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5912: 	$type = 2;
                   5913:         $udom = $1;
                   5914:         $unum = $2;
                   5915:         $group = $3;
                   5916:         $file_name = $3.'/'.$4;
                   5917:     }
                   5918:     if (wantarray) {
                   5919: 	return ($type,$udom,$unum,$file_name,$group);
                   5920:     }
                   5921:     return $type;
                   5922: }
                   5923: 
                   5924: sub is_portfolio_url {
                   5925:     my ($url) = @_;
                   5926:     return scalar(&parse_portfolio_url($url));
                   5927: }
                   5928: 
1.798     raeburn  5929: sub is_portfolio_file {
                   5930:     my ($file) = @_;
1.820     raeburn  5931:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5932:         return 1;
                   5933:     }
                   5934:     return;
                   5935: }
                   5936: 
1.976     raeburn  5937: sub usertools_access {
1.1084    raeburn  5938:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5939:     my ($access,%tools);
                   5940:     if ($context eq '') {
                   5941:         $context = 'tools';
                   5942:     }
                   5943:     if ($context eq 'requestcourses') {
                   5944:         %tools = (
                   5945:                       official   => 1,
                   5946:                       unofficial => 1,
1.1006    raeburn  5947:                       community  => 1,
1.985     raeburn  5948:                  );
1.1183    raeburn  5949:     } elsif ($context eq 'requestauthor') {
                   5950:         %tools = (
                   5951:                       requestauthor => 1,
                   5952:                  );
1.985     raeburn  5953:     } else {
                   5954:         %tools = (
                   5955:                       aboutme   => 1,
                   5956:                       blog      => 1,
1.1177    raeburn  5957:                       webdav    => 1,
1.985     raeburn  5958:                       portfolio => 1,
                   5959:                  );
                   5960:     }
1.976     raeburn  5961:     return if (!defined($tools{$tool}));
                   5962: 
                   5963:     if ((!defined($udom)) || (!defined($uname))) {
                   5964:         $udom = $env{'user.domain'};
                   5965:         $uname = $env{'user.name'};
                   5966:     }
                   5967: 
1.978     raeburn  5968:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5969:         if ($action ne 'reload') {
1.985     raeburn  5970:             if ($context eq 'requestcourses') {
                   5971:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  5972:             } elsif ($context eq 'requestauthor') {
                   5973:                 return $env{'environment.canrequest.author'};
1.985     raeburn  5974:             } else {
                   5975:                 return $env{'environment.availabletools.'.$tool};
                   5976:             }
                   5977:         }
1.976     raeburn  5978:     }
                   5979: 
1.1183    raeburn  5980:     my ($toolstatus,$inststatus,$envkey);
                   5981:     if ($context eq 'requestauthor') {
                   5982:         $envkey = $context; 
                   5983:     } else {
                   5984:         $envkey = $context.'.'.$tool;
                   5985:     }
1.976     raeburn  5986: 
1.985     raeburn  5987:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5988:          ($action ne 'reload')) {
1.1183    raeburn  5989:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  5990:         $inststatus = $env{'environment.inststatus'};
                   5991:     } else {
1.1084    raeburn  5992:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  5993:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  5994:             $inststatus = $userenvref->{'inststatus'};
                   5995:         } else {
1.1183    raeburn  5996:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   5997:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  5998:             $inststatus = $userenv{'inststatus'};
                   5999:         }
1.976     raeburn  6000:     }
                   6001: 
                   6002:     if ($toolstatus ne '') {
                   6003:         if ($toolstatus) {
                   6004:             $access = 1;
                   6005:         } else {
                   6006:             $access = 0;
                   6007:         }
                   6008:         return $access;
                   6009:     }
                   6010: 
1.1084    raeburn  6011:     my ($is_adv,%domdef);
                   6012:     if (ref($is_advref) eq 'HASH') {
                   6013:         $is_adv = $is_advref->{'is_adv'};
                   6014:     } else {
                   6015:         $is_adv = &is_advanced_user($udom,$uname);
                   6016:     }
                   6017:     if (ref($domdefref) eq 'HASH') {
                   6018:         %domdef = %{$domdefref};
                   6019:     } else {
                   6020:         %domdef = &get_domain_defaults($udom);
                   6021:     }
1.976     raeburn  6022:     if (ref($domdef{$tool}) eq 'HASH') {
                   6023:         if ($is_adv) {
                   6024:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6025:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6026:                     $access = 1;
                   6027:                 } else {
                   6028:                     $access = 0;
                   6029:                 }
                   6030:                 return $access;
                   6031:             }
                   6032:         }
                   6033:         if ($inststatus ne '') {
                   6034:             my ($hasaccess,$hasnoaccess);
                   6035:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6036:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6037:                     if ($domdef{$tool}{$affiliation}) {
                   6038:                         $hasaccess = 1;
                   6039:                     } else {
                   6040:                         $hasnoaccess = 1;
                   6041:                     }
                   6042:                 }
                   6043:             }
                   6044:             if ($hasaccess || $hasnoaccess) {
                   6045:                 if ($hasaccess) {
                   6046:                     $access = 1;
                   6047:                 } elsif ($hasnoaccess) {
                   6048:                     $access = 0; 
                   6049:                 }
                   6050:                 return $access;
                   6051:             }
                   6052:         } else {
                   6053:             if ($domdef{$tool}{'default'} ne '') {
                   6054:                 if ($domdef{$tool}{'default'}) {
                   6055:                     $access = 1;
                   6056:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6057:                     $access = 0;
                   6058:                 }
                   6059:                 return $access;
                   6060:             }
                   6061:         }
                   6062:     } else {
1.1177    raeburn  6063:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6064:             $access = 1;
                   6065:         } else {
                   6066:             $access = 0;
                   6067:         }
1.976     raeburn  6068:         return $access;
                   6069:     }
                   6070: }
                   6071: 
1.1050    raeburn  6072: sub is_course_owner {
                   6073:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6074:     if (($udom eq '') || ($uname eq '')) {
                   6075:         $udom = $env{'user.domain'};
                   6076:         $uname = $env{'user.name'};
                   6077:     }
                   6078:     unless (($udom eq '') || ($uname eq '')) {
                   6079:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6080:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6081:                 return 1;
                   6082:             } else {
                   6083:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6084:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6085:                     return 1;
                   6086:                 }
                   6087:             }
                   6088:         }
                   6089:     }
                   6090:     return;
                   6091: }
                   6092: 
1.976     raeburn  6093: sub is_advanced_user {
                   6094:     my ($udom,$uname) = @_;
1.1085    raeburn  6095:     if ($udom ne '' && $uname ne '') {
                   6096:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6097:             if (wantarray) {
                   6098:                 return ($env{'user.adv'},$env{'user.author'});
                   6099:             } else {
                   6100:                 return $env{'user.adv'};
                   6101:             }
1.1085    raeburn  6102:         }
                   6103:     }
1.976     raeburn  6104:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6105:     my %allroles;
1.1128    raeburn  6106:     my ($is_adv,$is_author);
1.976     raeburn  6107:     foreach my $role (keys(%roleshash)) {
                   6108:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6109:         my $area = '/'.$tdomain.'/'.$trest;
                   6110:         if ($sec ne '') {
                   6111:             $area .= '/'.$sec;
                   6112:         }
                   6113:         if (($area ne '') && ($trole ne '')) {
                   6114:             my $spec=$trole.'.'.$area;
                   6115:             if ($trole =~ /^cr\//) {
                   6116:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6117:             } elsif ($trole ne 'gr') {
                   6118:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6119:             }
1.1128    raeburn  6120:             if ($trole eq 'au') {
                   6121:                 $is_author = 1;
                   6122:             }
1.976     raeburn  6123:         }
                   6124:     }
                   6125:     foreach my $role (keys(%allroles)) {
                   6126:         last if ($is_adv);
                   6127:         foreach my $item (split(/:/,$allroles{$role})) {
                   6128:             if ($item ne '') {
                   6129:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6130:                 if ($privilege eq 'adv') {
                   6131:                     $is_adv = 1;
                   6132:                     last;
                   6133:                 }
                   6134:             }
                   6135:         }
                   6136:     }
1.1128    raeburn  6137:     if (wantarray) {
                   6138:         return ($is_adv,$is_author);
                   6139:     }
1.976     raeburn  6140:     return $is_adv;
                   6141: }
1.798     raeburn  6142: 
1.1035    raeburn  6143: sub check_can_request {
1.1036    raeburn  6144:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6145:     my $canreq = 0;
                   6146:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6147:     my @options = ('approval','validate','autolimit');
                   6148:     my $optregex = join('|',@options);
                   6149:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6150:         foreach my $type (@{$types}) {
                   6151:             if (&usertools_access($env{'user.name'},
                   6152:                                   $env{'user.domain'},
                   6153:                                   $type,undef,'requestcourses')) {
                   6154:                 $canreq ++;
1.1036    raeburn  6155:                 if (ref($request_domains) eq 'HASH') {
                   6156:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6157:                 }
1.1035    raeburn  6158:                 if ($dom eq $env{'user.domain'}) {
                   6159:                     $can_request->{$type} = 1;
                   6160:                 }
                   6161:             }
                   6162:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6163:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6164:                 if (@curr > 0) {
1.1036    raeburn  6165:                     foreach my $item (@curr) {
                   6166:                         if (ref($request_domains) eq 'HASH') {
                   6167:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6168:                             if ($otherdom ne '') {
                   6169:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6170:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6171:                                         push(@{$request_domains->{$type}},$otherdom);
                   6172:                                     }
                   6173:                                 } else {
                   6174:                                     push(@{$request_domains->{$type}},$otherdom);
                   6175:                                 }
                   6176:                             }
                   6177:                         }
                   6178:                     }
                   6179:                     unless($dom eq $env{'user.domain'}) {
                   6180:                         $canreq ++;
1.1035    raeburn  6181:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6182:                             $can_request->{$type} = 1;
                   6183:                         }
                   6184:                     }
                   6185:                 }
                   6186:             }
                   6187:         }
                   6188:     }
                   6189:     return $canreq;
                   6190: }
                   6191: 
1.341     www      6192: # ---------------------------------------------- Custom access rule evaluation
                   6193: 
                   6194: sub customaccess {
                   6195:     my ($priv,$uri)=@_;
1.807     albertel 6196:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6197:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6198:     $udom = &LONCAPA::clean_domain($udom);
                   6199:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6200:     my $access=0;
1.800     albertel 6201:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6202: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6203: 	if ($type eq 'user') {
                   6204: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6205: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6206: 		if ($tdom) {
                   6207: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6208: 		}
1.896     albertel 6209: 		if ($tuname) {
                   6210: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6211: 		}
                   6212: 		$access=($effect eq 'allow');
                   6213: 		last;
                   6214: 	    }
                   6215: 	} else {
                   6216: 	    if ($role) {
                   6217: 		if ($role ne $urole) { next; }
                   6218: 	    }
                   6219: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6220: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6221: 		if ($tdom) {
                   6222: 		    if ($tdom ne $udom) { next; }
                   6223: 		}
                   6224: 		if ($tcrs) {
                   6225: 		    if ($tcrs ne $ucrs) { next; }
                   6226: 		}
                   6227: 		if ($tsec) {
                   6228: 		    if ($tsec ne $usec) { next; }
                   6229: 		}
                   6230: 		$access=($effect eq 'allow');
                   6231: 		last;
                   6232: 	    }
                   6233: 	    if ($realm eq '' && $role eq '') {
                   6234: 		$access=($effect eq 'allow');
                   6235: 	    }
1.402     bowersj2 6236: 	}
1.341     www      6237:     }
                   6238:     return $access;
                   6239: }
                   6240: 
1.103     harris41 6241: # ------------------------------------------------- Check for a user privilege
1.12      www      6242: 
                   6243: sub allowed {
1.810     raeburn  6244:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6245:     my $ver_orguri=$uri;
1.439     www      6246:     $uri=&deversion($uri);
1.152     www      6247:     my $orguri=$uri;
1.52      www      6248:     $uri=&declutter($uri);
1.809     raeburn  6249: 
1.810     raeburn  6250:     if ($priv eq 'evb') {
                   6251: # Evade communication block restrictions for specified role in a course
                   6252:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6253:             return $1;
                   6254:         } else {
                   6255:             return;
                   6256:         }
                   6257:     }
                   6258: 
1.620     albertel 6259:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6260: # Free bre access to adm and meta resources
1.775     albertel 6261:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6262: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6263: 	&& ($priv eq 'bre')) {
1.14      www      6264: 	return 'F';
1.159     www      6265:     }
                   6266: 
1.545     banghart 6267: # Free bre access to user's own portfolio contents
1.714     raeburn  6268:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6269:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6270: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6271:         my %setters;
                   6272:         my ($startblock,$endblock) = 
                   6273:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6274:         if ($startblock && $endblock) {
                   6275:             return 'B';
                   6276:         } else {
                   6277:             return 'F';
                   6278:         }
1.545     banghart 6279:     }
                   6280: 
1.762     raeburn  6281: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6282:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6283:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6284:         if (exists($env{'request.course.id'})) {
                   6285:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6286:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6287:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6288:                 my $courseprivid=$env{'request.course.id'};
                   6289:                 $courseprivid=~s/\_/\//;
                   6290:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6291:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6292:                     return $1; 
1.762     raeburn  6293:                 } else {
                   6294:                     if ($env{'request.course.sec'}) {
                   6295:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6296:                     }
                   6297:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6298:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6299:                         return $2;
                   6300:                     }
1.714     raeburn  6301:                 }
                   6302:             }
                   6303:         }
                   6304:     }
                   6305: 
1.159     www      6306: # Free bre to public access
                   6307: 
                   6308:     if ($priv eq 'bre') {
1.238     www      6309:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6310: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6311:            return 'F'; 
                   6312:         }
1.238     www      6313:         if ($copyright eq 'priv') {
                   6314:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6315: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6316: 		return '';
                   6317:             }
                   6318:         }
                   6319:         if ($copyright eq 'domain') {
                   6320:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6321: 	    unless (($env{'user.domain'} eq $1) ||
                   6322:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6323: 		return '';
                   6324:             }
1.262     matthew  6325:         }
1.620     albertel 6326:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6327:             # Library role, so allow browsing of resources in this domain.
                   6328:             return 'F';
1.238     www      6329:         }
1.341     www      6330:         if ($copyright eq 'custom') {
                   6331: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6332:         }
1.14      www      6333:     }
1.264     matthew  6334:     # Domain coordinator is trying to create a course
1.620     albertel 6335:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6336:         # uri is the requested domain in this case.
                   6337:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6338:         # a role of dc for the domain in question.
1.620     albertel 6339:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6340:     }
1.29      www      6341: 
1.52      www      6342:     my $thisallowed='';
                   6343:     my $statecond=0;
                   6344:     my $courseprivid='';
                   6345: 
1.1039    raeburn  6346:     my $ownaccess;
1.1043    raeburn  6347:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6348:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6349:         if ($uri eq '') {
                   6350:             $ownaccess = 1;
                   6351:         } else {
                   6352:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6353:                 my $udom = $env{'user.domain'};
                   6354:                 my $uname = $env{'user.name'};
                   6355:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6356:                     $ownaccess = 1;
1.1040    raeburn  6357:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6358:                     unless ($uri =~ m{\.\./}) {
                   6359:                         $ownaccess = 1;
                   6360:                     }
                   6361:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6362:                     my $now = time;
                   6363:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6364:                         my $adom = $1;
                   6365:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6366:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6367:                                 my ($start,$end) = split('.',$env{$key});
                   6368:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6369:                                     $ownaccess = 1;
                   6370:                                     last;
                   6371:                                 }
                   6372:                             }
                   6373:                         }
                   6374:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6375:                         my $adom = $1;
                   6376:                         my $aname = $2;
1.1042    raeburn  6377:                         foreach my $role ('ca','aa') { 
                   6378:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6379:                                 my ($start,$end) =
                   6380:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6381:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6382:                                     $ownaccess = 1;
                   6383:                                     last;
                   6384:                                 }
1.1039    raeburn  6385:                             }
                   6386:                         }
                   6387:                     }
                   6388:                 }
                   6389:             }
                   6390:         }
                   6391:     }
                   6392: 
1.52      www      6393: # Course
                   6394: 
1.620     albertel 6395:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6396:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6397:             $thisallowed.=$1;
                   6398:         }
1.52      www      6399:     }
1.29      www      6400: 
1.52      www      6401: # Domain
                   6402: 
1.620     albertel 6403:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6404:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6405:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6406:             $thisallowed.=$1;
                   6407:         }
1.12      www      6408:     }
1.52      www      6409: 
1.1141    raeburn  6410: # User who is not author or co-author might still be able to edit
                   6411: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6412:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6413:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6414:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6415:             $thisallowed.=$1;
                   6416:         }
                   6417:     }
                   6418: 
1.52      www      6419: # Course: uri itself is a course
1.66      www      6420:     my $courseuri=$uri;
                   6421:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6422:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6423: 
1.620     albertel 6424:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6425:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6426:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6427:             $thisallowed.=$1;
                   6428:         }
1.12      www      6429:     }
1.29      www      6430: 
1.665     albertel 6431: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6432: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6433:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6434: 	$thisallowed='';
1.671     raeburn  6435:         my ($match)=&is_on_map($uri);
                   6436:         if ($match) {
                   6437:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6438:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6439:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6440:                 if (@blockers > 0) {
                   6441:                     $thisallowed = 'B';
                   6442:                 } else {
                   6443:                     $thisallowed.=$1;
                   6444:                 }
1.671     raeburn  6445:             }
                   6446:         } else {
1.705     albertel 6447:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6448:             if ($refuri) {
                   6449:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6450:                     $thisallowed='F';
1.671     raeburn  6451:                 } else {
                   6452:                     $refuri=&declutter($refuri);
                   6453:                     my ($match) = &is_on_map($refuri);
                   6454:                     if ($match) {
1.1162    raeburn  6455:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6456:                         if (@blockers > 0) {
                   6457:                             $thisallowed = 'B';
                   6458:                         } else {
                   6459:                             $thisallowed='F';
                   6460:                         }
1.671     raeburn  6461:                     }
1.669     raeburn  6462:                 }
1.671     raeburn  6463:             }
                   6464:         }
1.314     www      6465:     }
1.492     albertel 6466: 
1.766     albertel 6467:     if ($priv eq 'bre'
                   6468: 	&& $thisallowed ne 'F' 
                   6469: 	&& $thisallowed ne '2'
                   6470: 	&& &is_portfolio_url($uri)) {
                   6471: 	$thisallowed = &portfolio_access($uri);
                   6472:     }
                   6473:     
1.52      www      6474: # Full access at system, domain or course-wide level? Exit.
1.29      www      6475:     if ($thisallowed=~/F/) {
                   6476: 	return 'F';
                   6477:     }
                   6478: 
1.52      www      6479: # If this is generating or modifying users, exit with special codes
1.29      www      6480: 
1.643     www      6481:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6482: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6483: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6484: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6485: 	    unless ($auname) { return $thisallowed; }
                   6486: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6487: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6488: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6489: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6490: 	}
1.52      www      6491: 	return $thisallowed;
                   6492:     }
                   6493: #
1.103     harris41 6494: # Gathered so far: system, domain and course wide privileges
1.52      www      6495: #
                   6496: # Course: See if uri or referer is an individual resource that is part of 
                   6497: # the course
                   6498: 
1.620     albertel 6499:     if ($env{'request.course.id'}) {
1.232     www      6500: 
1.620     albertel 6501:        $courseprivid=$env{'request.course.id'};
                   6502:        if ($env{'request.course.sec'}) {
                   6503:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6504:        }
                   6505:        $courseprivid=~s/\_/\//;
                   6506:        my $checkreferer=1;
1.232     www      6507:        my ($match,$cond)=&is_on_map($uri);
                   6508:        if ($match) {
                   6509:            $statecond=$cond;
1.620     albertel 6510:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6511:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6512:                my $value = $1;
                   6513:                if ($priv eq 'bre') {
                   6514:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6515:                    if (@blockers > 0) {
                   6516:                        $thisallowed = 'B';
                   6517:                    } else {
                   6518:                        $thisallowed.=$value;
                   6519:                    }
                   6520:                } else {
                   6521:                    $thisallowed.=$value;
                   6522:                }
1.52      www      6523:                $checkreferer=0;
                   6524:            }
1.29      www      6525:        }
1.83      www      6526:        
1.148     www      6527:        if ($checkreferer) {
1.620     albertel 6528: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6529:             unless ($refuri) {
1.800     albertel 6530:                 foreach my $key (keys(%env)) {
                   6531: 		    if ($key=~/^httpref\..*\*/) {
                   6532: 			my $pattern=$key;
1.156     www      6533:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6534:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6535:                         $pattern=~s/\//\\\//g;
1.152     www      6536:                         if ($orguri=~/$pattern/) {
1.800     albertel 6537: 			    $refuri=$env{$key};
1.148     www      6538:                         }
                   6539:                     }
1.191     harris41 6540:                 }
1.148     www      6541:             }
1.232     www      6542: 
1.148     www      6543:          if ($refuri) { 
1.152     www      6544: 	  $refuri=&declutter($refuri);
1.232     www      6545:           my ($match,$cond)=&is_on_map($refuri);
                   6546:             if ($match) {
                   6547:               my $refstatecond=$cond;
1.620     albertel 6548:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6549:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6550:                   my $value = $1;
                   6551:                   if ($priv eq 'bre') {
                   6552:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6553:                       if (@blockers > 0) {
                   6554:                           $thisallowed = 'B';
                   6555:                       } else {
                   6556:                           $thisallowed.=$value;
                   6557:                       }
                   6558:                   } else {
                   6559:                       $thisallowed.=$value;
                   6560:                   }
1.53      www      6561:                   $uri=$refuri;
                   6562:                   $statecond=$refstatecond;
1.52      www      6563:               }
                   6564:           }
1.148     www      6565:         }
1.29      www      6566:        }
1.52      www      6567:    }
1.29      www      6568: 
1.52      www      6569: #
1.103     harris41 6570: # Gathered now: all privileges that could apply, and condition number
1.52      www      6571: # 
                   6572: #
                   6573: # Full or no access?
                   6574: #
1.29      www      6575: 
1.52      www      6576:     if ($thisallowed=~/F/) {
                   6577: 	return 'F';
                   6578:     }
1.29      www      6579: 
1.52      www      6580:     unless ($thisallowed) {
                   6581:         return '';
                   6582:     }
1.29      www      6583: 
1.52      www      6584: # Restrictions exist, deal with them
                   6585: #
                   6586: #   C:according to course preferences
                   6587: #   R:according to resource settings
                   6588: #   L:unless locked
                   6589: #   X:according to user session state
                   6590: #
                   6591: 
                   6592: # Possibly locked functionality, check all courses
1.54      www      6593: # Locks might take effect only after 10 minutes cache expiration for other
                   6594: # courses, and 2 minutes for current course
1.52      www      6595: 
                   6596:     my $envkey;
                   6597:     if ($thisallowed=~/L/) {
1.1000    raeburn  6598:         foreach $envkey (keys(%env)) {
1.54      www      6599:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6600:                my $courseid=$2;
                   6601:                my $roleid=$1.'.'.$2;
1.92      www      6602:                $courseid=~s/^\///;
1.54      www      6603:                my $expiretime=600;
1.620     albertel 6604:                if ($env{'request.role'} eq $roleid) {
1.54      www      6605: 		  $expiretime=120;
                   6606:                }
                   6607: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6608:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6609:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6610: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6611:                }
1.620     albertel 6612:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6613:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6614: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6615:                        &log($env{'user.domain'},$env{'user.name'},
                   6616:                             $env{'user.home'},
1.57      www      6617:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6618:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6619:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6620: 		       return '';
                   6621:                    }
                   6622:                }
1.620     albertel 6623:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6624:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6625: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6626:                        &log($env{'user.domain'},$env{'user.name'},
                   6627:                             $env{'user.home'},
1.57      www      6628:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6629:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6630:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6631: 		       return '';
                   6632:                    }
                   6633:                }
                   6634: 	   }
1.29      www      6635:        }
1.52      www      6636:     }
                   6637:    
                   6638: #
                   6639: # Rest of the restrictions depend on selected course
                   6640: #
                   6641: 
1.620     albertel 6642:     unless ($env{'request.course.id'}) {
1.766     albertel 6643: 	if ($thisallowed eq 'A') {
                   6644: 	    return 'A';
1.814     raeburn  6645:         } elsif ($thisallowed eq 'B') {
                   6646:             return 'B';
1.766     albertel 6647: 	} else {
                   6648: 	    return '1';
                   6649: 	}
1.52      www      6650:     }
1.29      www      6651: 
1.52      www      6652: #
                   6653: # Now user is definitely in a course
                   6654: #
1.53      www      6655: 
                   6656: 
                   6657: # Course preferences
                   6658: 
                   6659:    if ($thisallowed=~/C/) {
1.620     albertel 6660:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6661:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6662:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6663: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6664: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6665: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6666: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6667: 			$env{'request.course.id'});
                   6668: 	   }
1.237     www      6669:            return '';
                   6670:        }
                   6671: 
1.620     albertel 6672:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6673: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6674: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6675: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6676: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6677: 			$env{'request.course.id'});
                   6678: 	   }
1.54      www      6679:            return '';
                   6680:        }
1.53      www      6681:    }
                   6682: 
                   6683: # Resource preferences
                   6684: 
                   6685:    if ($thisallowed=~/R/) {
1.620     albertel 6686:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6687:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6688: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6689: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6690: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6691: 	   }
                   6692: 	   return '';
1.54      www      6693:        }
1.53      www      6694:    }
1.30      www      6695: 
1.246     www      6696: # Restricted by state or randomout?
1.30      www      6697: 
1.52      www      6698:    if ($thisallowed=~/X/) {
1.620     albertel 6699:       if ($env{'acc.randomout'}) {
1.579     albertel 6700: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6701:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6702:             return ''; 
                   6703:          }
1.247     www      6704:       }
                   6705:       if (&condval($statecond)) {
1.52      www      6706: 	 return '2';
                   6707:       } else {
                   6708:          return '';
                   6709:       }
                   6710:    }
1.30      www      6711: 
1.766     albertel 6712:     if ($thisallowed eq 'A') {
                   6713: 	return 'A';
1.814     raeburn  6714:     } elsif ($thisallowed eq 'B') {
                   6715:         return 'B';
1.766     albertel 6716:     }
1.52      www      6717:    return 'F';
1.232     www      6718: }
1.1162    raeburn  6719: 
1.1192    raeburn  6720: # ------------------------------------------- Check construction space access
                   6721: 
                   6722: sub constructaccess {
                   6723:     my ($url,$setpriv)=@_;
                   6724: 
                   6725: # We do not allow editing of previous versions of files
                   6726:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6727: 
                   6728: # Get username and domain from URL
                   6729:     my ($ownername,$ownerdomain,$ownerhome);
                   6730: 
                   6731:     ($ownerdomain,$ownername) =
                   6732:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6733: 
                   6734: # The URL does not really point to any authorspace, forget it
                   6735:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6736: 
                   6737: # Now we need to see if the user has access to the authorspace of
                   6738: # $ownername at $ownerdomain
                   6739: 
                   6740:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6741: # Real author for this?
                   6742:        $ownerhome = $env{'user.home'};
                   6743:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6744:           return ($ownername,$ownerdomain,$ownerhome);
                   6745:        }
                   6746:     } else {
                   6747: # Co-author for this?
                   6748:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6749:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6750:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6751:             return ($ownername,$ownerdomain,$ownerhome);
                   6752:         }
                   6753:     }
                   6754: 
                   6755: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6756: # we might as well leave
                   6757:    unless ($setpriv) { return ''; }
                   6758: 
                   6759: # Backdoor access?
                   6760:     my $allowed=&allowed('eco',$ownerdomain);
                   6761: # Nope
                   6762:     unless ($allowed) { return ''; }
                   6763: # Looks like we may have access, but could be locked by the owner of the construction space
                   6764:     if ($allowed eq 'U') {
                   6765:         my %blocked=&get('environment',['domcoord.author'],
                   6766:                          $ownerdomain,$ownername);
                   6767: # Is blocked by owner
                   6768:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6769:     }
                   6770:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6771: # Grant temporary access
                   6772:         my $then=$env{'user.login.time'};
                   6773:         my $update==$env{'user.update.time'};
                   6774:         if (!$update) { $update = $then; }
                   6775:         my $refresh=$env{'user.refresh.time'};
                   6776:         if (!$refresh) { $refresh = $update; }
                   6777:         my $now = time;
                   6778:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6779:                            $now,'ca','constructaccess');
                   6780:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6781:         return($ownername,$ownerdomain,$ownerhome);
                   6782:     }
                   6783: # No business here
                   6784:     return '';
                   6785: }
                   6786: 
1.1162    raeburn  6787: sub get_comm_blocks {
                   6788:     my ($cdom,$cnum) = @_;
                   6789:     if ($cdom eq '' || $cnum eq '') {
                   6790:         return unless ($env{'request.course.id'});
                   6791:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6792:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6793:     }
                   6794:     my %commblocks;
                   6795:     my $hashid=$cdom.'_'.$cnum;
                   6796:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6797:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6798:         %commblocks = %{$blocksref};
                   6799:     } else {
                   6800:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6801:         my $cachetime = 600;
                   6802:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6803:     }
                   6804:     return %commblocks;
                   6805: }
                   6806: 
                   6807: sub has_comm_blocking {
                   6808:     my ($priv,$symb,$uri,$blocks) = @_;
                   6809:     return unless ($env{'request.course.id'});
                   6810:     return unless ($priv eq 'bre');
                   6811:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6812:     my %commblocks;
                   6813:     if (ref($blocks) eq 'HASH') {
                   6814:         %commblocks = %{$blocks};
                   6815:     } else {
                   6816:         %commblocks = &get_comm_blocks();
                   6817:     }
                   6818:     return unless (keys(%commblocks) > 0);
                   6819:     if (!$symb) { $symb=&symbread($uri,1); }
                   6820:     my ($map,$resid,undef)=&decode_symb($symb);
                   6821:     my %tocheck = (
                   6822:                     maps      => $map,
                   6823:                     resources => $symb,
                   6824:                   );
                   6825:     my @blockers;
                   6826:     my $now = time;
1.1163    raeburn  6827:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6828:     foreach my $block (keys(%commblocks)) {
                   6829:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6830:             my ($start,$end) = ($1,$2);
                   6831:             if ($start <= $now && $end >= $now) {
                   6832:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6833:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6834:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6835:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6836:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6837:                                     push(@blockers,$block);
                   6838:                                 }
                   6839:                             }
                   6840:                         }
                   6841:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6842:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6843:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6844:                                     push(@blockers,$block);
                   6845:                                 }
                   6846:                             }
                   6847:                         }
                   6848:                     }
                   6849:                 }
                   6850:             }
                   6851:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6852:             my $item = $1;
1.1163    raeburn  6853:             my @to_test;
1.1162    raeburn  6854:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6855:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6856:                     my $check_interval;
                   6857:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6858:                         my @interval;
                   6859:                         my $type = 'map';
                   6860:                         if ($item eq 'course') {
                   6861:                             $type = 'course';
                   6862:                             @interval=&EXT("resource.0.interval");
                   6863:                         } else {
                   6864:                             if ($item =~ /___\d+___/) {
                   6865:                                 $type = 'resource';
                   6866:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6867:                                 if (ref($navmap)) {                        
                   6868:                                     my $res = $navmap->getBySymb($item); 
                   6869:                                     push(@to_test,$res);
                   6870:                                 }
1.1162    raeburn  6871:                             } else {
                   6872:                                 my $mapsymb = &symbread($item,1);
                   6873:                                 if ($mapsymb) {
                   6874:                                     if (ref($navmap)) {
                   6875:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6876:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6877:                                         foreach my $res (@to_test) {
1.1162    raeburn  6878:                                             my $symb = $res->symb();
                   6879:                                             next if ($symb eq $mapsymb);
                   6880:                                             if ($symb ne '') {
                   6881:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6882:                                                 last;
                   6883:                                             }
                   6884:                                         }
                   6885:                                     }
                   6886:                                 }
                   6887:                             }
                   6888:                         }
                   6889:                         if ($interval[0] =~ /\d+/) {
                   6890:                             my $first_access;
                   6891:                             if ($type eq 'resource') {
                   6892:                                 $first_access=&get_first_access($interval[1],$item);
                   6893:                             } elsif ($type eq 'map') {
                   6894:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6895:                             } else {
                   6896:                                 $first_access=&get_first_access($interval[1]);
                   6897:                             }
                   6898:                             if ($first_access) {
                   6899:                                 my $timesup = $first_access+$interval[0];
                   6900:                                 if ($timesup > $now) {
1.1163    raeburn  6901:                                     foreach my $res (@to_test) {
                   6902:                                         if ($res->is_problem()) {
                   6903:                                             if ($res->completable()) {
                   6904:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6905:                                                     push(@blockers,$block);
                   6906:                                                 }
                   6907:                                                 last;
                   6908:                                             }
                   6909:                                         }
1.1162    raeburn  6910:                                     }
                   6911:                                 }
                   6912:                             }
                   6913:                         }
                   6914:                     }
                   6915:                 }
                   6916:             }
                   6917:         }
                   6918:     }
                   6919:     return @blockers;
                   6920: }
                   6921: 
                   6922: sub check_docs_block {
                   6923:     my ($docsblock,$tocheck) =@_;
                   6924:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6925:         return;
                   6926:     }
                   6927:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6928:         if ($tocheck->{'maps'}) {
                   6929:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6930:                 return 1;
                   6931:             }
                   6932:         }
                   6933:     }
                   6934:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6935:         if ($tocheck->{'resources'}) {
                   6936:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6937:                 return 1;
                   6938:             }
                   6939:         }
                   6940:     }
                   6941:     return;
                   6942: }
                   6943: 
1.1133    foxr     6944: #
                   6945: #   Removes the versino from a URI and
                   6946: #   splits it in to its filename and path to the filename.
                   6947: #   Seems like File::Basename could have done this more clearly.
                   6948: #   Parameters:
                   6949: #      $uri   - input URI
                   6950: #   Returns:
                   6951: #     Two element list consisting of 
                   6952: #     $pathname  - the URI up to and excluding the trailing /
                   6953: #     $filename  - The part of the URI following the last /
                   6954: #  NOTE:
                   6955: #    Another realization of this is simply:
                   6956: #    use File::Basename;
                   6957: #    ...
                   6958: #    $uri = shift;
                   6959: #    $filename = basename($uri);
                   6960: #    $path     = dirname($uri);
                   6961: #    return ($filename, $path);
                   6962: #
                   6963: #     The implementation below is probably faster however.
                   6964: #
1.710     albertel 6965: sub split_uri_for_cond {
                   6966:     my $uri=&deversion(&declutter(shift));
                   6967:     my @uriparts=split(/\//,$uri);
                   6968:     my $filename=pop(@uriparts);
                   6969:     my $pathname=join('/',@uriparts);
                   6970:     return ($pathname,$filename);
                   6971: }
1.232     www      6972: # --------------------------------------------------- Is a resource on the map?
                   6973: 
                   6974: sub is_on_map {
1.710     albertel 6975:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6976:     #Trying to find the conditional for the file
1.620     albertel 6977:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6978: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6979:     if ($match) {
1.289     bowersj2 6980: 	return (1,$1);
                   6981:     } else {
1.434     www      6982: 	return (0,0);
1.289     bowersj2 6983:     }
1.12      www      6984: }
                   6985: 
1.427     www      6986: # --------------------------------------------------------- Get symb from alias
                   6987: 
                   6988: sub get_symb_from_alias {
                   6989:     my $symb=shift;
                   6990:     my ($map,$resid,$url)=&decode_symb($symb);
                   6991: # Already is a symb
                   6992:     if ($url) { return $symb; }
                   6993: # Must be an alias
                   6994:     my $aliassymb='';
                   6995:     my %bighash;
1.620     albertel 6996:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6997:                             &GDBM_READER(),0640)) {
                   6998:         my $rid=$bighash{'mapalias_'.$symb};
                   6999: 	if ($rid) {
                   7000: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7001: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7002: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7003: 	}
                   7004:         untie %bighash;
                   7005:     }
                   7006:     return $aliassymb;
                   7007: }
                   7008: 
1.12      www      7009: # ----------------------------------------------------------------- Define Role
                   7010: 
                   7011: sub definerole {
                   7012:   if (allowed('mcr','/')) {
                   7013:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7014:     foreach my $role (split(':',$sysrole)) {
                   7015: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7016:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7017:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7018: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7019:                return "refused:s:$crole&$cqual"; 
                   7020:             }
                   7021:         }
1.191     harris41 7022:     }
1.800     albertel 7023:     foreach my $role (split(':',$domrole)) {
                   7024: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7025:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7026:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7027: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7028:                return "refused:d:$crole&$cqual"; 
                   7029:             }
                   7030:         }
1.191     harris41 7031:     }
1.800     albertel 7032:     foreach my $role (split(':',$courole)) {
                   7033: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7034:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7035:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7036: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7037:                return "refused:c:$crole&$cqual"; 
                   7038:             }
                   7039:         }
1.191     harris41 7040:     }
1.620     albertel 7041:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7042:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7043: 	        "rolesdef_$rolename=".
                   7044:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7045:     return reply($command,$env{'user.home'});
1.12      www      7046:   } else {
                   7047:     return 'refused';
                   7048:   }
1.105     harris41 7049: }
                   7050: 
                   7051: # ---------------- Make a metadata query against the network of library servers
                   7052: 
                   7053: sub metadata_query {
1.244     matthew  7054:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7055:     my %rhash;
1.845     albertel 7056:     my %libserv = &all_library();
1.244     matthew  7057:     my @server_list = (defined($server_array) ? @$server_array
                   7058:                                               : keys(%libserv) );
                   7059:     for my $server (@server_list) {
1.118     harris41 7060: 	unless ($custom or $customshow) {
                   7061: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7062: 	    $rhash{$server}=$reply;
                   7063: 	}
                   7064: 	else {
                   7065: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7066: 			     &escape($custom).':'.&escape($customshow),
                   7067: 			     $server);
                   7068: 	    $rhash{$server}=$reply;
                   7069: 	}
1.112     harris41 7070:     }
1.118     harris41 7071:     return \%rhash;
1.240     www      7072: }
                   7073: 
                   7074: # ----------------------------------------- Send log queries and wait for reply
                   7075: 
                   7076: sub log_query {
                   7077:     my ($uname,$udom,$query,%filters)=@_;
                   7078:     my $uhome=&homeserver($uname,$udom);
                   7079:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7080:     my $uhost=&hostname($uhome);
1.800     albertel 7081:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7082:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7083:                        $uhome);
1.479     albertel 7084:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7085:     return get_query_reply($queryid);
                   7086: }
                   7087: 
1.818     raeburn  7088: # -------------------------- Update MySQL table for portfolio file
                   7089: 
                   7090: sub update_portfolio_table {
1.821     raeburn  7091:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7092:     if ($group ne '') {
                   7093:         $file_name =~s /^\Q$group\E//;
                   7094:     }
1.818     raeburn  7095:     my $homeserver = &homeserver($uname,$udom);
                   7096:     my $queryid=
1.821     raeburn  7097:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7098:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7099:     my $reply = &get_query_reply($queryid);
                   7100:     return $reply;
                   7101: }
                   7102: 
1.899     raeburn  7103: # -------------------------- Update MySQL allusers table
                   7104: 
                   7105: sub update_allusers_table {
                   7106:     my ($uname,$udom,$names) = @_;
                   7107:     my $homeserver = &homeserver($uname,$udom);
                   7108:     my $queryid=
                   7109:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7110:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7111:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7112:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7113:                'generation='.&escape($names->{'generation'}).'%%'.
                   7114:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7115:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7116:     return;
1.899     raeburn  7117: }
                   7118: 
1.508     raeburn  7119: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7120: 
                   7121: sub fetch_enrollment_query {
1.511     raeburn  7122:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7123:     my $homeserver;
1.547     raeburn  7124:     my $maxtries = 1;
1.508     raeburn  7125:     if ($context eq 'automated') {
                   7126:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7127:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7128:     } else {
                   7129:         $homeserver = &homeserver($cnum,$dom);
                   7130:     }
1.838     albertel 7131:     my $host=&hostname($homeserver);
1.506     raeburn  7132:     my $cmd = '';
1.1000    raeburn  7133:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7134:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7135:     }
                   7136:     $cmd =~ s/%%$//;
                   7137:     $cmd = &escape($cmd);
                   7138:     my $query = 'fetchenrollment';
1.620     albertel 7139:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7140:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7141:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7142:         return 'error: '.$queryid;
                   7143:     }
1.506     raeburn  7144:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7145:     my $tries = 1;
                   7146:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7147:         $reply = &get_query_reply($queryid);
                   7148:         $tries ++;
                   7149:     }
1.526     raeburn  7150:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7151:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7152:     } else {
1.901     albertel 7153:         my @responses = split(/:/,$reply);
1.515     raeburn  7154:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7155:             foreach my $line (@responses) {
                   7156:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7157:                 $$replyref{$key} = $value;
                   7158:             }
                   7159:         } else {
1.1117    foxr     7160:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7161:             foreach my $line (@responses) {
                   7162:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7163:                 $$replyref{$key} = $value;
                   7164:                 if ($value > 0) {
1.800     albertel 7165:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7166:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7167:                         my $destname = $pathname.'/'.$filename;
                   7168:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7169:                         if ($xml_classlist =~ /^error/) {
                   7170:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7171:                         } else {
1.506     raeburn  7172:                             if ( open(FILE,">$destname") ) {
                   7173:                                 print FILE &unescape($xml_classlist);
                   7174:                                 close(FILE);
1.526     raeburn  7175:                             } else {
                   7176:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7177:                             }
                   7178:                         }
                   7179:                     }
                   7180:                 }
                   7181:             }
                   7182:         }
                   7183:         return 'ok';
                   7184:     }
                   7185:     return 'error';
                   7186: }
                   7187: 
1.242     www      7188: sub get_query_reply {
                   7189:     my $queryid=shift;
1.1117    foxr     7190:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7191:     my $reply='';
                   7192:     for (1..100) {
                   7193: 	sleep 2;
                   7194:         if (-e $replyfile.'.end') {
1.448     albertel 7195: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7196: 		$reply = join('',<$fh>);
                   7197: 		close($fh);
1.240     www      7198: 	   } else { return 'error: reply_file_error'; }
1.242     www      7199:            return &unescape($reply);
                   7200: 	}
1.240     www      7201:     }
1.242     www      7202:     return 'timeout:'.$queryid;
1.240     www      7203: }
                   7204: 
                   7205: sub courselog_query {
1.241     www      7206: #
                   7207: # possible filters:
                   7208: # url: url or symb
                   7209: # username
                   7210: # domain
                   7211: # action: view, submit, grade
                   7212: # start: timestamp
                   7213: # end: timestamp
                   7214: #
1.240     www      7215:     my (%filters)=@_;
1.620     albertel 7216:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7217:     if ($filters{'url'}) {
                   7218: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7219:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7220:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7221:     }
1.620     albertel 7222:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7223:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7224:     return &log_query($cname,$cdom,'courselog',%filters);
                   7225: }
                   7226: 
                   7227: sub userlog_query {
1.858     raeburn  7228: #
                   7229: # possible filters:
                   7230: # action: log check role
                   7231: # start: timestamp
                   7232: # end: timestamp
                   7233: #
1.240     www      7234:     my ($uname,$udom,%filters)=@_;
                   7235:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7236: }
                   7237: 
1.506     raeburn  7238: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7239: 
                   7240: sub auto_run {
1.508     raeburn  7241:     my ($cnum,$cdom) = @_;
1.876     raeburn  7242:     my $response = 0;
                   7243:     my $settings;
                   7244:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7245:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7246:         $settings = $domconfig{'autoenroll'};
                   7247:         if ($settings->{'run'} eq '1') {
                   7248:             $response = 1;
                   7249:         }
                   7250:     } else {
1.934     raeburn  7251:         my $homeserver;
                   7252:         if (&is_course($cdom,$cnum)) {
                   7253:             $homeserver = &homeserver($cnum,$cdom);
                   7254:         } else {
                   7255:             $homeserver = &domain($cdom,'primary');
                   7256:         }
                   7257:         if ($homeserver ne 'no_host') {
                   7258:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7259:         }
1.876     raeburn  7260:     }
1.506     raeburn  7261:     return $response;
                   7262: }
1.776     albertel 7263: 
1.506     raeburn  7264: sub auto_get_sections {
1.508     raeburn  7265:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7266:     my $homeserver;
                   7267:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7268:         $homeserver = &homeserver($cnum,$cdom);
                   7269:     }
                   7270:     if (!defined($homeserver)) { 
                   7271:         if ($cdom =~ /^$match_domain$/) {
                   7272:             $homeserver = &domain($cdom,'primary');
                   7273:         }
                   7274:     }
                   7275:     my @secs;
                   7276:     if (defined($homeserver)) {
                   7277:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7278:         unless ($response eq 'refused') {
                   7279:             @secs = split(/:/,$response);
                   7280:         }
1.506     raeburn  7281:     }
                   7282:     return @secs;
                   7283: }
1.776     albertel 7284: 
1.506     raeburn  7285: sub auto_new_course {
1.1099    raeburn  7286:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7287:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7288:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7289:     return $response;
                   7290: }
1.776     albertel 7291: 
1.506     raeburn  7292: sub auto_validate_courseID {
1.508     raeburn  7293:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7294:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7295:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7296:     return $response;
                   7297: }
1.776     albertel 7298: 
1.1007    raeburn  7299: sub auto_validate_instcode {
1.1020    raeburn  7300:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7301:     my ($homeserver,$response);
                   7302:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7303:         $homeserver = &homeserver($cnum,$cdom);
                   7304:     }
                   7305:     if (!defined($homeserver)) {
                   7306:         if ($cdom =~ /^$match_domain$/) {
                   7307:             $homeserver = &domain($cdom,'primary');
                   7308:         }
                   7309:     }
1.1065    raeburn  7310:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7311:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  7312:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   7313:     return ($outcome,$description);
1.1007    raeburn  7314: }
                   7315: 
1.506     raeburn  7316: sub auto_create_password {
1.873     raeburn  7317:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7318:     my ($homeserver,$response);
1.506     raeburn  7319:     my $create_passwd = 0;
                   7320:     my $authchk = '';
1.873     raeburn  7321:     if ($udom =~ /^$match_domain$/) {
                   7322:         $homeserver = &domain($udom,'primary');
                   7323:     }
                   7324:     if ($homeserver eq '') {
                   7325:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7326:             $homeserver = &homeserver($cnum,$cdom);
                   7327:         }
                   7328:     }
                   7329:     if ($homeserver eq '') {
                   7330:         $authchk = 'nodomain';
1.506     raeburn  7331:     } else {
1.873     raeburn  7332:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7333:         if ($response eq 'refused') {
                   7334:             $authchk = 'refused';
                   7335:         } else {
1.901     albertel 7336:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7337:         }
1.506     raeburn  7338:     }
                   7339:     return ($authparam,$create_passwd,$authchk);
                   7340: }
                   7341: 
1.706     raeburn  7342: sub auto_photo_permission {
                   7343:     my ($cnum,$cdom,$students) = @_;
                   7344:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7345:     my ($outcome,$perm_reqd,$conditions) = 
                   7346: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7347:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7348: 	return (undef,undef);
                   7349:     }
1.706     raeburn  7350:     return ($outcome,$perm_reqd,$conditions);
                   7351: }
                   7352: 
                   7353: sub auto_checkphotos {
                   7354:     my ($uname,$udom,$pid) = @_;
                   7355:     my $homeserver = &homeserver($uname,$udom);
                   7356:     my ($result,$resulttype);
                   7357:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7358: 				   &escape($uname).':'.&escape($pid),
                   7359: 				   $homeserver));
1.709     albertel 7360:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7361: 	return (undef,undef);
                   7362:     }
1.706     raeburn  7363:     if ($outcome) {
                   7364:         ($result,$resulttype) = split(/:/,$outcome);
                   7365:     } 
                   7366:     return ($result,$resulttype);
                   7367: }
                   7368: 
                   7369: sub auto_photochoice {
                   7370:     my ($cnum,$cdom) = @_;
                   7371:     my $homeserver = &homeserver($cnum,$cdom);
                   7372:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7373: 						       &escape($cdom),
                   7374: 						       $homeserver)));
1.709     albertel 7375:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7376: 	return (undef,undef);
                   7377:     }
1.706     raeburn  7378:     return ($update,$comment);
                   7379: }
                   7380: 
                   7381: sub auto_photoupdate {
                   7382:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7383:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7384:     my $host=&hostname($homeserver);
1.706     raeburn  7385:     my $cmd = '';
                   7386:     my $maxtries = 1;
1.800     albertel 7387:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7388:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7389:     }
                   7390:     $cmd =~ s/%%$//;
                   7391:     $cmd = &escape($cmd);
                   7392:     my $query = 'institutionalphotos';
                   7393:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7394:     unless ($queryid=~/^\Q$host\E\_/) {
                   7395:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7396:         return 'error: '.$queryid;
                   7397:     }
                   7398:     my $reply = &get_query_reply($queryid);
                   7399:     my $tries = 1;
                   7400:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7401:         $reply = &get_query_reply($queryid);
                   7402:         $tries ++;
                   7403:     }
                   7404:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7405:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7406:     } else {
                   7407:         my @responses = split(/:/,$reply);
                   7408:         my $outcome = shift(@responses); 
                   7409:         foreach my $item (@responses) {
                   7410:             my ($key,$value) = split(/=/,$item);
                   7411:             $$photo{$key} = $value;
                   7412:         }
                   7413:         return $outcome;
                   7414:     }
                   7415:     return 'error';
                   7416: }
                   7417: 
1.521     raeburn  7418: sub auto_instcode_format {
1.793     albertel 7419:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7420: 	$cat_order) = @_;
1.521     raeburn  7421:     my $courses = '';
1.772     raeburn  7422:     my @homeservers;
1.521     raeburn  7423:     if ($caller eq 'global') {
1.841     albertel 7424: 	my %servers = &get_servers($codedom,'library');
                   7425: 	foreach my $tryserver (keys(%servers)) {
                   7426: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7427: 		push(@homeservers,$tryserver);
                   7428: 	    }
1.584     raeburn  7429:         }
1.1022    raeburn  7430:     } elsif ($caller eq 'requests') {
                   7431:         if ($codedom =~ /^$match_domain$/) {
                   7432:             my $chome = &domain($codedom,'primary');
                   7433:             unless ($chome eq 'no_host') {
                   7434:                 push(@homeservers,$chome);
                   7435:             }
                   7436:         }
1.521     raeburn  7437:     } else {
1.772     raeburn  7438:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7439:     }
1.793     albertel 7440:     foreach my $code (keys(%{$instcodes})) {
                   7441:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7442:     }
                   7443:     chop($courses);
1.772     raeburn  7444:     my $ok_response = 0;
                   7445:     my $response;
                   7446:     while (@homeservers > 0 && $ok_response == 0) {
                   7447:         my $server = shift(@homeservers); 
                   7448:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7449:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7450:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7451: 		split(/:/,$response);
1.772     raeburn  7452:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7453:             push(@{$codetitles},&str2array($codetitles_str));
                   7454:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7455:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7456:             $ok_response = 1;
                   7457:         }
                   7458:     }
                   7459:     if ($ok_response) {
1.521     raeburn  7460:         return 'ok';
1.772     raeburn  7461:     } else {
                   7462:         return $response;
1.521     raeburn  7463:     }
                   7464: }
                   7465: 
1.792     raeburn  7466: sub auto_instcode_defaults {
                   7467:     my ($domain,$returnhash,$code_order) = @_;
                   7468:     my @homeservers;
1.841     albertel 7469: 
                   7470:     my %servers = &get_servers($domain,'library');
                   7471:     foreach my $tryserver (keys(%servers)) {
                   7472: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7473: 	    push(@homeservers,$tryserver);
                   7474: 	}
1.792     raeburn  7475:     }
1.841     albertel 7476: 
1.792     raeburn  7477:     my $response;
1.841     albertel 7478:     foreach my $server (@homeservers) {
1.792     raeburn  7479:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7480:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7481: 	
                   7482: 	foreach my $pair (split(/\&/,$response)) {
                   7483: 	    my ($name,$value)=split(/\=/,$pair);
                   7484: 	    if ($name eq 'code_order') {
                   7485: 		@{$code_order} = split(/\&/,&unescape($value));
                   7486: 	    } else {
                   7487: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7488: 	    }
                   7489: 	}
                   7490: 	return 'ok';
1.792     raeburn  7491:     }
1.841     albertel 7492: 
                   7493:     return $response;
1.1003    raeburn  7494: }
                   7495: 
                   7496: sub auto_possible_instcodes {
1.1007    raeburn  7497:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7498:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7499:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7500:         return;
                   7501:     }
1.1003    raeburn  7502:     my (@homeservers,$uhome);
                   7503:     if (defined(&domain($domain,'primary'))) {
                   7504:         $uhome=&domain($domain,'primary');
                   7505:         push(@homeservers,&domain($domain,'primary'));
                   7506:     } else {
                   7507:         my %servers = &get_servers($domain,'library');
                   7508:         foreach my $tryserver (keys(%servers)) {
                   7509:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7510:                 push(@homeservers,$tryserver);
                   7511:             }
                   7512:         }
                   7513:     }
                   7514:     my $response;
                   7515:     foreach my $server (@homeservers) {
                   7516:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7517:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7518:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7519:             split(':',$response);
                   7520:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7521:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7522:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7523:             my ($name,$value)=split('=',$item);
                   7524:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7525:         }
                   7526:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7527:             my ($name,$value)=split('=',$item);
                   7528:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7529:         }
                   7530:         return 'ok';
                   7531:     }
                   7532:     return $response;
                   7533: }
1.792     raeburn  7534: 
1.1010    raeburn  7535: sub auto_courserequest_checks {
                   7536:     my ($dom) = @_;
1.1020    raeburn  7537:     my ($homeserver,%validations);
                   7538:     if ($dom =~ /^$match_domain$/) {
                   7539:         $homeserver = &domain($dom,'primary');
                   7540:     }
                   7541:     unless ($homeserver eq 'no_host') {
                   7542:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7543:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7544:             my @items = split(/&/,$response);
                   7545:             foreach my $item (@items) {
                   7546:                 my ($key,$value) = split('=',$item);
                   7547:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7548:             }
                   7549:         }
                   7550:     }
1.1010    raeburn  7551:     return %validations; 
                   7552: }
                   7553: 
1.1020    raeburn  7554: sub auto_courserequest_validation {
                   7555:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7556:     my ($homeserver,$response);
                   7557:     if ($dom =~ /^$match_domain$/) {
                   7558:         $homeserver = &domain($dom,'primary');
                   7559:     }
                   7560:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7561:           
1.1020    raeburn  7562:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7563:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7564:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7565:                                     $homeserver));
                   7566:     }
                   7567:     return $response;
                   7568: }
                   7569: 
1.777     albertel 7570: sub auto_validate_class_sec {
1.918     raeburn  7571:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7572:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7573:     my $ownerlist;
                   7574:     if (ref($owners) eq 'ARRAY') {
                   7575:         $ownerlist = join(',',@{$owners});
                   7576:     } else {
                   7577:         $ownerlist = $owners;
                   7578:     }
1.773     raeburn  7579:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7580:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7581:     return $response;
                   7582: }
                   7583: 
1.679     raeburn  7584: # ------------------------------------------------------- Course Group routines
                   7585: 
                   7586: sub get_coursegroups {
1.809     raeburn  7587:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7588:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7589: }
                   7590: 
1.679     raeburn  7591: sub modify_coursegroup {
                   7592:     my ($cdom,$cnum,$groupsettings) = @_;
                   7593:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7594: }
                   7595: 
1.809     raeburn  7596: sub toggle_coursegroup_status {
                   7597:     my ($cdom,$cnum,$group,$action) = @_;
                   7598:     my ($from_namespace,$to_namespace);
                   7599:     if ($action eq 'delete') {
                   7600:         $from_namespace = 'coursegroups';
                   7601:         $to_namespace = 'deleted_groups';
                   7602:     } else {
                   7603:         $from_namespace = 'deleted_groups';
                   7604:         $to_namespace = 'coursegroups';
                   7605:     }
                   7606:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7607:     if (my $tmp = &error(%curr_group)) {
                   7608:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7609:         return ('read error',$tmp);
                   7610:     } else {
                   7611:         my %savedsettings = %curr_group; 
1.809     raeburn  7612:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7613:         my $deloutcome;
                   7614:         if ($result eq 'ok') {
1.809     raeburn  7615:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7616:         } else {
                   7617:             return ('write error',$result);
                   7618:         }
                   7619:         if ($deloutcome eq 'ok') {
                   7620:             return 'ok';
                   7621:         } else {
                   7622:             return ('delete error',$deloutcome);
                   7623:         }
                   7624:     }
                   7625: }
                   7626: 
1.679     raeburn  7627: sub modify_group_roles {
1.957     raeburn  7628:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7629:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7630:     my $role = 'gr/'.&escape($userprivs);
                   7631:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7632:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7633:     if ($result eq 'ok') {
                   7634:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7635:     }
1.679     raeburn  7636:     return $result;
                   7637: }
                   7638: 
                   7639: sub modify_coursegroup_membership {
                   7640:     my ($cdom,$cnum,$membership) = @_;
                   7641:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7642:     return $result;
                   7643: }
                   7644: 
1.682     raeburn  7645: sub get_active_groups {
                   7646:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7647:     my $now = time;
                   7648:     my %groups = ();
                   7649:     foreach my $key (keys(%env)) {
1.811     albertel 7650:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7651:             my ($start,$end) = split(/\./,$env{$key});
                   7652:             if (($end!=0) && ($end<$now)) { next; }
                   7653:             if (($start!=0) && ($start>$now)) { next; }
                   7654:             if ($1 eq $cdom && $2 eq $cnum) {
                   7655:                 $groups{$3} = $env{$key} ;
                   7656:             }
                   7657:         }
                   7658:     }
                   7659:     return %groups;
                   7660: }
                   7661: 
1.683     raeburn  7662: sub get_group_membership {
                   7663:     my ($cdom,$cnum,$group) = @_;
                   7664:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7665: }
                   7666: 
                   7667: sub get_users_groups {
                   7668:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7669:     my @usersgroups;
1.683     raeburn  7670:     my $cachetime=1800;
                   7671: 
                   7672:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7673:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7674:     if (defined($cached)) {
1.734     albertel 7675:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7676:     } else {  
                   7677:         $grouplist = '';
1.816     raeburn  7678:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7679:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7680:         my $access_end = $env{'course.'.$courseid.
                   7681:                               '.default_enrollment_end_date'};
                   7682:         my $now = time;
                   7683:         foreach my $key (keys(%roleshash)) {
                   7684:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7685:                 my $group = $1;
                   7686:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7687:                     my $start = $2;
                   7688:                     my $end = $1;
                   7689:                     if ($start == -1) { next; } # deleted from group
                   7690:                     if (($start!=0) && ($start>$now)) { next; }
                   7691:                     if (($end!=0) && ($end<$now)) {
                   7692:                         if ($access_end && $access_end < $now) {
                   7693:                             if ($access_end - $end < 86400) {
                   7694:                                 push(@usersgroups,$group);
1.733     raeburn  7695:                             }
                   7696:                         }
1.817     raeburn  7697:                         next;
1.733     raeburn  7698:                     }
1.817     raeburn  7699:                     push(@usersgroups,$group);
1.683     raeburn  7700:                 }
                   7701:             }
                   7702:         }
1.817     raeburn  7703:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7704:         $grouplist = join(':',@usersgroups);
                   7705:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7706:     }
1.733     raeburn  7707:     return @usersgroups;
1.683     raeburn  7708: }
                   7709: 
                   7710: sub devalidate_getgroups_cache {
                   7711:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7712:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7713: 
1.683     raeburn  7714:     my $hashid="$udom:$uname:$courseid";
                   7715:     &devalidate_cache_new('getgroups',$hashid);
                   7716: }
                   7717: 
1.12      www      7718: # ------------------------------------------------------------------ Plain Text
                   7719: 
                   7720: sub plaintext {
1.988     raeburn  7721:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7722:     if ($short =~ m{^cr/}) {
1.758     albertel 7723: 	return (split('/',$short))[-1];
                   7724:     }
1.742     raeburn  7725:     if (!defined($cid)) {
                   7726:         $cid = $env{'request.course.id'};
                   7727:     }
                   7728:     my %rolenames = (
1.1008    raeburn  7729:                       Course    => 'std',
                   7730:                       Community => 'alt1',
1.742     raeburn  7731:                     );
1.1037    raeburn  7732:     if ($cid ne '') {
                   7733:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7734:             unless ($forcedefault) {
                   7735:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7736:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7737:                 return &Apache::lonlocal::mt($roletext);
                   7738:             }
                   7739:         }
                   7740:     }
                   7741:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7742:         (defined($rolenames{$type})) && 
                   7743:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7744:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7745:     } elsif ($cid ne '') {
                   7746:         my $crstype = $env{'course.'.$cid.'.type'};
                   7747:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7748:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7749:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7750:         }
1.742     raeburn  7751:     }
1.1037    raeburn  7752:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7753: }
                   7754: 
                   7755: # ----------------------------------------------------------------- Assign Role
                   7756: 
                   7757: sub assignrole {
1.957     raeburn  7758:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7759:         $context)=@_;
1.21      www      7760:     my $mrole;
                   7761:     if ($role =~ /^cr\//) {
1.393     www      7762:         my $cwosec=$url;
1.811     albertel 7763:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7764: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7765:            my $refused = 1;
                   7766:            if ($context eq 'requestcourses') {
                   7767:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7768:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7769:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7770:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7771:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7772:                            if ($crsenv{'internal.courseowner'} eq
                   7773:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7774:                                $refused = '';
                   7775:                            }
                   7776:                        }
                   7777:                    }
                   7778:                }
                   7779:            }
                   7780:            if ($refused) {
                   7781:                &logthis('Refused custom assignrole: '.
                   7782:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7783:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7784:                return 'refused';
                   7785:            }
1.104     www      7786:         }
1.21      www      7787:         $mrole='cr';
1.678     raeburn  7788:     } elsif ($role =~ /^gr\//) {
                   7789:         my $cwogrp=$url;
1.811     albertel 7790:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7791:         unless (&allowed('mdg',$cwogrp)) {
                   7792:             &logthis('Refused group assignrole: '.
                   7793:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7794:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7795:             return 'refused';
                   7796:         }
                   7797:         $mrole='gr';
1.21      www      7798:     } else {
1.82      www      7799:         my $cwosec=$url;
1.811     albertel 7800:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7801:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7802:             my $refused;
                   7803:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7804:                 if (!(&allowed('c'.$role,$url))) {
                   7805:                     $refused = 1;
                   7806:                 }
                   7807:             } else {
                   7808:                 $refused = 1;
                   7809:             }
1.947     raeburn  7810:             if ($refused) {
1.1045    raeburn  7811:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7812:                 if (!$selfenroll && $context eq 'course') {
                   7813:                     my %crsenv;
                   7814:                     if ($role eq 'cc' || $role eq 'co') {
                   7815:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7816:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7817:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7818:                                 if ($crsenv{'internal.courseowner'} eq 
                   7819:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7820:                                     $refused = '';
                   7821:                                 }
                   7822:                             }
                   7823:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7824:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7825:                                 if ($crsenv{'internal.courseowner'} eq 
                   7826:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7827:                                     $refused = '';
                   7828:                                 }
                   7829:                             }
                   7830:                         }
                   7831:                     }
                   7832:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7833:                     $refused = '';
1.1017    raeburn  7834:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7835:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7836:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7837:                         my $wrongcc;
                   7838:                         if ($cnum =~ /^$match_community$/) {
                   7839:                             $wrongcc = 1 if ($role eq 'cc');
                   7840:                         } else {
                   7841:                             $wrongcc = 1 if ($role eq 'co');
                   7842:                         }
                   7843:                         unless ($wrongcc) {
                   7844:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7845:                             if ($crsenv{'internal.courseowner'} eq 
                   7846:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7847:                                 $refused = '';
                   7848:                             }
1.1017    raeburn  7849:                         }
                   7850:                     }
1.1183    raeburn  7851:                 } elsif ($context eq 'requestauthor') {
                   7852:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   7853:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7854:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7855:                             $refused = '';
                   7856:                         } else {
                   7857:                             my %domdefaults = &get_domain_defaults($udom);
                   7858:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7859:                                 my $checkbystatus;
                   7860:                                 if ($env{'user.adv'}) { 
                   7861:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7862:                                     if ($disposition eq 'automatic') {
                   7863:                                         $refused = '';
                   7864:                                     } elsif ($disposition eq '') {
                   7865:                                         $checkbystatus = 1;
                   7866:                                     } 
                   7867:                                 } else {
                   7868:                                     $checkbystatus = 1;
                   7869:                                 }
                   7870:                                 if ($checkbystatus) {
                   7871:                                     if ($env{'environment.inststatus'}) {
                   7872:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7873:                                         foreach my $type (@inststatuses) {
                   7874:                                             if (($type ne '') &&
                   7875:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7876:                                                 $refused = '';
                   7877:                                             }
                   7878:                                         }
                   7879:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   7880:                                         $refused = '';
                   7881:                                     }
                   7882:                                 }
                   7883:                             }
                   7884:                         }
                   7885:                     }
1.1017    raeburn  7886:                 }
                   7887:                 if ($refused) {
1.947     raeburn  7888:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7889:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7890: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7891:                     return 'refused';
                   7892:                 }
1.932     raeburn  7893:             }
1.1131    raeburn  7894:         } elsif ($role eq 'au') {
                   7895:             if ($url ne '/'.$udom.'/') {
                   7896:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7897:                          ' to assign author role for '.$uname.':'.$udom.
                   7898:                          ' in domain: '.$url.' refused (wrong domain).');
                   7899:                 return 'refused';
                   7900:             }
1.104     www      7901:         }
1.21      www      7902:         $mrole=$role;
                   7903:     }
1.620     albertel 7904:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7905:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7906:     if ($end) { $command.='_'.$end; }
1.21      www      7907:     if ($start) {
                   7908: 	if ($end) { 
1.81      www      7909:            $command.='_'.$start; 
1.21      www      7910:         } else {
1.81      www      7911:            $command.='_0_'.$start;
1.21      www      7912:         }
                   7913:     }
1.739     raeburn  7914:     my $origstart = $start;
                   7915:     my $origend = $end;
1.957     raeburn  7916:     my $delflag;
1.357     www      7917: # actually delete
                   7918:     if ($deleteflag) {
1.373     www      7919: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7920: # modify command to delete the role
1.620     albertel 7921:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7922:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7923: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7924: # set start and finish to negative values for userrolelog
                   7925:            $start=-1;
                   7926:            $end=-1;
1.957     raeburn  7927:            $delflag = 1;
1.357     www      7928:         }
                   7929:     }
                   7930: # send command
1.349     www      7931:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7932: # log new user role if status is ok
1.349     www      7933:     if ($answer eq 'ok') {
1.663     raeburn  7934: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7935: # for course roles, perform group memberships changes triggered by role change.
                   7936:         unless ($role =~ /^gr/) {
                   7937:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7938:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7939:         }
1.1184    raeburn  7940:         if (($role eq 'cc') || ($role eq 'in') ||
                   7941:             ($role eq 'ep') || ($role eq 'ad') ||
                   7942:             ($role eq 'ta') || ($role eq 'st') ||
                   7943:             ($role=~/^cr/) || ($role eq 'gr') ||
                   7944:             ($role eq 'co')) {
                   7945:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7946:                            $selfenroll,$context);
                   7947:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   7948:                  ($role eq 'au') || ($role eq 'dc')) {
                   7949:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7950:                            $context);
                   7951:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   7952:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7953:                              $context); 
                   7954:         }
1.1053    raeburn  7955:         if ($role eq 'cc') {
                   7956:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7957:         }
1.349     www      7958:     }
                   7959:     return $answer;
1.169     harris41 7960: }
                   7961: 
1.1053    raeburn  7962: sub autoupdate_coowners {
                   7963:     my ($url,$end,$start,$uname,$udom) = @_;
                   7964:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7965:     if (($cdom ne '') && ($cnum ne '')) {
                   7966:         my $now = time;
                   7967:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7968:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7969:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7970:             my $instcode = $coursehash{'internal.coursecode'};
                   7971:             if ($instcode ne '') {
1.1056    raeburn  7972:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7973:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7974:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7975:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7976:                         if ($result eq 'valid') {
                   7977:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7978:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7979:                                     push(@newcoowners,$coowner);
                   7980:                                 }
                   7981:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7982:                                     push(@newcoowners,$uname.':'.$udom);
                   7983:                                 }
                   7984:                                 @newcoowners = sort(@newcoowners);
                   7985:                             } else {
                   7986:                                 push(@newcoowners,$uname.':'.$udom);
                   7987:                             }
                   7988:                         } else {
                   7989:                             if ($coursehash{'internal.co-owners'}) {
                   7990:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7991:                                     unless ($coowner eq $uname.':'.$udom) {
                   7992:                                         push(@newcoowners,$coowner);
                   7993:                                     }
                   7994:                                 }
                   7995:                                 unless (@newcoowners > 0) {
                   7996:                                     $delcoowners = 1;
                   7997:                                     $coowners = '';
                   7998:                                 }
                   7999:                             }
                   8000:                         }
                   8001:                         if (@newcoowners || $delcoowners) {
                   8002:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8003:                                             $delcoowners,@newcoowners);
                   8004:                         }
                   8005:                     }
                   8006:                 }
                   8007:             }
                   8008:         }
                   8009:     }
                   8010: }
                   8011: 
                   8012: sub store_coowners {
                   8013:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8014:     my $cid = $cdom.'_'.$cnum;
                   8015:     my ($coowners,$delresult,$putresult);
                   8016:     if (@newcoowners) {
                   8017:         $coowners = join(',',@newcoowners);
                   8018:         my %coownershash = (
                   8019:                             'internal.co-owners' => $coowners,
                   8020:                            );
                   8021:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8022:         if ($putresult eq 'ok') {
                   8023:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8024:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8025:             }
                   8026:         }
                   8027:     }
                   8028:     if ($delcoowners) {
                   8029:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8030:         if ($delresult eq 'ok') {
                   8031:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8032:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8033:             }
                   8034:         }
                   8035:     }
                   8036:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8037:         my %crsinfo =
                   8038:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8039:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8040:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8041:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8042:         }
                   8043:     }
                   8044: }
                   8045: 
1.169     harris41 8046: # -------------------------------------------------- Modify user authentication
1.197     www      8047: # Overrides without validation
                   8048: 
1.169     harris41 8049: sub modifyuserauth {
                   8050:     my ($udom,$uname,$umode,$upass)=@_;
                   8051:     my $uhome=&homeserver($uname,$udom);
1.197     www      8052:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8053:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8054:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8055:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8056:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8057: 		     &escape($upass),$uhome);
1.620     albertel 8058:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8059:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8060:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8061:     &log($udom,,$uname,$uhome,
1.620     albertel 8062:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8063:                                      $env{'user.name'}.', '.$umode.
1.197     www      8064:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8065:     unless ($reply eq 'ok') {
1.197     www      8066:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8067: 	return 'error: '.$reply;
                   8068:     }   
1.170     harris41 8069:     return 'ok';
1.80      www      8070: }
                   8071: 
1.81      www      8072: # --------------------------------------------------------------- Modify a user
1.80      www      8073: 
1.81      www      8074: sub modifyuser {
1.206     matthew  8075:     my ($udom,    $uname, $uid,
                   8076:         $umode,   $upass, $first,
                   8077:         $middle,  $last,  $gene,
1.1058    raeburn  8078:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8079:     $udom= &LONCAPA::clean_domain($udom);
                   8080:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8081:     my $showcandelete = 'none';
                   8082:     if (ref($candelete) eq 'ARRAY') {
                   8083:         if (@{$candelete} > 0) {
                   8084:             $showcandelete = join(', ',@{$candelete});
                   8085:         }
                   8086:     }
1.81      www      8087:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8088:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8089: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8090:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8091:                                      ' desiredhome not specified'). 
1.620     albertel 8092:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8093:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8094:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8095:     my $newuser;
                   8096:     if ($uhome eq 'no_host') {
                   8097:         $newuser = 1;
                   8098:     }
1.80      www      8099: # ----------------------------------------------------------------- Create User
1.406     albertel 8100:     if (($uhome eq 'no_host') && 
                   8101: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8102:         my $unhome='';
1.844     albertel 8103:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8104:             $unhome = $desiredhome;
1.620     albertel 8105: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8106: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8107:         } else { # load balancing routine for determining $unhome
1.81      www      8108:             my $loadm=10000000;
1.841     albertel 8109: 	    my %servers = &get_servers($udom,'library');
                   8110: 	    foreach my $tryserver (keys(%servers)) {
                   8111: 		my $answer=reply('load',$tryserver);
                   8112: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8113: 		    $loadm=$answer;
                   8114: 		    $unhome=$tryserver;
                   8115: 		}
1.80      www      8116: 	    }
                   8117:         }
                   8118:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8119: 	    return 'error: unable to find a home server for '.$uname.
                   8120:                    ' in domain '.$udom;
1.80      www      8121:         }
                   8122:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8123:                          &escape($upass),$unhome);
                   8124: 	unless ($reply eq 'ok') {
                   8125:             return 'error: '.$reply;
                   8126:         }   
1.230     stredwic 8127:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8128:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8129: 	    return 'error: unable verify users home machine.';
1.80      www      8130:         }
1.209     matthew  8131:     }   # End of creation of new user
1.80      www      8132: # ---------------------------------------------------------------------- Add ID
                   8133:     if ($uid) {
                   8134:        $uid=~tr/A-Z/a-z/;
                   8135:        my %uidhash=&idrget($udom,$uname);
1.196     www      8136:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8137:          && (!$forceid)) {
1.80      www      8138: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8139: 	      return 'error: user id "'.$uid.'" does not match '.
                   8140:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8141:           }
                   8142:        } else {
                   8143: 	  &idput($udom,($uname => $uid));
                   8144:        }
                   8145:     }
                   8146: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8147:     my @tmp=&get('environment',
1.899     raeburn  8148: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8149:                     'permanentemail','inststatus'],
1.134     albertel 8150: 		   $udom,$uname);
1.1075    raeburn  8151:     my (%names,%oldnames);
1.313     matthew  8152:     if ($tmp[0] =~ m/^error:.*/) { 
                   8153:         %names=(); 
                   8154:     } else {
                   8155:         %names = @tmp;
1.1075    raeburn  8156:         %oldnames = %names;
1.313     matthew  8157:     }
1.388     www      8158: #
1.1058    raeburn  8159: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8160: # of users did not contain them), do not overwrite existing values
                   8161: # unless field is in $candelete array ref.  
                   8162: #
                   8163: 
                   8164:     my @fields = ('firstname','middlename','lastname','generation',
                   8165:                   'permanentemail','id');
                   8166:     my %newvalues;
                   8167:     if (ref($candelete) eq 'ARRAY') {
                   8168:         foreach my $field (@fields) {
                   8169:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8170:                 if ($field eq 'firstname') {
                   8171:                     $names{$field} = $first;
                   8172:                 } elsif ($field eq 'middlename') {
                   8173:                     $names{$field} = $middle;
                   8174:                 } elsif ($field eq 'lastname') {
                   8175:                     $names{$field} = $last;
                   8176:                 } elsif ($field eq 'generation') { 
                   8177:                     $names{$field} = $gene;
                   8178:                 } elsif ($field eq 'permanentemail') {
                   8179:                     $names{$field} = $email;
                   8180:                 } elsif ($field eq 'id') {
                   8181:                     $names{$field}  = $uid;
                   8182:                 }
                   8183:             }
                   8184:         }
                   8185:     }
1.388     www      8186:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8187:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8188:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8189:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8190:     if ($email) {
                   8191:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8192:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8193:     }
1.899     raeburn  8194:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8195:     if (defined($inststatus)) {
                   8196:         $names{'inststatus'} = '';
                   8197:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8198:         if (ref($usertypes) eq 'HASH') {
                   8199:             my @okstatuses; 
                   8200:             foreach my $item (split(/:/,$inststatus)) {
                   8201:                 if (defined($usertypes->{$item})) {
                   8202:                     push(@okstatuses,$item);  
                   8203:                 }
                   8204:             }
                   8205:             if (@okstatuses) {
                   8206:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8207:             }
                   8208:         }
                   8209:     }
1.1075    raeburn  8210:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8211:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8212:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8213:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8214:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8215:     } else {
                   8216:         $logmsg .= ' during self creation';
                   8217:     }
1.1075    raeburn  8218:     my $changed;
                   8219:     if ($newuser) {
                   8220:         $changed = 1;
                   8221:     } else {
                   8222:         foreach my $field (@fields) {
                   8223:             if ($names{$field} ne $oldnames{$field}) {
                   8224:                 $changed = 1;
                   8225:                 last;
                   8226:             }
                   8227:         }
                   8228:     }
                   8229:     unless ($changed) {
                   8230:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8231:         &logthis($logmsg);
                   8232:         return 'ok';
                   8233:     }
                   8234:     my $reply = &put('environment', \%names, $udom,$uname);
                   8235:     if ($reply ne 'ok') { 
                   8236:         return 'error: '.$reply;
                   8237:     }
1.1087    raeburn  8238:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8239:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8240:     }
1.1075    raeburn  8241:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8242:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8243:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8244:     &logthis($logmsg);
1.134     albertel 8245:     return 'ok';
1.80      www      8246: }
                   8247: 
1.81      www      8248: # -------------------------------------------------------------- Modify student
1.80      www      8249: 
1.81      www      8250: sub modifystudent {
                   8251:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8252:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  8253:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 8254:     if (!$cid) {
1.620     albertel 8255: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8256: 	    return 'not_in_class';
                   8257: 	}
1.80      www      8258:     }
                   8259: # --------------------------------------------------------------- Make the user
1.81      www      8260:     my $reply=&modifyuser
1.209     matthew  8261: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8262:          $desiredhome,$email,$inststatus);
1.80      www      8263:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8264:     # This will cause &modify_student_enrollment to get the uid from the
                   8265:     # students environment
                   8266:     $uid = undef if (!$forceid);
1.455     albertel 8267:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  8268: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  8269:     return $reply;
                   8270: }
                   8271: 
                   8272: sub modify_student_enrollment {
1.957     raeburn  8273:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 8274:     my ($cdom,$cnum,$chome);
                   8275:     if (!$cid) {
1.620     albertel 8276: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8277: 	    return 'not_in_class';
                   8278: 	}
1.620     albertel 8279: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8280: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8281:     } else {
                   8282: 	($cdom,$cnum)=split(/_/,$cid);
                   8283:     }
1.620     albertel 8284:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8285:     if (!$chome) {
1.457     raeburn  8286: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8287:     }
1.455     albertel 8288:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8289:     # Make sure the user exists
1.81      www      8290:     my $uhome=&homeserver($uname,$udom);
                   8291:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8292: 	return 'error: no such user';
                   8293:     }
1.297     matthew  8294:     # Get student data if we were not given enough information
                   8295:     if (!defined($first)  || $first  eq '' || 
                   8296:         !defined($last)   || $last   eq '' || 
                   8297:         !defined($uid)    || $uid    eq '' || 
                   8298:         !defined($middle) || $middle eq '' || 
                   8299:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8300:         # They did not supply us with enough data to enroll the student, so
                   8301:         # we need to pick up more information.
1.297     matthew  8302:         my %tmp = &get('environment',
1.294     matthew  8303:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8304:                        ,$udom,$uname);
                   8305: 
1.800     albertel 8306:         #foreach my $key (keys(%tmp)) {
                   8307:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8308:         #}
1.294     matthew  8309:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8310:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8311:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8312:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8313:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8314:     }
1.556     albertel 8315:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8316:     my $user = "$uname:$udom";
                   8317:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8318:     my $reply=cput('classlist',
1.1148    raeburn  8319: 		   {$user => 
1.515     raeburn  8320: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 8321: 		   $cdom,$cnum);
1.1148    raeburn  8322:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8323:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8324:     } else { 
1.81      www      8325: 	return 'error: '.$reply;
                   8326:     }
1.297     matthew  8327:     # Add student role to user
1.83      www      8328:     my $uurl='/'.$cid;
1.81      www      8329:     $uurl=~s/\_/\//g;
                   8330:     if ($usec) {
                   8331: 	$uurl.='/'.$usec;
                   8332:     }
1.1148    raeburn  8333:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8334:                              $selfenroll,$context);
                   8335:     if ($result ne 'ok') {
                   8336:         if ($old_entry{$user} ne '') {
                   8337:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8338:         } else {
                   8339:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8340:         }
                   8341:     }
                   8342:     return $result; 
1.21      www      8343: }
                   8344: 
1.556     albertel 8345: sub format_name {
                   8346:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8347:     my $name;
                   8348:     if ($first ne 'lastname') {
                   8349: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8350:     } else {
                   8351: 	if ($lastname=~/\S/) {
                   8352: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8353: 	    $name=~s/\s+,/,/;
                   8354: 	} else {
                   8355: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8356: 	}
                   8357:     }
                   8358:     $name=~s/^\s+//;
                   8359:     $name=~s/\s+$//;
                   8360:     $name=~s/\s+/ /g;
                   8361:     return $name;
                   8362: }
                   8363: 
1.84      www      8364: # ------------------------------------------------- Write to course preferences
                   8365: 
                   8366: sub writecoursepref {
                   8367:     my ($courseid,%prefs)=@_;
                   8368:     $courseid=~s/^\///;
                   8369:     $courseid=~s/\_/\//g;
                   8370:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8371:     my $chome=homeserver($cnum,$cdomain);
                   8372:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8373: 	return 'error: no such course';
                   8374:     }
                   8375:     my $cstring='';
1.800     albertel 8376:     foreach my $pref (keys(%prefs)) {
                   8377: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8378:     }
1.84      www      8379:     $cstring=~s/\&$//;
                   8380:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8381: }
                   8382: 
                   8383: # ---------------------------------------------------------- Make/modify course
                   8384: 
                   8385: sub createcourse {
1.741     raeburn  8386:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8387:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8388:     $url=&declutter($url);
                   8389:     my $cid='';
1.1028    raeburn  8390:     if ($context eq 'requestcourses') {
                   8391:         my $can_create = 0;
                   8392:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8393:         if ($udom eq $ownerdom) {
                   8394:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8395:                                   $context)) {
                   8396:                 $can_create = 1;
                   8397:             }
                   8398:         } else {
                   8399:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8400:                                            $category);
                   8401:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8402:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8403:                 if (@curr > 0) {
                   8404:                     my @options = qw(approval validate autolimit);
                   8405:                     my $optregex = join('|',@options);
                   8406:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8407:                         $can_create = 1;
                   8408:                     }
                   8409:                 }
                   8410:             }
                   8411:         }
                   8412:         if ($can_create) {
                   8413:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8414:                 unless (&allowed('ccc',$udom)) {
                   8415:                     return 'refused'; 
                   8416:                 }
1.1017    raeburn  8417:             }
                   8418:         } else {
                   8419:             return 'refused';
                   8420:         }
1.1028    raeburn  8421:     } elsif (!&allowed('ccc',$udom)) {
                   8422:         return 'refused';
1.84      www      8423:     }
1.1011    raeburn  8424: # --------------------------------------------------------------- Get Unique ID
                   8425:     my $uname;
                   8426:     if ($cnum =~ /^$match_courseid$/) {
                   8427:         my $chome=&homeserver($cnum,$udom,'true');
                   8428:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8429:             $uname = $cnum;
                   8430:         } else {
1.1038    raeburn  8431:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8432:         }
                   8433:     } else {
1.1038    raeburn  8434:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8435:     }
                   8436:     return $uname if ($uname =~ /^error/);
                   8437: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8438:     if (!defined($course_server)) {
                   8439:         if (defined(&domain($udom,'primary'))) {
                   8440:             $course_server = &domain($udom,'primary');
                   8441:         } else {
                   8442:             $course_server = $env{'user.home'}; 
                   8443:         }
                   8444:     }
                   8445:     my %host_servers =
                   8446:         &Apache::lonnet::get_servers($udom,'library');
                   8447:     unless ($host_servers{$course_server}) {
                   8448:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8449:     }
1.84      www      8450: # ------------------------------------------------------------- Make the course
                   8451:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8452:                       $course_server);
1.84      www      8453:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8454:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8455:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8456: 	return 'error: no such course';
                   8457:     }
1.271     www      8458: # ----------------------------------------------------------------- Course made
1.516     raeburn  8459: # log existence
1.1029    raeburn  8460:     my $now = time;
1.918     raeburn  8461:     my $newcourse = {
                   8462:                     $udom.'_'.$uname => {
1.921     raeburn  8463:                                      description => $description,
                   8464:                                      inst_code   => $inst_code,
                   8465:                                      owner       => $course_owner,
                   8466:                                      type        => $crstype,
1.1029    raeburn  8467:                                      creator     => $env{'user.name'}.':'.
                   8468:                                                     $env{'user.domain'},
                   8469:                                      created     => $now,
                   8470:                                      context     => $context,
1.918     raeburn  8471:                                                 },
                   8472:                     };
1.921     raeburn  8473:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8474: # set toplevel url
1.271     www      8475:     my $topurl=$url;
                   8476:     unless ($nonstandard) {
                   8477: # ------------------------------------------ For standard courses, make top url
                   8478:         my $mapurl=&clutter($url);
1.278     www      8479:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8480:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8481: <map>
                   8482: <resource id="1" type="start"></resource>
                   8483: <resource id="2" src="$mapurl"></resource>
                   8484: <resource id="3" type="finish"></resource>
                   8485: <link index="1" from="1" to="2"></link>
                   8486: <link index="2" from="2" to="3"></link>
                   8487: </map>
                   8488: ENDINITMAP
                   8489:         $topurl=&declutter(
1.638     albertel 8490:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8491:                           );
                   8492:     }
                   8493: # ----------------------------------------------------------- Write preferences
1.84      www      8494:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8495:                      ('description'              => $description,
                   8496:                       'url'                      => $topurl,
                   8497:                       'internal.creator'         => $env{'user.name'}.':'.
                   8498:                                                     $env{'user.domain'},
                   8499:                       'internal.created'         => $now,
                   8500:                       'internal.creationcontext' => $context)
                   8501:                     );
1.84      www      8502:     return '/'.$udom.'/'.$uname;
                   8503: }
                   8504: 
1.1011    raeburn  8505: # ------------------------------------------------------------------- Create ID
                   8506: sub generate_coursenum {
1.1038    raeburn  8507:     my ($udom,$crstype) = @_;
1.1011    raeburn  8508:     my $domdesc = &domain($udom);
                   8509:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8510:     my $first;
                   8511:     if ($crstype eq 'Community') {
                   8512:         $first = '0';
                   8513:     } else {
                   8514:         $first = int(1+rand(9)); 
                   8515:     } 
                   8516:     my $uname=$first.
1.1011    raeburn  8517:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8518:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8519:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8520: # ----------------------------------------------- Make sure that does not exist
                   8521:     my $uhome=&homeserver($uname,$udom,'true');
                   8522:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8523:         if ($crstype eq 'Community') {
                   8524:             $first = '0';
                   8525:         } else {
                   8526:             $first = int(1+rand(9));
                   8527:         }
                   8528:         $uname=$first.
1.1011    raeburn  8529:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8530:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8531:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8532:         $uhome=&homeserver($uname,$udom,'true');
                   8533:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8534:             return 'error: unable to generate unique course-ID';
                   8535:         }
                   8536:     }
                   8537:     return $uname;
                   8538: }
                   8539: 
1.813     albertel 8540: sub is_course {
1.1167    droeschl 8541:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8542:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8543: 
                   8544:     return unless $cdom and $cnum;
                   8545: 
                   8546:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8547:         '.');
                   8548: 
                   8549:     return unless exists($courses{$cdom.'_'.$cnum});
                   8550:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8551: }
                   8552: 
1.1015    raeburn  8553: sub store_userdata {
                   8554:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8555:     my $result;
1.1016    raeburn  8556:     if ($datakey ne '') {
1.1013    raeburn  8557:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8558:             if ($udom eq '' || $uname eq '') {
                   8559:                 $udom = $env{'user.domain'};
                   8560:                 $uname = $env{'user.name'};
                   8561:             }
                   8562:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8563:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8564:                 $result = 'error: no_host';
                   8565:             } else {
                   8566:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8567:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8568: 
                   8569:                 my $namevalue='';
                   8570:                 foreach my $key (keys(%{$storehash})) {
                   8571:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8572:                 }
                   8573:                 $namevalue=~s/\&$//;
1.1105    raeburn  8574:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8575:                                   $namevalue,$uhome);
1.1013    raeburn  8576:             }
                   8577:         } else {
                   8578:             $result = 'error: data to store was not a hash reference'; 
                   8579:         }
                   8580:     } else {
                   8581:         $result= 'error: invalid requestkey'; 
                   8582:     }
                   8583:     return $result;
                   8584: }
                   8585: 
1.21      www      8586: # ---------------------------------------------------------- Assign Custom Role
                   8587: 
                   8588: sub assigncustomrole {
1.957     raeburn  8589:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8590:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8591:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8592: }
                   8593: 
                   8594: # ----------------------------------------------------------------- Revoke Role
                   8595: 
                   8596: sub revokerole {
1.957     raeburn  8597:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8598:     my $now=time;
1.965     raeburn  8599:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8600: }
                   8601: 
                   8602: # ---------------------------------------------------------- Revoke Custom Role
                   8603: 
                   8604: sub revokecustomrole {
1.957     raeburn  8605:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8606:     my $now=time;
1.357     www      8607:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8608:            $deleteflag,$selfenroll,$context);
1.17      www      8609: }
                   8610: 
1.533     banghart 8611: # ------------------------------------------------------------ Disk usage
1.535     albertel 8612: sub diskusage {
1.955     raeburn  8613:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8614:     $directorypath =~ s/\/$//;
                   8615:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8616:                        .&escape($getpropath).':'.&escape($uname).':'
                   8617:                        .&escape($udom),homeserver($uname,$udom));
                   8618:     if ($listing eq 'unknown_cmd') {
                   8619:         if ($getpropath) {
                   8620:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8621:         }
                   8622:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8623:     }
1.514     albertel 8624:     return $listing;
1.512     banghart 8625: }
                   8626: 
1.566     banghart 8627: sub is_locked {
1.1096    raeburn  8628:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8629:     my @check;
                   8630:     my $is_locked;
1.1093    raeburn  8631:     push (@check,$file_name);
1.613     albertel 8632:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8633: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8634:     my ($tmp)=keys(%locked);
                   8635:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8636:     
1.566     banghart 8637:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8638:         $is_locked = 'false';
                   8639:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8640:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8641:                $is_locked = 'true';
1.1096    raeburn  8642:                if (ref($which) eq 'ARRAY') {
                   8643:                    push(@{$which},$entry);
                   8644:                } else {
                   8645:                    last;
                   8646:                }
1.745     raeburn  8647:            }
                   8648:        }
1.566     banghart 8649:     } else {
                   8650:         $is_locked = 'false';
                   8651:     }
1.1093    raeburn  8652:     return $is_locked;
1.566     banghart 8653: }
                   8654: 
1.759     albertel 8655: sub declutter_portfile {
                   8656:     my ($file) = @_;
1.833     albertel 8657:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8658:     return $file;
                   8659: }
                   8660: 
1.559     banghart 8661: # ------------------------------------------------------------- Mark as Read Only
                   8662: 
                   8663: sub mark_as_readonly {
                   8664:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8665:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8666:     my ($tmp)=keys(%current_permissions);
                   8667:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8668:     foreach my $file (@{$files}) {
1.759     albertel 8669: 	$file = &declutter_portfile($file);
1.561     banghart 8670:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8671:     }
1.613     albertel 8672:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8673:     return;
                   8674: }
                   8675: 
1.572     banghart 8676: # ------------------------------------------------------------Save Selected Files
                   8677: 
                   8678: sub save_selected_files {
                   8679:     my ($user, $path, @files) = @_;
                   8680:     my $filename = $user."savedfiles";
1.573     banghart 8681:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8682:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8683:     foreach my $file (@files) {
1.620     albertel 8684:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8685:     }
                   8686:     foreach my $file (@other_files) {
1.574     banghart 8687:         print (OUT $file."\n");
1.572     banghart 8688:     }
1.574     banghart 8689:     close (OUT);
1.572     banghart 8690:     return 'ok';
                   8691: }
                   8692: 
1.574     banghart 8693: sub clear_selected_files {
                   8694:     my ($user) = @_;
                   8695:     my $filename = $user."savedfiles";
1.1117    foxr     8696:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8697:     print (OUT undef);
                   8698:     close (OUT);
                   8699:     return ("ok");    
                   8700: }
                   8701: 
1.572     banghart 8702: sub files_in_path {
                   8703:     my ($user, $path) = @_;
                   8704:     my $filename = $user."savedfiles";
                   8705:     my %return_files;
1.1117    foxr     8706:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8707:     while (my $line_in = <IN>) {
1.574     banghart 8708:         chomp ($line_in);
                   8709:         my @paths_and_file = split (m!/!, $line_in);
                   8710:         my $file_part = pop (@paths_and_file);
                   8711:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8712:         $path_part.='/';
                   8713:         my $path_and_file = $path_part.$file_part;
                   8714:         if ($path_part eq $path) {
                   8715:             $return_files{$file_part}= 'selected';
                   8716:         }
                   8717:     }
1.574     banghart 8718:     close (IN);
                   8719:     return (\%return_files);
1.572     banghart 8720: }
                   8721: 
                   8722: # called in portfolio select mode, to show files selected NOT in current directory
                   8723: sub files_not_in_path {
                   8724:     my ($user, $path) = @_;
                   8725:     my $filename = $user."savedfiles";
                   8726:     my @return_files;
                   8727:     my $path_part;
1.1117    foxr     8728:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8729:     while (my $line = <IN>) {
1.572     banghart 8730:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8731:         my @paths_and_file = split(m|/|, $line);
                   8732:         my $file_part = pop(@paths_and_file);
                   8733:         chomp($file_part);
                   8734:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8735:         $path_part .= '/';
                   8736:         my $path_and_file = $path_part.$file_part;
                   8737:         if ($path_part ne $path) {
1.800     albertel 8738:             push(@return_files, ($path_and_file));
1.572     banghart 8739:         }
                   8740:     }
1.800     albertel 8741:     close(OUT);
1.574     banghart 8742:     return (@return_files);
1.572     banghart 8743: }
                   8744: 
1.745     raeburn  8745: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8746: 
1.745     raeburn  8747: sub get_portfile_permissions {
                   8748:     my ($domain,$user) = @_;
1.613     albertel 8749:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8750:     my ($tmp)=keys(%current_permissions);
                   8751:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8752:     return \%current_permissions;
                   8753: }
                   8754: 
                   8755: #---------------------------------------------Get portfolio file access controls
                   8756: 
1.749     raeburn  8757: sub get_access_controls {
1.745     raeburn  8758:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8759:     my %access;
                   8760:     my $real_file = $file;
                   8761:     $file =~ s/\.meta$//;
1.745     raeburn  8762:     if (defined($file)) {
1.749     raeburn  8763:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8764:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8765:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8766:             }
                   8767:         }
1.745     raeburn  8768:     } else {
1.749     raeburn  8769:         foreach my $key (keys(%{$current_permissions})) {
                   8770:             if ($key =~ /\0accesscontrol$/) {
                   8771:                 if (defined($group)) {
                   8772:                     if ($key !~ m-^\Q$group\E/-) {
                   8773:                         next;
                   8774:                     }
                   8775:                 }
                   8776:                 my ($fullpath) = split(/\0/,$key);
                   8777:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8778:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8779:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8780:                     }
                   8781:                 }
                   8782:             }
                   8783:         }
                   8784:     }
                   8785:     return %access;
                   8786: }
                   8787: 
                   8788: sub modify_access_controls {
                   8789:     my ($file_name,$changes,$domain,$user)=@_;
                   8790:     my ($outcome,$deloutcome);
                   8791:     my %store_permissions;
                   8792:     my %new_values;
                   8793:     my %new_control;
                   8794:     my %translation;
                   8795:     my @deletions = ();
                   8796:     my $now = time;
                   8797:     if (exists($$changes{'activate'})) {
                   8798:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8799:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8800:             my $numnew = scalar(@newitems);
                   8801:             for (my $i=0; $i<$numnew; $i++) {
                   8802:                 my $newkey = $newitems[$i];
                   8803:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8804:                 if ($newkey =~ /^\d+:/) { 
                   8805:                     $newkey =~ s/^(\d+)/$newid/;
                   8806:                     $translation{$1} = $newid;
                   8807:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8808:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8809:                     $translation{$1} = $newid;
                   8810:                 }
1.749     raeburn  8811:                 $new_values{$file_name."\0".$newkey} = 
                   8812:                                           $$changes{'activate'}{$newitems[$i]};
                   8813:                 $new_control{$newkey} = $now;
                   8814:             }
                   8815:         }
                   8816:     }
                   8817:     my %todelete;
                   8818:     my %changed_items;
                   8819:     foreach my $action ('delete','update') {
                   8820:         if (exists($$changes{$action})) {
                   8821:             if (ref($$changes{$action}) eq 'HASH') {
                   8822:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8823:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8824:                     if ($action eq 'delete') { 
                   8825:                         $todelete{$itemnum} = 1;
                   8826:                     } else {
                   8827:                         $changed_items{$itemnum} = $key;
                   8828:                     }
                   8829:                 }
1.745     raeburn  8830:             }
                   8831:         }
1.749     raeburn  8832:     }
                   8833:     # get lock on access controls for file.
                   8834:     my $lockhash = {
                   8835:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8836:                                                        ':'.$env{'user.domain'},
                   8837:                    }; 
                   8838:     my $tries = 0;
                   8839:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8840:    
                   8841:     while (($gotlock ne 'ok') && $tries <3) {
                   8842:         $tries ++;
                   8843:         sleep 1;
                   8844:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8845:     }
                   8846:     if ($gotlock eq 'ok') {
                   8847:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8848:         my ($tmp)=keys(%curr_permissions);
                   8849:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8850:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8851:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8852:             if (ref($curr_controls) eq 'HASH') {
                   8853:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8854:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8855:                     if (defined($todelete{$itemnum})) {
                   8856:                         push(@deletions,$file_name."\0".$control_item);
                   8857:                     } else {
                   8858:                         if (defined($changed_items{$itemnum})) {
                   8859:                             $new_control{$changed_items{$itemnum}} = $now;
                   8860:                             push(@deletions,$file_name."\0".$control_item);
                   8861:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8862:                         } else {
                   8863:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8864:                         }
                   8865:                     }
1.745     raeburn  8866:                 }
                   8867:             }
                   8868:         }
1.970     raeburn  8869:         my ($group);
                   8870:         if (&is_course($domain,$user)) {
                   8871:             ($group,my $file) = split(/\//,$file_name,2);
                   8872:         }
1.749     raeburn  8873:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8874:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8875:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8876:         #  remove lock
                   8877:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8878:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8879:         my $sqlresult =
1.970     raeburn  8880:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8881:                                     $group);
1.749     raeburn  8882:     } else {
                   8883:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8884:     }
1.749     raeburn  8885:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8886: }
                   8887: 
1.827     raeburn  8888: sub make_public_indefinitely {
                   8889:     my ($requrl) = @_;
                   8890:     my $now = time;
                   8891:     my $action = 'activate';
                   8892:     my $aclnum = 0;
                   8893:     if (&is_portfolio_url($requrl)) {
                   8894:         my (undef,$udom,$unum,$file_name,$group) =
                   8895:             &parse_portfolio_url($requrl);
                   8896:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8897:         my %access_controls = &get_access_controls($current_perms,
                   8898:                                                    $group,$file_name);
                   8899:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8900:             my ($num,$scope,$end,$start) = 
                   8901:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8902:             if ($scope eq 'public') {
                   8903:                 if ($start <= $now && $end == 0) {
                   8904:                     $action = 'none';
                   8905:                 } else {
                   8906:                     $action = 'update';
                   8907:                     $aclnum = $num;
                   8908:                 }
                   8909:                 last;
                   8910:             }
                   8911:         }
                   8912:         if ($action eq 'none') {
                   8913:              return 'ok';
                   8914:         } else {
                   8915:             my %changes;
                   8916:             my $newend = 0;
                   8917:             my $newstart = $now;
                   8918:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8919:             $changes{$action}{$newkey} = {
                   8920:                 type => 'public',
                   8921:                 time => {
                   8922:                     start => $newstart,
                   8923:                     end   => $newend,
                   8924:                 },
                   8925:             };
                   8926:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8927:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8928:             return $outcome;
                   8929:         }
                   8930:     } else {
                   8931:         return 'invalid';
                   8932:     }
                   8933: }
                   8934: 
1.745     raeburn  8935: #------------------------------------------------------Get Marked as Read Only
                   8936: 
                   8937: sub get_marked_as_readonly {
                   8938:     my ($domain,$user,$what,$group) = @_;
                   8939:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8940:     my @readonly_files;
1.629     banghart 8941:     my $cmp1=$what;
                   8942:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8943:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8944:         if (defined($group)) {
                   8945:             if ($file_name !~ m-^\Q$group\E/-) {
                   8946:                 next;
                   8947:             }
                   8948:         }
1.561     banghart 8949:         if (ref($value) eq "ARRAY"){
                   8950:             foreach my $stored_what (@{$value}) {
1.629     banghart 8951:                 my $cmp2=$stored_what;
1.759     albertel 8952:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8953:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8954:                 }
1.629     banghart 8955:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8956:                     push(@readonly_files, $file_name);
1.745     raeburn  8957:                     last;
1.563     banghart 8958:                 } elsif (!defined($what)) {
                   8959:                     push(@readonly_files, $file_name);
1.745     raeburn  8960:                     last;
1.561     banghart 8961:                 }
                   8962:             }
1.745     raeburn  8963:         }
1.561     banghart 8964:     }
                   8965:     return @readonly_files;
                   8966: }
1.577     banghart 8967: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8968: 
1.577     banghart 8969: sub get_marked_as_readonly_hash {
1.745     raeburn  8970:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8971:     my %readonly_files;
1.745     raeburn  8972:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8973:         if (defined($group)) {
                   8974:             if ($file_name !~ m-^\Q$group\E/-) {
                   8975:                 next;
                   8976:             }
                   8977:         }
1.577     banghart 8978:         if (ref($value) eq "ARRAY"){
                   8979:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8980:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8981:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8982:                         if ($lock_descriptor eq 'graded') {
                   8983:                             $readonly_files{$file_name} = 'graded';
                   8984:                         } elsif ($lock_descriptor eq 'handback') {
                   8985:                             $readonly_files{$file_name} = 'handback';
                   8986:                         } else {
                   8987:                             if (!exists($readonly_files{$file_name})) {
                   8988:                                 $readonly_files{$file_name} = 'locked';
                   8989:                             }
                   8990:                         }
1.745     raeburn  8991:                     }
1.750     banghart 8992:                 } 
1.577     banghart 8993:             }
                   8994:         } 
                   8995:     }
                   8996:     return %readonly_files;
                   8997: }
1.559     banghart 8998: # ------------------------------------------------------------ Unmark as Read Only
                   8999: 
                   9000: sub unmark_as_readonly {
1.629     banghart 9001:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9002:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9003:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9004:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9005:     my $symb_crs = $what;
                   9006:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9007:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9008:     my ($tmp)=keys(%current_permissions);
                   9009:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9010:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9011:     foreach my $file (@readonly_files) {
1.759     albertel 9012: 	my $clean_file = &declutter_portfile($file);
                   9013: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9014: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9015:         my @new_locks;
                   9016:         my @del_keys;
                   9017:         if (ref($current_locks) eq "ARRAY"){
                   9018:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9019:                 my $compare=$locker;
1.749     raeburn  9020:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9021:                     $compare=join('',@{$locker});
1.746     raeburn  9022:                     if ($compare ne $symb_crs) {
                   9023:                         push(@new_locks, $locker);
                   9024:                     }
1.563     banghart 9025:                 }
                   9026:             }
1.650     albertel 9027:             if (scalar(@new_locks) > 0) {
1.563     banghart 9028:                 $current_permissions{$file} = \@new_locks;
                   9029:             } else {
                   9030:                 push(@del_keys, $file);
1.613     albertel 9031:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9032:                 delete($current_permissions{$file});
1.563     banghart 9033:             }
                   9034:         }
1.561     banghart 9035:     }
1.613     albertel 9036:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9037:     return;
                   9038: }
1.512     banghart 9039: 
1.17      www      9040: # ------------------------------------------------------------ Directory lister
                   9041: 
                   9042: sub dirlist {
1.955     raeburn  9043:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9044:     $uri=~s/^\///;
                   9045:     $uri=~s/\/$//;
1.253     stredwic 9046:     my ($udom, $uname);
1.955     raeburn  9047:     if ($getuserdir) {
1.253     stredwic 9048:         $udom = $userdomain;
                   9049:         $uname = $username;
1.955     raeburn  9050:     } else {
                   9051:         (undef,$udom,$uname)=split(/\//,$uri);
                   9052:         if(defined($userdomain)) {
                   9053:             $udom = $userdomain;
                   9054:         }
                   9055:         if(defined($username)) {
                   9056:             $uname = $username;
                   9057:         }
1.253     stredwic 9058:     }
1.955     raeburn  9059:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9060: 
1.955     raeburn  9061:     $dirRoot = $perlvar{'lonDocRoot'};
                   9062:     if (defined($getpropath)) {
                   9063:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9064:         $dirRoot =~ s/\/$//;
1.955     raeburn  9065:     } elsif (defined($getuserdir)) {
                   9066:         my $subdir=$uname.'__';
                   9067:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9068:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9069:                    ."/$udom/$subdir/$uname";
                   9070:     } elsif (defined($alternateRoot)) {
                   9071:         $dirRoot = $alternateRoot;
1.751     banghart 9072:     }
1.253     stredwic 9073: 
                   9074:     if($udom) {
                   9075:         if($uname) {
1.1135    raeburn  9076:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9077:             if ($uhome eq 'no_host') {
                   9078:                 return ([],'no_host');
                   9079:             }
1.955     raeburn  9080:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9081:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9082:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9083:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9084:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9085:             } else {
                   9086:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9087:             }
1.605     matthew  9088:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9089:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9090:                 @listing_results = split(/:/,$listing);
                   9091:             } else {
                   9092:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9093:             }
1.1135    raeburn  9094:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9095:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9096:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9097:                 return ([],$listing);
                   9098:             } else {
                   9099:                 return (\@listing_results);
1.1135    raeburn  9100:             }
1.955     raeburn  9101:         } elsif(!$alternateRoot) {
1.1136    raeburn  9102:             my (%allusers,%listerror);
1.841     albertel 9103: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9104:  	    foreach my $tryserver (keys(%servers)) {
                   9105:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9106:                                   &escape($udom),$tryserver);
                   9107:                 if ($listing eq 'unknown_cmd') {
                   9108: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9109: 				      $udom, $tryserver);
                   9110:                 } else {
                   9111:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9112:                 }
1.841     albertel 9113: 		if ($listing eq 'unknown_cmd') {
                   9114: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9115: 				      $udom, $tryserver);
                   9116: 		    @listing_results = split(/:/,$listing);
                   9117: 		} else {
                   9118: 		    @listing_results =
                   9119: 			map { &unescape($_); } split(/:/,$listing);
                   9120: 		}
1.1136    raeburn  9121:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9122:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9123:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9124:                     $listerror{$tryserver} = $listing;
                   9125:                 } else {
1.841     albertel 9126: 		    foreach my $line (@listing_results) {
                   9127: 			my ($entry) = split(/&/,$line,2);
                   9128: 			$allusers{$entry} = 1;
                   9129: 		    }
                   9130: 		}
1.253     stredwic 9131:             }
1.1136    raeburn  9132:             my @alluserslist=();
1.800     albertel 9133:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9134:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9135:             }
1.1136    raeburn  9136:             return (\@alluserslist);
1.253     stredwic 9137:         } else {
1.1136    raeburn  9138:             return ([],'missing username');
1.253     stredwic 9139:         }
1.955     raeburn  9140:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9141:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9142:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9143:         return (\@all_domains);
1.955     raeburn  9144:     } else {
1.1136    raeburn  9145:         return ([],'missing domain');
1.275     stredwic 9146:     }
                   9147: }
                   9148: 
                   9149: # --------------------------------------------- GetFileTimestamp
                   9150: # This function utilizes dirlist and returns the date stamp for
                   9151: # when it was last modified.  It will also return an error of -1
                   9152: # if an error occurs
                   9153: 
                   9154: sub GetFileTimestamp {
1.955     raeburn  9155:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9156:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9157:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9158:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9159:                                     undef,$getuserdir);
                   9160:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9161:         return -1;
                   9162:     }
                   9163:     if (ref($fileref) eq 'ARRAY') {
                   9164:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9165:         # @stats contains first the filename, then the stat output
                   9166:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9167:     } else {
                   9168:         return -1;
1.253     stredwic 9169:     }
1.26      www      9170: }
                   9171: 
1.712     albertel 9172: sub stat_file {
                   9173:     my ($uri) = @_;
1.787     albertel 9174:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9175: 
1.955     raeburn  9176:     my ($udom,$uname,$file);
1.712     albertel 9177:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9178: 	($udom,$uname,$file) =
1.811     albertel 9179: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9180: 	$file = 'userfiles/'.$file;
                   9181:     }
                   9182:     if ($uri =~ m-^/res/-) {
                   9183: 	($udom,$uname) = 
1.807     albertel 9184: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9185: 	$file = $uri;
                   9186:     }
                   9187: 
                   9188:     if (!$udom || !$uname || !$file) {
                   9189: 	# unable to handle the uri
                   9190: 	return ();
                   9191:     }
1.956     raeburn  9192:     my $getpropath;
                   9193:     if ($file =~ /^userfiles\//) {
                   9194:         $getpropath = 1;
                   9195:     }
1.1136    raeburn  9196:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9197:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9198:         return ();
                   9199:     } else {
                   9200:         if (ref($listref) eq 'ARRAY') {
                   9201:             my @stats = split('&',$listref->[0]);
                   9202: 	    shift(@stats); #filename is first
                   9203: 	    return @stats;
                   9204:         }
1.712     albertel 9205:     }
                   9206:     return ();
                   9207: }
                   9208: 
1.26      www      9209: # -------------------------------------------------------- Value of a Condition
                   9210: 
1.713     albertel 9211: # gets the value of a specific preevaluated condition
                   9212: #    stored in the string  $env{user.state.<cid>}
                   9213: # or looks up a condition reference in the bighash and if if hasn't
                   9214: # already been evaluated recurses into docondval to get the value of
                   9215: # the condition, then memoizing it to 
                   9216: #   $env{user.state.<cid>.<condition>}
1.40      www      9217: sub directcondval {
                   9218:     my $number=shift;
1.620     albertel 9219:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9220: 	&Apache::lonuserstate::evalstate();
                   9221:     }
1.713     albertel 9222:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9223: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9224:     } elsif ($number =~ /^_/) {
                   9225: 	my $sub_condition;
                   9226: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9227: 		&GDBM_READER(),0640)) {
                   9228: 	    $sub_condition=$bighash{'conditions'.$number};
                   9229: 	    untie(%bighash);
                   9230: 	}
                   9231: 	my $value = &docondval($sub_condition);
1.949     raeburn  9232: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9233: 	return $value;
                   9234:     }
1.620     albertel 9235:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9236:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9237:     } else {
                   9238:        return 2;
                   9239:     }
                   9240: }
                   9241: 
1.713     albertel 9242: # get the collection of conditions for this resource
1.26      www      9243: sub condval {
                   9244:     my $condidx=shift;
1.54      www      9245:     my $allpathcond='';
1.713     albertel 9246:     foreach my $cond (split(/\|/,$condidx)) {
                   9247: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9248: 	    $allpathcond.=
                   9249: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9250: 	}
1.191     harris41 9251:     }
1.54      www      9252:     $allpathcond=~s/\|$//;
1.713     albertel 9253:     return &docondval($allpathcond);
                   9254: }
                   9255: 
                   9256: #evaluates an expression of conditions
                   9257: sub docondval {
                   9258:     my ($allpathcond) = @_;
                   9259:     my $result=0;
                   9260:     if ($env{'request.course.id'}
                   9261: 	&& defined($allpathcond)) {
                   9262: 	my $operand='|';
                   9263: 	my @stack;
                   9264: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9265: 	    if ($chunk eq '(') {
                   9266: 		push @stack,($operand,$result);
                   9267: 	    } elsif ($chunk eq ')') {
                   9268: 		my $before=pop @stack;
                   9269: 		if (pop @stack eq '&') {
                   9270: 		    $result=$result>$before?$before:$result;
                   9271: 		} else {
                   9272: 		    $result=$result>$before?$result:$before;
                   9273: 		}
                   9274: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9275: 		$operand=$chunk;
                   9276: 	    } else {
                   9277: 		my $new=directcondval($chunk);
                   9278: 		if ($operand eq '&') {
                   9279: 		    $result=$result>$new?$new:$result;
                   9280: 		} else {
                   9281: 		    $result=$result>$new?$result:$new;
                   9282: 		}
                   9283: 	    }
                   9284: 	}
1.26      www      9285:     }
                   9286:     return $result;
1.421     albertel 9287: }
                   9288: 
                   9289: # ---------------------------------------------------- Devalidate courseresdata
                   9290: 
                   9291: sub devalidatecourseresdata {
                   9292:     my ($coursenum,$coursedomain)=@_;
                   9293:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9294:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9295: }
                   9296: 
1.763     www      9297: 
1.200     www      9298: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9299: #
                   9300: #  Parameters:
                   9301: #      $coursenum    - Number of the course.
                   9302: #      $coursedomain - Domain at which the course was created.
                   9303: #  Returns:
                   9304: #     A hash of the course parameters along (I think) with timestamps
                   9305: #     and version info.
1.877     foxr     9306: 
1.624     albertel 9307: sub get_courseresdata {
                   9308:     my ($coursenum,$coursedomain)=@_;
1.200     www      9309:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9310:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9311:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9312:     my %dumpreply;
1.417     albertel 9313:     unless (defined($cached)) {
1.624     albertel 9314: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9315: 	$result=\%dumpreply;
1.251     albertel 9316: 	my ($tmp) = keys(%dumpreply);
                   9317: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9318: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9319: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9320: 	    return $tmp;
1.416     albertel 9321: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9322: 	    $result=undef;
1.599     albertel 9323: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9324: 	}
                   9325:     }
1.624     albertel 9326:     return $result;
                   9327: }
                   9328: 
1.633     albertel 9329: sub devalidateuserresdata {
                   9330:     my ($uname,$udom)=@_;
                   9331:     my $hashid="$udom:$uname";
                   9332:     &devalidate_cache_new('userres',$hashid);
                   9333: }
                   9334: 
1.624     albertel 9335: sub get_userresdata {
                   9336:     my ($uname,$udom)=@_;
                   9337:     #most student don\'t have any data set, check if there is some data
                   9338:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9339: 
                   9340:     my $hashid="$udom:$uname";
                   9341:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9342:     if (!defined($cached)) {
                   9343: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9344: 	$result=\%resourcedata;
                   9345: 	&do_cache_new('userres',$hashid,$result,600);
                   9346:     }
                   9347:     my ($tmp)=keys(%$result);
                   9348:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9349: 	return $result;
                   9350:     }
                   9351:     #error 2 occurs when the .db doesn't exist
                   9352:     if ($tmp!~/error: 2 /) {
1.672     albertel 9353: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9354: 		 " Trying to get resource data for ".
                   9355: 		 $uname." at ".$udom.": ".
                   9356: 		 $tmp."</font>");
                   9357:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9358: 	#&EXT_cache_set($udom,$uname);
                   9359: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9360: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9361:     }
                   9362:     return $tmp;
                   9363: }
1.879     foxr     9364: #----------------------------------------------- resdata - return resource data
                   9365: #  Purpose:
                   9366: #    Return resource data for either users or for a course.
                   9367: #  Parameters:
                   9368: #     $name      - Course/user name.
                   9369: #     $domain    - Name of the domain the user/course is registered on.
                   9370: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9371: #     @which     - Array of names of resources desired.
                   9372: #  Returns:
                   9373: #     The value of the first reasource in @which that is found in the
                   9374: #     resource hash.
                   9375: #  Exceptional Conditions:
                   9376: #     If the $type passed in is not valid (not the string 'course' or 
                   9377: #     'user', an undefined  reference is returned.
                   9378: #     If none of the resources are found, an undef is returned
1.624     albertel 9379: sub resdata {
                   9380:     my ($name,$domain,$type,@which)=@_;
                   9381:     my $result;
                   9382:     if ($type eq 'course') {
                   9383: 	$result=&get_courseresdata($name,$domain);
                   9384:     } elsif ($type eq 'user') {
                   9385: 	$result=&get_userresdata($name,$domain);
                   9386:     }
                   9387:     if (!ref($result)) { return $result; }    
1.251     albertel 9388:     foreach my $item (@which) {
1.927     albertel 9389: 	if (defined($result->{$item->[0]})) {
                   9390: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9391: 	}
1.250     albertel 9392:     }
1.291     albertel 9393:     return undef;
1.200     www      9394: }
                   9395: 
1.379     matthew  9396: #
                   9397: # EXT resource caching routines
                   9398: #
                   9399: 
                   9400: sub clear_EXT_cache_status {
1.383     albertel 9401:     &delenv('cache.EXT.');
1.379     matthew  9402: }
                   9403: 
                   9404: sub EXT_cache_status {
                   9405:     my ($target_domain,$target_user) = @_;
1.383     albertel 9406:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9407:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9408:         # We know already the user has no data
                   9409:         return 1;
                   9410:     } else {
                   9411:         return 0;
                   9412:     }
                   9413: }
                   9414: 
                   9415: sub EXT_cache_set {
                   9416:     my ($target_domain,$target_user) = @_;
1.383     albertel 9417:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9418:     #&appenv({$cachename => time});
1.379     matthew  9419: }
                   9420: 
1.28      www      9421: # --------------------------------------------------------- Value of a Variable
1.58      www      9422: sub EXT {
1.715     albertel 9423: 
1.395     albertel 9424:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9425:     unless ($varname) { return ''; }
1.218     albertel 9426:     #get real user name/domain, courseid and symb
                   9427:     my $courseid;
1.359     albertel 9428:     my $publicuser;
1.427     www      9429:     if ($symbparm) {
                   9430: 	$symbparm=&get_symb_from_alias($symbparm);
                   9431:     }
1.218     albertel 9432:     if (!($uname && $udom)) {
1.790     albertel 9433:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9434:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9435:     } else {
1.620     albertel 9436: 	$courseid=$env{'request.course.id'};
1.218     albertel 9437:     }
1.48      www      9438:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9439:     my $rest;
1.320     albertel 9440:     if (defined($therest[0])) {
1.48      www      9441:        $rest=join('.',@therest);
                   9442:     } else {
                   9443:        $rest='';
                   9444:     }
1.320     albertel 9445: 
1.57      www      9446:     my $qualifierrest=$qualifier;
                   9447:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9448:     my $spacequalifierrest=$space;
                   9449:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9450:     if ($realm eq 'user') {
1.48      www      9451: # --------------------------------------------------------------- user.resource
                   9452: 	if ($space eq 'resource') {
1.651     albertel 9453: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9454: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9455: 		 &&
1.744     albertel 9456: 		 ($symbparm eq &symbread()) ) {	
                   9457: 		# if we are in the middle of processing the resource the
                   9458: 		# get the value we are planning on committing
                   9459:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9460:                     return $Apache::lonhomework::results{$qualifierrest};
                   9461:                 } else {
                   9462:                     return $Apache::lonhomework::history{$qualifierrest};
                   9463:                 }
1.335     albertel 9464: 	    } else {
1.359     albertel 9465: 		my %restored;
1.620     albertel 9466: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9467: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9468: 		} else {
                   9469: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9470: 		}
1.335     albertel 9471: 		return $restored{$qualifierrest};
                   9472: 	    }
1.48      www      9473: # ----------------------------------------------------------------- user.access
                   9474:         } elsif ($space eq 'access') {
1.218     albertel 9475: 	    # FIXME - not supporting calls for a specific user
1.48      www      9476:             return &allowed($qualifier,$rest);
                   9477: # ------------------------------------------ user.preferences, user.environment
                   9478:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9479: 	    if (($uname eq $env{'user.name'}) &&
                   9480: 		($udom eq $env{'user.domain'})) {
                   9481: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9482: 	    } else {
1.359     albertel 9483: 		my %returnhash;
                   9484: 		if (!$publicuser) {
                   9485: 		    %returnhash=&userenvironment($udom,$uname,
                   9486: 						 $qualifierrest);
                   9487: 		}
1.218     albertel 9488: 		return $returnhash{$qualifierrest};
                   9489: 	    }
1.48      www      9490: # ----------------------------------------------------------------- user.course
                   9491:         } elsif ($space eq 'course') {
1.218     albertel 9492: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9493:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9494: # ------------------------------------------------------------------- user.role
                   9495:         } elsif ($space eq 'role') {
1.218     albertel 9496: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9497:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9498:             if ($qualifier eq 'value') {
                   9499: 		return $role;
                   9500:             } elsif ($qualifier eq 'extent') {
                   9501:                 return $where;
                   9502:             }
                   9503: # ----------------------------------------------------------------- user.domain
                   9504:         } elsif ($space eq 'domain') {
1.218     albertel 9505:             return $udom;
1.48      www      9506: # ------------------------------------------------------------------- user.name
                   9507:         } elsif ($space eq 'name') {
1.218     albertel 9508:             return $uname;
1.48      www      9509: # ---------------------------------------------------- Any other user namespace
1.29      www      9510:         } else {
1.359     albertel 9511: 	    my %reply;
                   9512: 	    if (!$publicuser) {
                   9513: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9514: 	    }
                   9515: 	    return $reply{$qualifierrest};
1.48      www      9516:         }
1.236     www      9517:     } elsif ($realm eq 'query') {
                   9518: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9519:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9520: 						[$spacequalifierrest]);
1.620     albertel 9521: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9522:    } elsif ($realm eq 'request') {
1.48      www      9523: # ------------------------------------------------------------- request.browser
                   9524:         if ($space eq 'browser') {
1.1145    bisitz   9525:             return $env{'browser.'.$qualifier};
1.57      www      9526: # ------------------------------------------------------------ request.filename
                   9527:         } else {
1.620     albertel 9528:             return $env{'request.'.$spacequalifierrest};
1.29      www      9529:         }
1.28      www      9530:     } elsif ($realm eq 'course') {
1.48      www      9531: # ---------------------------------------------------------- course.description
1.620     albertel 9532:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9533:     } elsif ($realm eq 'resource') {
1.165     www      9534: 
1.620     albertel 9535: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9536: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9537: 	}
1.693     albertel 9538: 
                   9539: 	if ($space eq 'title') {
                   9540: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9541: 	    return &gettitle($symbparm);
                   9542: 	}
                   9543: 	
                   9544: 	if ($space eq 'map') {
                   9545: 	    my ($map) = &decode_symb($symbparm);
                   9546: 	    return &symbread($map);
                   9547: 	}
1.905     albertel 9548: 	if ($space eq 'filename') {
                   9549: 	    if ($symbparm) {
                   9550: 		return &clutter((&decode_symb($symbparm))[2]);
                   9551: 	    }
                   9552: 	    return &hreflocation('',$env{'request.filename'});
                   9553: 	}
1.693     albertel 9554: 
                   9555: 	my ($section, $group, @groups);
1.593     albertel 9556: 	my ($courselevelm,$courselevel);
1.539     albertel 9557: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9558: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9559: 
1.218     albertel 9560: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9561: 
1.60      www      9562: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9563: 	    my $symbp=$symbparm;
1.735     albertel 9564: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9565: 
                   9566: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9567: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9568: 
1.620     albertel 9569: 	    if (($env{'user.name'} eq $uname) &&
                   9570: 		($env{'user.domain'} eq $udom)) {
                   9571: 		$section=$env{'request.course.sec'};
1.733     raeburn  9572:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9573:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9574: 	    } else {
1.539     albertel 9575: 		if (! defined($usection)) {
1.551     albertel 9576: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9577: 		} else {
                   9578: 		    $section = $usection;
                   9579: 		}
1.733     raeburn  9580:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9581: 	    }
                   9582: 
                   9583: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9584: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9585: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9586: 
1.593     albertel 9587: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9588: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9589: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9590: 
1.60      www      9591: # ----------------------------------------------------------- first, check user
1.624     albertel 9592: 
                   9593: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9594: 				       ([$courselevelr,'resource'],
                   9595: 					[$courselevelm,'map'     ],
                   9596: 					[$courselevel, 'course'  ]));
1.931     albertel 9597: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9598: 
1.594     albertel 9599: # ------------------------------------------------ second, check some of course
1.684     raeburn  9600:             my $coursereply;
1.691     raeburn  9601:             if (@groups > 0) {
                   9602:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9603:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9604:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9605:             }
1.96      www      9606: 
1.684     raeburn  9607: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9608: 				  $env{'course.'.$courseid.'.domain'},
                   9609: 				  'course',
                   9610: 				  ([$seclevelr,   'resource'],
                   9611: 				   [$seclevelm,   'map'     ],
                   9612: 				   [$seclevel,    'course'  ],
                   9613: 				   [$courselevelr,'resource']));
                   9614: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9615: 
1.60      www      9616: # ------------------------------------------------------ third, check map parms
1.218     albertel 9617: 	    my %parmhash=();
                   9618: 	    my $thisparm='';
                   9619: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9620: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9621: 		    &GDBM_READER(),0640)) {
1.218     albertel 9622: 		$thisparm=$parmhash{$symbparm};
                   9623: 		untie(%parmhash);
                   9624: 	    }
1.927     albertel 9625: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9626: 	}
1.594     albertel 9627: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9628: 
1.218     albertel 9629: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9630: 	my $filename;
                   9631: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9632: 	if ($symbparm) {
1.409     www      9633: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9634: 	} else {
1.620     albertel 9635: 	    $filename=$env{'request.filename'};
1.282     albertel 9636: 	}
                   9637: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9638: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9639: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9640: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9641: 
1.927     albertel 9642: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9643: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9644: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9645: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9646: 				     $env{'course.'.$courseid.'.domain'},
                   9647: 				     'course',
1.927     albertel 9648: 				     ([$courselevelm,'map'   ],
                   9649: 				      [$courselevel, 'course']));
                   9650: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9651: 	}
1.145     www      9652: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9653: 	unless ($space eq '0') {
1.336     albertel 9654: 	    my @parts=split(/_/,$space);
                   9655: 	    my $id=pop(@parts);
                   9656: 	    my $part=join('_',@parts);
                   9657: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9658: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9659: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9660: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9661: 	}
1.395     albertel 9662: 	if ($recurse) { return undef; }
                   9663: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9664: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9665: # ---------------------------------------------------- Any other user namespace
                   9666:     } elsif ($realm eq 'environment') {
                   9667: # ----------------------------------------------------------------- environment
1.620     albertel 9668: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9669: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9670: 	} else {
1.770     albertel 9671: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9672: 		return '';
                   9673: 	    }
1.219     albertel 9674: 	    my %returnhash=&userenvironment($udom,$uname,
                   9675: 					    $spacequalifierrest);
                   9676: 	    return $returnhash{$spacequalifierrest};
                   9677: 	}
1.28      www      9678:     } elsif ($realm eq 'system') {
1.48      www      9679: # ----------------------------------------------------------------- system.time
                   9680: 	if ($space eq 'time') {
                   9681: 	    return time;
                   9682:         }
1.696     albertel 9683:     } elsif ($realm eq 'server') {
                   9684: # ----------------------------------------------------------------- system.time
                   9685: 	if ($space eq 'name') {
                   9686: 	    return $ENV{'SERVER_NAME'};
                   9687:         }
1.28      www      9688:     }
1.48      www      9689:     return '';
1.61      www      9690: }
                   9691: 
1.927     albertel 9692: sub get_reply {
                   9693:     my ($reply_value) = @_;
1.940     raeburn  9694:     if (ref($reply_value) eq 'ARRAY') {
                   9695:         if (wantarray) {
                   9696: 	    return @$reply_value;
                   9697:         }
                   9698:         return $reply_value->[0];
                   9699:     } else {
                   9700:         return $reply_value;
1.927     albertel 9701:     }
                   9702: }
                   9703: 
1.691     raeburn  9704: sub check_group_parms {
                   9705:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9706:     my @groupitems = ();
                   9707:     my $resultitem;
1.927     albertel 9708:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9709:     foreach my $group (@{$groups}) {
                   9710:         foreach my $level (@levels) {
1.927     albertel 9711:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9712:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9713:         }
                   9714:     }
                   9715:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9716:                             $env{'course.'.$courseid.'.domain'},
                   9717:                                      'course',@groupitems);
                   9718:     return $coursereply;
                   9719: }
                   9720: 
                   9721: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9722:     my ($courseid,@groups) = @_;
                   9723:     @groups = sort(@groups);
1.691     raeburn  9724:     return @groups;
                   9725: }
                   9726: 
1.395     albertel 9727: sub packages_tab_default {
                   9728:     my ($uri,$varname)=@_;
                   9729:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9730: 
                   9731:     my (@extension,@specifics,$do_default);
                   9732:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9733: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9734: 	if ($pack_type eq 'default') {
                   9735: 	    $do_default=1;
                   9736: 	} elsif ($pack_type eq 'extension') {
                   9737: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9738: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9739: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9740: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9741: 	}
                   9742:     }
                   9743:     # first look for a package that matches the requested part id
                   9744:     foreach my $package (@specifics) {
                   9745: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9746: 	next if ($pack_part ne $part);
                   9747: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9748: 	    return $packagetab{"$pack_type&$name&default"};
                   9749: 	}
                   9750:     }
                   9751:     # look for any possible matching non extension_ package
                   9752:     foreach my $package (@specifics) {
                   9753: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9754: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9755: 	    return $packagetab{"$pack_type&$name&default"};
                   9756: 	}
1.585     albertel 9757: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9758: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9759: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9760: 	}
                   9761:     }
1.738     albertel 9762:     # look for any posible extension_ match
                   9763:     foreach my $package (@extension) {
                   9764: 	my ($package,$pack_type)=@{$package};
                   9765: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9766: 	    return $packagetab{"$pack_type&$name&default"};
                   9767: 	}
                   9768: 	if (defined($packagetab{$package."&$name&default"})) {
                   9769: 	    return $packagetab{$package."&$name&default"};
                   9770: 	}
                   9771:     }
                   9772:     # look for a global default setting
                   9773:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9774: 	return $packagetab{"default&$name&default"};
                   9775:     }
1.395     albertel 9776:     return undef;
                   9777: }
                   9778: 
1.334     albertel 9779: sub add_prefix_and_part {
                   9780:     my ($prefix,$part)=@_;
                   9781:     my $keyroot;
                   9782:     if (defined($prefix) && $prefix !~ /^__/) {
                   9783: 	# prefix that has a part already
                   9784: 	$keyroot=$prefix;
                   9785:     } elsif (defined($prefix)) {
                   9786: 	# prefix that is missing a part
                   9787: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9788:     } else {
                   9789: 	# no prefix at all
                   9790: 	if (defined($part)) { $keyroot='_'.$part; }
                   9791:     }
                   9792:     return $keyroot;
                   9793: }
                   9794: 
1.71      www      9795: # ---------------------------------------------------------------- Get metadata
                   9796: 
1.599     albertel 9797: my %metaentry;
1.1070    www      9798: my %importedpartids;
1.71      www      9799: sub metadata {
1.176     www      9800:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9801:     $uri=&declutter($uri);
1.288     albertel 9802:     # if it is a non metadata possible uri return quickly
1.529     albertel 9803:     if (($uri eq '') || 
                   9804: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9805: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9806:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9807: 	return undef;
                   9808:     }
1.1140    www      9809:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9810: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9811: 	return undef;
1.288     albertel 9812:     }
1.73      www      9813:     my $filename=$uri;
                   9814:     $uri=~s/\.meta$//;
1.172     www      9815: #
                   9816: # Is the metadata already cached?
1.177     www      9817: # Look at timestamp of caching
1.172     www      9818: # Everything is cached by the main uri, libraries are never directly cached
                   9819: #
1.428     albertel 9820:     if (!defined($liburi)) {
1.599     albertel 9821: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9822: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9823:     }
                   9824:     {
1.1069    www      9825: # Imported parts would go here
1.1070    www      9826:         my %importedids=();
                   9827:         my @origfileimportpartids=();
1.1069    www      9828:         my $importedparts=0;
1.172     www      9829: #
                   9830: # Is this a recursive call for a library?
                   9831: #
1.599     albertel 9832: #	if (! exists($metacache{$uri})) {
                   9833: #	    $metacache{$uri}={};
                   9834: #	}
1.924     albertel 9835: 	my $cachetime = 60*60;
1.171     www      9836:         if ($liburi) {
                   9837: 	    $liburi=&declutter($liburi);
                   9838:             $filename=$liburi;
1.401     bowersj2 9839:         } else {
1.599     albertel 9840: 	    &devalidate_cache_new('meta',$uri);
                   9841: 	    undef(%metaentry);
1.401     bowersj2 9842: 	}
1.140     www      9843:         my %metathesekeys=();
1.73      www      9844:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9845: 	my $metastring;
1.1140    www      9846: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9847: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9848: 	    $metastring = 
1.929     albertel 9849: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9850: 					  ('grade_target' => 'meta'));
                   9851: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9852: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9853:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9854: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9855: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9856: 	    $metastring=&getfile($file);
1.489     albertel 9857: 	}
1.208     albertel 9858:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9859:         my $token;
1.140     www      9860:         undef %metathesekeys;
1.71      www      9861:         while ($token=$parser->get_token) {
1.339     albertel 9862: 	    if ($token->[0] eq 'S') {
                   9863: 		if (defined($token->[2]->{'package'})) {
1.172     www      9864: #
                   9865: # This is a package - get package info
                   9866: #
1.339     albertel 9867: 		    my $package=$token->[2]->{'package'};
                   9868: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9869: 		    if (defined($token->[2]->{'id'})) { 
                   9870: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9871: 		    }
1.599     albertel 9872: 		    if ($metaentry{':packages'}) {
                   9873: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9874: 		    } else {
1.599     albertel 9875: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9876: 		    }
1.736     albertel 9877: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9878: 			my $part=$keyroot;
                   9879: 			$part=~s/^\_//;
1.736     albertel 9880: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9881: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9882: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9883: 			    # ignore package.tab specified default values
                   9884:                             # here &package_tab_default() will fetch those
                   9885: 			    if ($subp eq 'default') { next; }
1.736     albertel 9886: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9887: 			    my $unikey;
                   9888: 			    if ($pack =~ /_0$/) {
                   9889: 				$unikey='parameter_0_'.$name;
                   9890: 				$part=0;
                   9891: 			    } else {
                   9892: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9893: 			    }
1.339     albertel 9894: 			    if ($subp eq 'display') {
                   9895: 				$value.=' [Part: '.$part.']';
                   9896: 			    }
1.599     albertel 9897: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9898: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9899: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9900: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9901: 			    }
1.599     albertel 9902: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9903: 				$metaentry{':'.$unikey}=
                   9904: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9905: 			    }
1.339     albertel 9906: 			}
                   9907: 		    }
                   9908: 		} else {
1.172     www      9909: #
                   9910: # This is not a package - some other kind of start tag
1.339     albertel 9911: #
                   9912: 		    my $entry=$token->[1];
1.1068    www      9913: 		    my $unikey='';
1.175     www      9914: 
1.339     albertel 9915: 		    if ($entry eq 'import') {
1.175     www      9916: #
                   9917: # Importing a library here
1.339     albertel 9918: #
1.1067    www      9919:                         my $location=$parser->get_text('/import');
                   9920:                         my $dir=$filename;
                   9921:                         $dir=~s|[^/]*$||;
                   9922:                         $location=&filelocation($dir,$location);
1.1069    www      9923:                        
1.1068    www      9924:                         my $importmode=$token->[2]->{'importmode'};
                   9925:                         if ($importmode eq 'problem') {
1.1069    www      9926: # Import as problem/response
1.1068    www      9927:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9928:                         } elsif ($importmode eq 'part') {
                   9929: # Import as part(s)
1.1069    www      9930:                            $importedparts=1;
                   9931: # We need to get the original file and the imported file to get the part order correct
                   9932: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9933: # Load and inspect original file
1.1070    www      9934:                            if ($#origfileimportpartids<0) {
                   9935:                               undef(%importedpartids);
                   9936:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9937:                               my $origfile=&getfile($origfilelocation);
                   9938:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9939:                            }
                   9940: 
1.1069    www      9941: # Load and inspect imported file
                   9942:                            my $impfile=&getfile($location);
                   9943:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9944:                            if ($#impfilepartids>=0) {
                   9945: # This problem had parts
1.1070    www      9946:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9947:                            } else {
                   9948: # Importing by turning a single problem into a problem part
                   9949: # It gets the import-tags ID as part-ID
                   9950:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9951:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9952:                            }
1.1068    www      9953:                         } else {
                   9954: # Normal import
                   9955:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9956:                            if (defined($token->[2]->{'id'})) {
                   9957:                               $unikey.='_'.$token->[2]->{'id'};
                   9958:                            }
1.1067    www      9959:                         }
                   9960: 
1.339     albertel 9961: 			if ($depthcount<20) {
1.736     albertel 9962: 			    my $metadata = 
                   9963: 				&metadata($uri,'keys', $location,$unikey,
                   9964: 					  $depthcount+1);
                   9965: 			    foreach my $meta (split(',',$metadata)) {
                   9966: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9967: 				$metathesekeys{$meta}=1;
1.339     albertel 9968: 			    }
1.1068    www      9969: 			
                   9970:                         }
1.1067    www      9971: 		    } else {
                   9972: #
                   9973: # Not importing, some other kind of non-package, non-library start tag
                   9974: # 
                   9975:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9976:                         if (defined($token->[2]->{'id'})) {
                   9977:                             $unikey.='_'.$token->[2]->{'id'};
                   9978:                         }
1.339     albertel 9979: 			if (defined($token->[2]->{'name'})) { 
                   9980: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9981: 			}
                   9982: 			$metathesekeys{$unikey}=1;
1.736     albertel 9983: 			foreach my $param (@{$token->[3]}) {
                   9984: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9985: 				$token->[2]->{$param};
1.339     albertel 9986: 			}
                   9987: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9988: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9989: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9990: 		 # only ws inside the tag, and not in default, so use default
                   9991: 		 # as value
1.599     albertel 9992: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9993: 			} elsif ( $internaltext =~ /\S/ ) {
                   9994: 		  # something interesting inside the tag
                   9995: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9996: 			} else {
1.908     albertel 9997: 		  # no interesting values, don't set a default
1.339     albertel 9998: 			}
1.172     www      9999: # end of not-a-package not-a-library import
1.339     albertel 10000: 		    }
1.172     www      10001: # end of not-a-package start tag
1.339     albertel 10002: 		}
1.172     www      10003: # the next is the end of "start tag"
1.339     albertel 10004: 	    }
                   10005: 	}
1.483     albertel 10006: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10007: 	$extension = lc($extension);
                   10008: 	if ($extension eq 'htm') { $extension='html'; }
                   10009: 
1.737     albertel 10010: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10011: 	    #no specific packages #how's our extension
                   10012: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10013: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10014: 					 \%metathesekeys);
                   10015: 	}
1.883     albertel 10016: 
                   10017: 	if (!exists($metaentry{':packages'})
                   10018: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10019: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10020: 		#no specific packages well let's get default then
                   10021: 		if ($key!~/^default&/) { next; }
1.488     albertel 10022: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10023: 					     \%metathesekeys);
                   10024: 	    }
                   10025: 	}
1.338     www      10026: # are there custom rights to evaluate
1.599     albertel 10027: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10028: 
1.338     www      10029:     #
                   10030:     # Importing a rights file here
1.339     albertel 10031:     #
                   10032: 	    unless ($depthcount) {
1.599     albertel 10033: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10034: 		my $dir=$filename;
                   10035: 		$dir=~s|[^/]*$||;
                   10036: 		$location=&filelocation($dir,$location);
1.736     albertel 10037: 		my $rights_metadata =
                   10038: 		    &metadata($uri,'keys',$location,'_rights',
                   10039: 			      $depthcount+1);
                   10040: 		foreach my $rights (split(',',$rights_metadata)) {
                   10041: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10042: 		    $metathesekeys{$rights}=1;
1.339     albertel 10043: 		}
                   10044: 	    }
                   10045: 	}
1.737     albertel 10046: 	# uniqifiy package listing
                   10047: 	my %seen;
                   10048: 	my @uniq_packages =
                   10049: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10050: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10051: 
1.1070    www      10052:         if ($importedparts) {
                   10053: # We had imported parts and need to rebuild partorder
                   10054:            $metaentry{':partorder'}='';
                   10055:            $metathesekeys{'partorder'}=1;
                   10056:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10057:                if ($origfileimportpartids[$index] eq 'part') {
                   10058: # original part, part of the problem
                   10059:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10060:                } else {
                   10061: # we have imported parts at this position
                   10062:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10063:                }
                   10064:            }
                   10065:            $metaentry{':partorder'}=~s/^\,//;
                   10066:         }
                   10067: 
1.737     albertel 10068: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10069: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10070: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10071: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10072: # this is the end of "was not already recently cached
1.71      www      10073:     }
1.599     albertel 10074:     return $metaentry{':'.$what};
1.261     albertel 10075: }
                   10076: 
1.488     albertel 10077: sub metadata_create_package_def {
1.483     albertel 10078:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10079:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10080:     if ($subp eq 'default') { next; }
                   10081:     
1.599     albertel 10082:     if (defined($metaentry{':packages'})) {
                   10083: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10084:     } else {
1.599     albertel 10085: 	$metaentry{':packages'}=$package;
1.483     albertel 10086:     }
                   10087:     my $value=$packagetab{$key};
                   10088:     my $unikey;
                   10089:     $unikey='parameter_0_'.$name;
1.599     albertel 10090:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10091:     $$metathesekeys{$unikey}=1;
1.599     albertel 10092:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10093: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10094:     }
1.599     albertel 10095:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10096: 	$metaentry{':'.$unikey}=
                   10097: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10098:     }
                   10099: }
                   10100: 
1.261     albertel 10101: sub metadata_generate_part0 {
                   10102:     my ($metadata,$metacache,$uri) = @_;
                   10103:     my %allnames;
1.737     albertel 10104:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10105: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10106: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10107: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10108: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10109: 	    $allnames{$name}=$part;
                   10110: 	  }
                   10111: 	}
                   10112:     }
                   10113:     foreach my $name (keys(%allnames)) {
                   10114:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10115:       my $key=":parameter_0_$name";
1.261     albertel 10116:       $$metacache{"$key.part"}='0';
                   10117:       $$metacache{"$key.name"}=$name;
1.428     albertel 10118:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10119: 					   $allnames{$name}.'_'.$name.
                   10120: 					   '.type'};
1.428     albertel 10121:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10122: 			     '.display'};
1.644     www      10123:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10124:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10125:       $$metacache{"$key.display"}=$olddis;
                   10126:     }
1.71      www      10127: }
                   10128: 
1.764     albertel 10129: # ------------------------------------------------------ Devalidate title cache
                   10130: 
                   10131: sub devalidate_title_cache {
                   10132:     my ($url)=@_;
                   10133:     if (!$env{'request.course.id'}) { return; }
                   10134:     my $symb=&symbread($url);
                   10135:     if (!$symb) { return; }
                   10136:     my $key=$env{'request.course.id'}."\0".$symb;
                   10137:     &devalidate_cache_new('title',$key);
                   10138: }
                   10139: 
1.1014    droeschl 10140: # ------------------------------------------------- Get the title of a course
                   10141: 
                   10142: sub current_course_title {
                   10143:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10144: }
1.301     www      10145: # ------------------------------------------------- Get the title of a resource
                   10146: 
                   10147: sub gettitle {
                   10148:     my $urlsymb=shift;
                   10149:     my $symb=&symbread($urlsymb);
1.534     albertel 10150:     if ($symb) {
1.620     albertel 10151: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10152: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10153: 	if (defined($cached)) { 
                   10154: 	    return $result;
                   10155: 	}
1.534     albertel 10156: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10157: 	my $title='';
1.907     albertel 10158: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10159: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10160: 	} else {
                   10161: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10162: 		    &GDBM_READER(),0640)) {
                   10163: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10164: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10165: 		untie(%bighash);
                   10166: 	    }
1.534     albertel 10167: 	}
                   10168: 	$title=~s/\&colon\;/\:/gs;
                   10169: 	if ($title) {
1.1159    www      10170: # Remember both $symb and $title for dynamic metadata
                   10171:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10172:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10173: # Cache this title and then return it
1.599     albertel 10174: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10175: 	}
                   10176: 	$urlsymb=$url;
                   10177:     }
                   10178:     my $title=&metadata($urlsymb,'title');
                   10179:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10180:     return $title;
1.301     www      10181: }
1.613     albertel 10182: 
1.614     albertel 10183: sub get_slot {
                   10184:     my ($which,$cnum,$cdom)=@_;
                   10185:     if (!$cnum || !$cdom) {
1.790     albertel 10186: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10187: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10188: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10189:     }
1.703     albertel 10190:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10191:     my %slotinfo;
                   10192:     if (exists($remembered{$key})) {
                   10193: 	$slotinfo{$which} = $remembered{$key};
                   10194:     } else {
                   10195: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10196: 	&Apache::lonhomework::showhash(%slotinfo);
                   10197: 	my ($tmp)=keys(%slotinfo);
                   10198: 	if ($tmp=~/^error:/) { return (); }
                   10199: 	$remembered{$key} = $slotinfo{$which};
                   10200:     }
1.616     albertel 10201:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10202: 	return %{$slotinfo{$which}};
                   10203:     }
                   10204:     return $slotinfo{$which};
1.614     albertel 10205: }
1.1150    raeburn  10206: 
                   10207: sub get_reservable_slots {
                   10208:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10209:     my $now = time;
                   10210:     my $reservable_info;
                   10211:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10212:     if (exists($remembered{$key})) {
                   10213:         $reservable_info = $remembered{$key};
                   10214:     } else {
                   10215:         my %resv;
                   10216:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10217:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10218:         $reservable_info = \%resv;
                   10219:         $remembered{$key} = $reservable_info;
                   10220:     }
                   10221:     return $reservable_info;
                   10222: }
                   10223: 
                   10224: sub get_course_slots {
                   10225:     my ($cnum,$cdom) = @_;
                   10226:     my $hashid=$cnum.':'.$cdom;
                   10227:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10228:     if (defined($cached)) {
                   10229:         if (ref($result) eq 'HASH') {
                   10230:             return %{$result};
                   10231:         }
                   10232:     } else {
                   10233:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10234:         my ($tmp) = keys(%slots);
                   10235:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10236:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10237:             return %slots;
                   10238:         }
                   10239:     }
                   10240:     return;
                   10241: }
                   10242: 
                   10243: sub devalidate_slots_cache {
                   10244:     my ($cnum,$cdom)=@_;
                   10245:     my $hashid=$cnum.':'.$cdom;
                   10246:     &devalidate_cache_new('allslots',$hashid);
                   10247: }
                   10248: 
1.1181    raeburn  10249: sub get_coursechange {
                   10250:     my ($cdom,$cnum) = @_;
                   10251:     if ($cdom eq '' || $cnum eq '') {
                   10252:         return unless ($env{'request.course.id'});
                   10253:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10254:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10255:     }
                   10256:     my $hashid=$cdom.'_'.$cnum;
                   10257:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10258:     if ((defined($cached)) && ($change ne '')) {
                   10259:         return $change;
                   10260:     } else {
                   10261:         my %crshash;
                   10262:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10263:         if ($crshash{'internal.contentchange'} eq '') {
                   10264:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10265:             if ($change eq '') {
                   10266:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10267:                 $change = $crshash{'internal.created'};
                   10268:             }
                   10269:         } else {
                   10270:             $change = $crshash{'internal.contentchange'};
                   10271:         }
                   10272:         my $cachetime = 600;
                   10273:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10274:     }
                   10275:     return $change;
                   10276: }
                   10277: 
                   10278: sub devalidate_coursechange_cache {
                   10279:     my ($cnum,$cdom)=@_;
                   10280:     my $hashid=$cnum.':'.$cdom;
                   10281:     &devalidate_cache_new('crschange',$hashid);
                   10282: }
                   10283: 
1.31      www      10284: # ------------------------------------------------- Update symbolic store links
                   10285: 
                   10286: sub symblist {
                   10287:     my ($mapname,%newhash)=@_;
1.438     www      10288:     $mapname=&deversion(&declutter($mapname));
1.31      www      10289:     my %hash;
1.620     albertel 10290:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10291:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10292:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10293: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10294: 		next if ($url eq 'last_known'
                   10295: 			 && $env{'form.no_update_last_known'});
                   10296: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10297: 						    $newhash{$url}->[1],
                   10298: 						    $newhash{$url}->[0]);
1.191     harris41 10299:             }
1.31      www      10300:             if (untie(%hash)) {
                   10301: 		return 'ok';
                   10302:             }
                   10303:         }
                   10304:     }
                   10305:     return 'error';
1.212     www      10306: }
                   10307: 
                   10308: # --------------------------------------------------------------- Verify a symb
                   10309: 
                   10310: sub symbverify {
1.1190    raeburn  10311:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10312:     my $thisfn=$thisurl;
1.439     www      10313:     $thisfn=&declutter($thisfn);
1.215     www      10314: # direct jump to resource in page or to a sequence - will construct own symbs
                   10315:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10316: # check URL part
1.409     www      10317:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10318: 
1.431     www      10319:     unless ($url eq $thisfn) { return 0; }
1.213     www      10320: 
1.216     www      10321:     $symb=&symbclean($symb);
1.510     www      10322:     $thisurl=&deversion($thisurl);
1.439     www      10323:     $thisfn=&deversion($thisfn);
1.213     www      10324: 
                   10325:     my %bighash;
                   10326:     my $okay=0;
1.431     www      10327: 
1.620     albertel 10328:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10329:                             &GDBM_READER(),0640)) {
1.1032    raeburn  10330:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10331:             $thisurl =~ s/\?.+$//;
                   10332:         }
1.510     www      10333:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  10334:         unless ($ids) {
                   10335:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10336:             $ids=$bighash{$idkey};
1.216     www      10337:         }
                   10338:         if ($ids) {
                   10339: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 10340: 	    foreach my $id (split(/\,/,$ids)) {
                   10341: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  10342:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10343:                    $symb =~ s/\?.+$//;
                   10344:                }
1.216     www      10345:                if (
                   10346:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10347:    eq $symb) {
                   10348:                    if (ref($encstate)) {
                   10349:                        $$encstate = $bighash{'encrypted_'.$id};
                   10350:                    }
1.620     albertel 10351: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10352: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10353:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10354: 		       $okay=1;
1.582     albertel 10355: 		   }
                   10356: 	       }
1.216     www      10357: 	   }
                   10358:         }
1.213     www      10359: 	untie(%bighash);
                   10360:     }
                   10361:     return $okay;
1.31      www      10362: }
                   10363: 
1.210     www      10364: # --------------------------------------------------------------- Clean-up symb
                   10365: 
                   10366: sub symbclean {
                   10367:     my $symb=shift;
1.568     albertel 10368:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10369: # remove version from map
                   10370:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10371: 
1.210     www      10372: # remove version from URL
                   10373:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10374: 
1.507     www      10375: # remove wrapper
                   10376: 
1.510     www      10377:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10378:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10379:     return $symb;
1.409     www      10380: }
                   10381: 
                   10382: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10383: 
                   10384: sub encode_symb {
                   10385:     my ($map,$resid,$url)=@_;
                   10386:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10387: }
1.409     www      10388: 
                   10389: sub decode_symb {
1.568     albertel 10390:     my $symb=shift;
                   10391:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10392:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10393:     return (&fixversion($map),$resid,&fixversion($url));
                   10394: }
                   10395: 
                   10396: sub fixversion {
                   10397:     my $fn=shift;
1.609     banghart 10398:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10399:     my %bighash;
                   10400:     my $uri=&clutter($fn);
1.620     albertel 10401:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10402: # is this cached?
1.599     albertel 10403:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10404:     if (defined($cached)) { return $result; }
                   10405: # unfortunately not cached, or expired
1.620     albertel 10406:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10407: 	    &GDBM_READER(),0640)) {
                   10408:  	if ($bighash{'version_'.$uri}) {
                   10409:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10410:  	    unless (($version eq 'mostrecent') || 
                   10411: 		    ($version==&getversion($uri))) {
1.440     www      10412:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10413:  	    }
                   10414:  	}
                   10415:  	untie %bighash;
1.413     www      10416:     }
1.599     albertel 10417:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10418: }
                   10419: 
                   10420: sub deversion {
                   10421:     my $url=shift;
                   10422:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10423:     return $url;
1.210     www      10424: }
                   10425: 
1.31      www      10426: # ------------------------------------------------------ Return symb list entry
                   10427: 
                   10428: sub symbread {
1.249     www      10429:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 10430:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1179    raeburn  10431:     if (defined($env{$cache_str})) {
                   10432:         if (($thisfn) || ($env{$cache_str} ne '')) {
                   10433:             return $env{$cache_str};
                   10434:         }
                   10435:     }
1.242     www      10436: # no filename provided? try from environment
1.44      www      10437:     unless ($thisfn) {
1.620     albertel 10438:         if ($env{'request.symb'}) {
                   10439: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10440: 	}
1.620     albertel 10441: 	$thisfn=$env{'request.filename'};
1.44      www      10442:     }
1.569     albertel 10443:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10444: # is that filename actually a symb? Verify, clean, and return
                   10445:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10446: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10447: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10448: 	}
1.242     www      10449:     }
1.44      www      10450:     $thisfn=declutter($thisfn);
1.31      www      10451:     my %hash;
1.37      www      10452:     my %bighash;
                   10453:     my $syval='';
1.620     albertel 10454:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10455:         my $targetfn = $thisfn;
1.609     banghart 10456:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10457:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10458:         }
1.687     albertel 10459: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10460: 	    $targetfn=$1;
                   10461: 	}
1.620     albertel 10462:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10463:                       &GDBM_READER(),0640)) {
1.481     raeburn  10464: 	    $syval=$hash{$targetfn};
1.37      www      10465:             untie(%hash);
                   10466:         }
                   10467: # ---------------------------------------------------------- There was an entry
                   10468:         if ($syval) {
1.601     albertel 10469: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10470: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10471: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10472: 		    #return $env{$cache_str}='';
1.601     albertel 10473: 		#}    
                   10474: 		#$syval.=$1;
                   10475: 	    #}
1.37      www      10476:         } else {
                   10477: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10478:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10479:                             &GDBM_READER(),0640)) {
1.37      www      10480: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10481:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10482:               unless ($ids) { 
                   10483:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10484:               }
                   10485:               unless ($ids) {
                   10486: # alias?
                   10487: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10488:               }
1.37      www      10489:               if ($ids) {
                   10490: # ------------------------------------------------------------------- Has ID(s)
                   10491:                  my @possibilities=split(/\,/,$ids);
1.39      www      10492:                  if ($#possibilities==0) {
                   10493: # ----------------------------------------------- There is only one possibility
1.37      www      10494: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10495: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10496: 						    $resid,$thisfn);
1.249     www      10497:                  } elsif (!$donotrecurse) {
1.39      www      10498: # ------------------------------------------ There is more than one possibility
                   10499:                      my $realpossible=0;
1.800     albertel 10500:                      foreach my $id (@possibilities) {
                   10501: 			 my $file=$bighash{'src_'.$id};
1.39      www      10502:                          if (&allowed('bre',$file)) {
1.800     albertel 10503:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10504:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10505: 				$realpossible++;
1.626     albertel 10506:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10507: 						    $resid,$thisfn);
1.39      www      10508:                             }
                   10509: 			 }
1.191     harris41 10510:                      }
1.39      www      10511: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10512:                  } else {
                   10513:                      $syval='';
1.37      www      10514:                  }
                   10515: 	      }
                   10516:               untie(%bighash)
1.481     raeburn  10517:            }
1.31      www      10518:         }
1.62      www      10519:         if ($syval) {
1.620     albertel 10520: 	    return $env{$cache_str}=$syval;
1.62      www      10521:         }
1.31      www      10522:     }
1.949     raeburn  10523:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10524:     return $env{$cache_str}='';
1.31      www      10525: }
                   10526: 
                   10527: # ---------------------------------------------------------- Return random seed
                   10528: 
1.32      www      10529: sub numval {
                   10530:     my $txt=shift;
                   10531:     $txt=~tr/A-J/0-9/;
                   10532:     $txt=~tr/a-j/0-9/;
                   10533:     $txt=~tr/K-T/0-9/;
                   10534:     $txt=~tr/k-t/0-9/;
                   10535:     $txt=~tr/U-Z/0-5/;
                   10536:     $txt=~tr/u-z/0-5/;
                   10537:     $txt=~s/\D//g;
1.564     albertel 10538:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10539:     return int($txt);
1.368     albertel 10540: }
                   10541: 
1.484     albertel 10542: sub numval2 {
                   10543:     my $txt=shift;
                   10544:     $txt=~tr/A-J/0-9/;
                   10545:     $txt=~tr/a-j/0-9/;
                   10546:     $txt=~tr/K-T/0-9/;
                   10547:     $txt=~tr/k-t/0-9/;
                   10548:     $txt=~tr/U-Z/0-5/;
                   10549:     $txt=~tr/u-z/0-5/;
                   10550:     $txt=~s/\D//g;
                   10551:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10552:     my $total;
                   10553:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10554:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10555:     return int($total);
                   10556: }
                   10557: 
1.575     albertel 10558: sub numval3 {
                   10559:     use integer;
                   10560:     my $txt=shift;
                   10561:     $txt=~tr/A-J/0-9/;
                   10562:     $txt=~tr/a-j/0-9/;
                   10563:     $txt=~tr/K-T/0-9/;
                   10564:     $txt=~tr/k-t/0-9/;
                   10565:     $txt=~tr/U-Z/0-5/;
                   10566:     $txt=~tr/u-z/0-5/;
                   10567:     $txt=~s/\D//g;
                   10568:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10569:     my $total;
                   10570:     foreach my $val (@txts) { $total+=$val; }
                   10571:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10572:     return $total;
                   10573: }
                   10574: 
1.675     albertel 10575: sub digest {
                   10576:     my ($data)=@_;
                   10577:     my $digest=&Digest::MD5::md5($data);
                   10578:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10579:     my ($e,$f);
                   10580:     {
                   10581:         use integer;
                   10582:         $e=($a+$b);
                   10583:         $f=($c+$d);
                   10584:         if ($_64bit) {
                   10585:             $e=(($e<<32)>>32);
                   10586:             $f=(($f<<32)>>32);
                   10587:         }
                   10588:     }
                   10589:     if (wantarray) {
                   10590: 	return ($e,$f);
                   10591:     } else {
                   10592: 	my $g;
                   10593: 	{
                   10594: 	    use integer;
                   10595: 	    $g=($e+$f);
                   10596: 	    if ($_64bit) {
                   10597: 		$g=(($g<<32)>>32);
                   10598: 	    }
                   10599: 	}
                   10600: 	return $g;
                   10601:     }
                   10602: }
                   10603: 
1.368     albertel 10604: sub latest_rnd_algorithm_id {
1.675     albertel 10605:     return '64bit5';
1.366     albertel 10606: }
1.32      www      10607: 
1.503     albertel 10608: sub get_rand_alg {
                   10609:     my ($courseid)=@_;
1.790     albertel 10610:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10611:     if ($courseid) {
1.620     albertel 10612: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10613:     }
                   10614:     return &latest_rnd_algorithm_id();
                   10615: }
                   10616: 
1.562     albertel 10617: sub validCODE {
                   10618:     my ($CODE)=@_;
                   10619:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10620:     return 0;
                   10621: }
                   10622: 
1.491     albertel 10623: sub getCODE {
1.620     albertel 10624:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10625:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10626: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10627: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10628: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10629:     }
                   10630:     return undef;
                   10631: }
1.1133    foxr     10632: #
                   10633: #  Determines the random seed for a specific context:
                   10634: #
                   10635: # parameters:
                   10636: #   symb      - in course context the symb for the seed.
                   10637: #   course_id - The course id of the form domain_coursenum.
                   10638: #   domain    - Domain for the user.
                   10639: #   course    - Course for the user.
                   10640: #   cenv      - environment of the course.
                   10641: #
                   10642: # NOTE:
                   10643: #   All parameters are picked out of the environment if missing
                   10644: #   or not defined.
                   10645: #   If a symb cannot be determined the current time is used instead.
                   10646: #
                   10647: #  For a given well defined symb, courside, domain, username,
                   10648: #  and course environment, the seed is reproducible.
                   10649: #
1.31      www      10650: sub rndseed {
1.1133    foxr     10651:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10652:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10653:     if (!defined($symb)) {
1.366     albertel 10654: 	unless ($symb=$wsymb) { return time; }
                   10655:     }
1.1146    foxr     10656:     if (!defined $courseid) { 
                   10657: 	$courseid=$wcourseid; 
                   10658:     }
                   10659:     if (!defined $domain) { $domain=$wdomain; }
                   10660:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10661: 
                   10662:     my $which;
                   10663:     if (defined($cenv->{'rndseed'})) {
                   10664: 	$which = $cenv->{'rndseed'};
                   10665:     } else {
                   10666: 	$which =&get_rand_alg($courseid);
                   10667:     }
1.491     albertel 10668:     if (defined(&getCODE())) {
1.1133    foxr     10669: 
1.675     albertel 10670: 	if ($which eq '64bit5') {
                   10671: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10672: 	} elsif ($which eq '64bit4') {
1.575     albertel 10673: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10674: 	} else {
                   10675: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10676: 	}
1.675     albertel 10677:     } elsif ($which eq '64bit5') {
                   10678: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10679:     } elsif ($which eq '64bit4') {
                   10680: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10681:     } elsif ($which eq '64bit3') {
                   10682: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10683:     } elsif ($which eq '64bit2') {
                   10684: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10685:     } elsif ($which eq '64bit') {
                   10686: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10687:     }
                   10688:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10689: }
                   10690: 
                   10691: sub rndseed_32bit {
                   10692:     my ($symb,$courseid,$domain,$username)=@_;
                   10693:     {
                   10694: 	use integer;
                   10695: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10696: 	my $symbseed=numval($symb) << 22;
                   10697: 	my $namechck=unpack("%32C*",$username) << 17;
                   10698: 	my $nameseed=numval($username) << 12;
                   10699: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10700: 	my $courseseed=unpack("%32C*",$courseid);
                   10701: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10702: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10703: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10704: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10705: 	return $num;
                   10706:     }
                   10707: }
                   10708: 
                   10709: sub rndseed_64bit {
                   10710:     my ($symb,$courseid,$domain,$username)=@_;
                   10711:     {
                   10712: 	use integer;
                   10713: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10714: 	my $symbseed=numval($symb) << 10;
                   10715: 	my $namechck=unpack("%32S*",$username);
                   10716: 	
                   10717: 	my $nameseed=numval($username) << 21;
                   10718: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10719: 	my $courseseed=unpack("%32S*",$courseid);
                   10720: 	
                   10721: 	my $num1=$symbchck+$symbseed+$namechck;
                   10722: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10723: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10724: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10725: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10726: 	return "$num1,$num2";
1.155     albertel 10727:     }
1.366     albertel 10728: }
                   10729: 
1.443     albertel 10730: sub rndseed_64bit2 {
                   10731:     my ($symb,$courseid,$domain,$username)=@_;
                   10732:     {
                   10733: 	use integer;
                   10734: 	# strings need to be an even # of cahracters long, it it is odd the
                   10735:         # last characters gets thrown away
                   10736: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10737: 	my $symbseed=numval($symb) << 10;
                   10738: 	my $namechck=unpack("%32S*",$username.' ');
                   10739: 	
                   10740: 	my $nameseed=numval($username) << 21;
1.501     albertel 10741: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10742: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10743: 	
                   10744: 	my $num1=$symbchck+$symbseed+$namechck;
                   10745: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10746: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10747: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10748: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10749: 	return "$num1,$num2";
                   10750:     }
                   10751: }
                   10752: 
                   10753: sub rndseed_64bit3 {
                   10754:     my ($symb,$courseid,$domain,$username)=@_;
                   10755:     {
                   10756: 	use integer;
                   10757: 	# strings need to be an even # of cahracters long, it it is odd the
                   10758:         # last characters gets thrown away
                   10759: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10760: 	my $symbseed=numval2($symb) << 10;
                   10761: 	my $namechck=unpack("%32S*",$username.' ');
                   10762: 	
                   10763: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10764: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10765: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10766: 	
                   10767: 	my $num1=$symbchck+$symbseed+$namechck;
                   10768: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10769: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10770: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10771: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10772: 	
1.503     albertel 10773: 	return "$num1:$num2";
1.443     albertel 10774:     }
                   10775: }
                   10776: 
1.575     albertel 10777: sub rndseed_64bit4 {
                   10778:     my ($symb,$courseid,$domain,$username)=@_;
                   10779:     {
                   10780: 	use integer;
                   10781: 	# strings need to be an even # of cahracters long, it it is odd the
                   10782:         # last characters gets thrown away
                   10783: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10784: 	my $symbseed=numval3($symb) << 10;
                   10785: 	my $namechck=unpack("%32S*",$username.' ');
                   10786: 	
                   10787: 	my $nameseed=numval3($username) << 21;
                   10788: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10789: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10790: 	
                   10791: 	my $num1=$symbchck+$symbseed+$namechck;
                   10792: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10793: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10794: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10795: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10796: 	
1.575     albertel 10797: 	return "$num1:$num2";
                   10798:     }
                   10799: }
                   10800: 
1.675     albertel 10801: sub rndseed_64bit5 {
                   10802:     my ($symb,$courseid,$domain,$username)=@_;
                   10803:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10804:     return "$num1:$num2";
                   10805: }
                   10806: 
1.366     albertel 10807: sub rndseed_CODE_64bit {
                   10808:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10809:     {
1.366     albertel 10810: 	use integer;
1.443     albertel 10811: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10812: 	my $symbseed=numval2($symb);
1.491     albertel 10813: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10814: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10815: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10816: 	my $num1=$symbseed+$CODEchck;
                   10817: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10818: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10819: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10820: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10821: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10822: 	return "$num1:$num2";
1.366     albertel 10823:     }
                   10824: }
                   10825: 
1.575     albertel 10826: sub rndseed_CODE_64bit4 {
                   10827:     my ($symb,$courseid,$domain,$username)=@_;
                   10828:     {
                   10829: 	use integer;
                   10830: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10831: 	my $symbseed=numval3($symb);
                   10832: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10833: 	my $CODEseed=numval3(&getCODE());
                   10834: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10835: 	my $num1=$symbseed+$CODEchck;
                   10836: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10837: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10838: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10839: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10840: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10841: 	return "$num1:$num2";
                   10842:     }
                   10843: }
                   10844: 
1.675     albertel 10845: sub rndseed_CODE_64bit5 {
                   10846:     my ($symb,$courseid,$domain,$username)=@_;
                   10847:     my $code = &getCODE();
                   10848:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10849:     return "$num1:$num2";
                   10850: }
                   10851: 
1.366     albertel 10852: sub setup_random_from_rndseed {
                   10853:     my ($rndseed)=@_;
1.503     albertel 10854:     if ($rndseed =~/([,:])/) {
                   10855: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10856: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10857:     } else {
                   10858: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10859:     }
1.36      albertel 10860: }
                   10861: 
1.474     albertel 10862: sub latest_receipt_algorithm_id {
1.835     albertel 10863:     return 'receipt3';
1.474     albertel 10864: }
                   10865: 
1.480     www      10866: sub recunique {
                   10867:     my $fucourseid=shift;
                   10868:     my $unique;
1.835     albertel 10869:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10870: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10871: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10872:     } else {
                   10873: 	$unique=$perlvar{'lonReceipt'};
                   10874:     }
                   10875:     return unpack("%32C*",$unique);
                   10876: }
                   10877: 
                   10878: sub recprefix {
                   10879:     my $fucourseid=shift;
                   10880:     my $prefix;
1.835     albertel 10881:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10882: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10883: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10884:     } else {
                   10885: 	$prefix=$perlvar{'lonHostID'};
                   10886:     }
                   10887:     return unpack("%32C*",$prefix);
                   10888: }
                   10889: 
1.76      www      10890: sub ireceipt {
1.474     albertel 10891:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10892: 
                   10893:     my $return =&recprefix($fucourseid).'-';
                   10894: 
                   10895:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10896: 	$env{'request.state'} eq 'construct') {
                   10897: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10898: 	return $return;
                   10899:     }
                   10900: 
1.76      www      10901:     my $cuname=unpack("%32C*",$funame);
                   10902:     my $cudom=unpack("%32C*",$fudom);
                   10903:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10904:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10905:     my $cunique=&recunique($fucourseid);
1.474     albertel 10906:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10907:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10908: 
1.790     albertel 10909: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10910: 			       
                   10911: 	$return.= ($cunique%$cuname+
                   10912: 		   $cunique%$cudom+
                   10913: 		   $cusymb%$cuname+
                   10914: 		   $cusymb%$cudom+
                   10915: 		   $cucourseid%$cuname+
                   10916: 		   $cucourseid%$cudom+
                   10917: 		   $cpart%$cuname+
                   10918: 		   $cpart%$cudom);
                   10919:     } else {
                   10920: 	$return.= ($cunique%$cuname+
                   10921: 		   $cunique%$cudom+
                   10922: 		   $cusymb%$cuname+
                   10923: 		   $cusymb%$cudom+
                   10924: 		   $cucourseid%$cuname+
                   10925: 		   $cucourseid%$cudom);
                   10926:     }
                   10927:     return $return;
1.76      www      10928: }
                   10929: 
                   10930: sub receipt {
1.474     albertel 10931:     my ($part)=@_;
1.790     albertel 10932:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10933:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10934: }
1.260     ng       10935: 
1.790     albertel 10936: sub whichuser {
                   10937:     my ($passedsymb)=@_;
                   10938:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10939:     if (defined($env{'form.grade_symb'})) {
                   10940: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10941: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10942: 	if (!$allowed &&
                   10943: 	    exists($env{'request.course.sec'}) &&
                   10944: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10945: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10946: 			      '/'.$env{'request.course.sec'});
                   10947: 	}
                   10948: 	if ($allowed) {
                   10949: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10950: 	    $courseid=$tmp_courseid;
                   10951: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10952: 	    ($name)=&get_env_multiple('form.grade_username');
                   10953: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10954: 	}
                   10955:     }
                   10956:     if (!$passedsymb) {
                   10957: 	$symb=&symbread();
                   10958:     } else {
                   10959: 	$symb=$passedsymb;
                   10960:     }
                   10961:     $courseid=$env{'request.course.id'};
                   10962:     $domain=$env{'user.domain'};
                   10963:     $name=$env{'user.name'};
                   10964:     if ($name eq 'public' && $domain eq 'public') {
                   10965: 	if (!defined($env{'form.username'})) {
                   10966: 	    $env{'form.username'}.=time.rand(10000000);
                   10967: 	}
                   10968: 	$name.=$env{'form.username'};
                   10969:     }
                   10970:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10971: 
                   10972: }
                   10973: 
1.36      albertel 10974: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10975: # returns either the contents of the file or 
                   10976: # -1 if the file doesn't exist
1.481     raeburn  10977: #
                   10978: # if the target is a file that was uploaded via DOCS, 
                   10979: # a check will be made to see if a current copy exists on the local server,
                   10980: # if it does this will be served, otherwise a copy will be retrieved from
                   10981: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10982: # the local server.   
1.472     albertel 10983: 
1.36      albertel 10984: sub getfile {
1.538     albertel 10985:     my ($file) = @_;
1.609     banghart 10986:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10987:     &repcopy($file);
                   10988:     return &readfile($file);
                   10989: }
                   10990: 
                   10991: sub repcopy_userfile {
                   10992:     my ($file)=@_;
1.1142    raeburn  10993:     my $londocroot = $perlvar{'lonDocRoot'};
                   10994:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10995:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10996:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10997: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10998:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10999:     if (-e "$file") {
1.828     www      11000: # we already have a local copy, check it out
1.538     albertel 11001: 	my @fileinfo = stat($file);
1.828     www      11002: 	my $rtncode;
                   11003: 	my $info;
1.538     albertel 11004: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11005: 	if ($lwpresp ne 'ok') {
1.828     www      11006: # there is no such file anymore, even though we had a local copy
1.482     albertel 11007: 	    if ($rtncode eq '404') {
1.538     albertel 11008: 		unlink($file);
1.482     albertel 11009: 	    }
                   11010: 	    return -1;
                   11011: 	}
                   11012: 	if ($info < $fileinfo[9]) {
1.828     www      11013: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11014: 	    return 'ok';
1.828     www      11015: 	} else {
                   11016: # the file is outdated, get rid of it
                   11017: 	    unlink($file);
1.482     albertel 11018: 	}
1.828     www      11019:     }
                   11020: # one way or the other, at this point, we don't have the file
                   11021: # construct the correct path for the file
                   11022:     my @parts = ($cdom,$cnum); 
                   11023:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11024: 	push @parts, split(/\//,$1);
                   11025:     }
                   11026:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11027:     foreach my $part (@parts) {
                   11028: 	$path .= '/'.$part;
                   11029: 	if (!-e $path) {
                   11030: 	    mkdir($path,0770);
1.482     albertel 11031: 	}
                   11032:     }
1.828     www      11033: # now the path exists for sure
                   11034: # get a user agent
                   11035:     my $ua=new LWP::UserAgent;
                   11036:     my $transferfile=$file.'.in.transfer';
                   11037: # FIXME: this should flock
                   11038:     if (-e $transferfile) { return 'ok'; }
                   11039:     my $request;
                   11040:     $uri=~s/^\///;
1.980     raeburn  11041:     my $homeserver = &homeserver($cnum,$cdom);
                   11042:     my $protocol = $protocol{$homeserver};
                   11043:     $protocol = 'http' if ($protocol ne 'https');
                   11044:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11045:     my $response=$ua->request($request,$transferfile);
                   11046: # did it work?
                   11047:     if ($response->is_error()) {
                   11048: 	unlink($transferfile);
                   11049: 	&logthis("Userfile repcopy failed for $uri");
                   11050: 	return -1;
                   11051:     }
                   11052: # worked, rename the transfer file
                   11053:     rename($transferfile,$file);
1.607     raeburn  11054:     return 'ok';
1.481     raeburn  11055: }
                   11056: 
1.517     albertel 11057: sub tokenwrapper {
                   11058:     my $uri=shift;
1.980     raeburn  11059:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11060:     $uri=~s|^/||;
1.620     albertel 11061:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11062:     my $token=$1;
1.552     albertel 11063:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11064:     if ($udom && $uname && $file) {
                   11065: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11066:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11067:         my $homeserver = &homeserver($uname,$udom);
                   11068:         my $protocol = $protocol{$homeserver};
                   11069:         $protocol = 'http' if ($protocol ne 'https');
                   11070:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11071:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11072:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11073:     } else {
                   11074:         return '/adm/notfound.html';
                   11075:     }
                   11076: }
                   11077: 
1.828     www      11078: # call with reqtype HEAD: get last modification time
                   11079: # call with reqtype GET: get the file contents
                   11080: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11081: #
1.481     raeburn  11082: sub getuploaded {
                   11083:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11084:     $uri=~s/^\///;
1.980     raeburn  11085:     my $homeserver = &homeserver($cnum,$cdom);
                   11086:     my $protocol = $protocol{$homeserver};
                   11087:     $protocol = 'http' if ($protocol ne 'https');
                   11088:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11089:     my $ua=new LWP::UserAgent;
                   11090:     my $request=new HTTP::Request($reqtype,$uri);
                   11091:     my $response=$ua->request($request);
                   11092:     $$rtncode = $response->code;
1.482     albertel 11093:     if (! $response->is_success()) {
                   11094: 	return 'failed';
                   11095:     }      
                   11096:     if ($reqtype eq 'HEAD') {
1.486     www      11097: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11098:     } elsif ($reqtype eq 'GET') {
                   11099: 	$$info = $response->content;
1.472     albertel 11100:     }
1.482     albertel 11101:     return 'ok';
1.36      albertel 11102: }
                   11103: 
1.481     raeburn  11104: sub readfile {
                   11105:     my $file = shift;
                   11106:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11107:     my $fh;
                   11108:     open($fh,"<$file");
                   11109:     my $a='';
1.800     albertel 11110:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11111:     return $a;
                   11112: }
                   11113: 
1.36      albertel 11114: sub filelocation {
1.590     banghart 11115:     my ($dir,$file) = @_;
                   11116:     my $location;
                   11117:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11118: 
                   11119:     if ($file =~ m-^/adm/-) {
                   11120: 	$file=~s-^/adm/wrapper/-/-;
                   11121: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11122:     }
1.882     albertel 11123: 
1.1139    www      11124:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11125:         $location = $file;
1.609     banghart 11126:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11127:         my ($udom,$uname,$filename)=
1.811     albertel 11128:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11129:         my $home=&homeserver($uname,$udom);
                   11130:         my $is_me=0;
                   11131:         my @ids=&current_machine_ids();
                   11132:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11133:         if ($is_me) {
1.1117    foxr     11134:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11135:         } else {
                   11136:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11137:   	      $udom.'/'.$uname.'/'.$filename;
                   11138:         }
1.882     albertel 11139:     } elsif ($file =~ m-^/adm/-) {
                   11140: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11141:     } else {
                   11142:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11143:         $file=~s:^/(res|priv)/:/:;
                   11144:         my $space=$1;
1.590     banghart 11145:         if ( !( $file =~ m:^/:) ) {
                   11146:             $location = $dir. '/'.$file;
                   11147:         } else {
1.1142    raeburn  11148:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11149:         }
1.59      albertel 11150:     }
1.590     banghart 11151:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11152:     while ($location=~m{/\.\./}) {
                   11153: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11154: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11155: 	} else {
                   11156: 	    $location=~ s{/\.\./}{/}g;
                   11157: 	}
                   11158:     } #remove dir/..
1.590     banghart 11159:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11160:     return $location;
1.46      www      11161: }
1.36      albertel 11162: 
1.46      www      11163: sub hreflocation {
                   11164:     my ($dir,$file)=@_;
1.980     raeburn  11165:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11166: 	$file=filelocation($dir,$file);
1.700     albertel 11167:     } elsif ($file=~m-^/adm/-) {
                   11168: 	$file=~s-^/adm/wrapper/-/-;
                   11169: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11170:     }
                   11171:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11172: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11173:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11174: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11175: 	        {/uploaded/$1/$2/}x;
1.46      www      11176:     }
1.913     albertel 11177:     if ($file=~ m{^/userfiles/}) {
                   11178: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11179:     }
1.462     albertel 11180:     return $file;
1.465     albertel 11181: }
                   11182: 
1.1139    www      11183: 
                   11184: 
                   11185: 
                   11186: 
1.465     albertel 11187: sub current_machine_domains {
1.853     albertel 11188:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11189: }
                   11190: 
                   11191: sub machine_domains {
                   11192:     my ($hostname) = @_;
1.465     albertel 11193:     my @domains;
1.838     albertel 11194:     my %hostname = &all_hostnames();
1.465     albertel 11195:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11196: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11197: 	if ($hostname eq $name) {
1.844     albertel 11198: 	    push(@domains,&host_domain($id));
1.465     albertel 11199: 	}
                   11200:     }
                   11201:     return @domains;
                   11202: }
                   11203: 
                   11204: sub current_machine_ids {
1.853     albertel 11205:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11206: }
                   11207: 
                   11208: sub machine_ids {
                   11209:     my ($hostname) = @_;
                   11210:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11211:     my @ids;
1.888     albertel 11212:     my %name_to_host = &all_names();
1.889     albertel 11213:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11214: 	return @{ $name_to_host{$hostname} };
                   11215:     }
                   11216:     return;
1.31      www      11217: }
                   11218: 
1.824     raeburn  11219: sub additional_machine_domains {
                   11220:     my @domains;
                   11221:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11222:     while( my $line = <$fh>) {
                   11223:         $line =~ s/\s//g;
                   11224:         push(@domains,$line);
                   11225:     }
                   11226:     return @domains;
                   11227: }
                   11228: 
                   11229: sub default_login_domain {
                   11230:     my $domain = $perlvar{'lonDefDomain'};
                   11231:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11232:     foreach my $posdom (&current_machine_domains(),
                   11233:                         &additional_machine_domains()) {
                   11234:         if (lc($posdom) eq lc($testdomain)) {
                   11235:             $domain=$posdom;
                   11236:             last;
                   11237:         }
                   11238:     }
                   11239:     return $domain;
                   11240: }
                   11241: 
1.31      www      11242: # ------------------------------------------------------------- Declutters URLs
                   11243: 
                   11244: sub declutter {
                   11245:     my $thisfn=shift;
1.569     albertel 11246:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11247:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11248:     $thisfn=~s/^\///;
1.697     albertel 11249:     $thisfn=~s|^adm/wrapper/||;
                   11250:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11251:     $thisfn=~s/^res\///;
1.1172    bisitz   11252:     $thisfn=~s/^priv\///;
1.1032    raeburn  11253:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11254:         $thisfn=~s/\?.+$//;
                   11255:     }
1.268     www      11256:     return $thisfn;
                   11257: }
                   11258: 
                   11259: # ------------------------------------------------------------- Clutter up URLs
                   11260: 
                   11261: sub clutter {
                   11262:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11263:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11264: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11265:        $thisfn='/res'.$thisfn; 
                   11266:     }
1.1031    raeburn  11267:     if ($thisfn !~m|^/adm|) {
                   11268: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11269: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11270: 	} else {
                   11271: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11272: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11273: 	    if ($embstyle eq 'ssi'
                   11274: 		|| ($embstyle eq 'hdn')
                   11275: 		|| ($embstyle eq 'rat')
                   11276: 		|| ($embstyle eq 'prv')
                   11277: 		|| ($embstyle eq 'ign')) {
                   11278: 		#do nothing with these
                   11279: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11280: 		|| ($embstyle eq 'emb')
                   11281: 		|| ($embstyle eq 'wrp')) {
                   11282: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11283: 	    } elsif ($embstyle eq 'unk'
                   11284: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11285: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11286: 	    } else {
1.718     www      11287: #		&logthis("Got a blank emb style");
1.695     albertel 11288: 	    }
1.694     albertel 11289: 	}
                   11290:     }
1.31      www      11291:     return $thisfn;
1.12      www      11292: }
                   11293: 
1.787     albertel 11294: sub clutter_with_no_wrapper {
                   11295:     my $uri = &clutter(shift);
                   11296:     if ($uri =~ m-^/adm/-) {
                   11297: 	$uri =~ s-^/adm/wrapper/-/-;
                   11298: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11299:     }
                   11300:     return $uri;
                   11301: }
                   11302: 
1.557     albertel 11303: sub freeze_escape {
                   11304:     my ($value)=@_;
                   11305:     if (ref($value)) {
                   11306: 	$value=&nfreeze($value);
                   11307: 	return '__FROZEN__'.&escape($value);
                   11308:     }
                   11309:     return &escape($value);
                   11310: }
                   11311: 
1.11      www      11312: 
1.557     albertel 11313: sub thaw_unescape {
                   11314:     my ($value)=@_;
                   11315:     if ($value =~ /^__FROZEN__/) {
                   11316: 	substr($value,0,10,undef);
                   11317: 	$value=&unescape($value);
                   11318: 	return &thaw($value);
                   11319:     }
                   11320:     return &unescape($value);
                   11321: }
                   11322: 
1.436     albertel 11323: sub correct_line_ends {
                   11324:     my ($result)=@_;
                   11325:     $$result =~s/\r\n/\n/mg;
                   11326:     $$result =~s/\r/\n/mg;
1.415     albertel 11327: }
1.1       albertel 11328: # ================================================================ Main Program
                   11329: 
1.184     www      11330: sub goodbye {
1.204     albertel 11331:    &logthis("Starting Shut down");
1.443     albertel 11332: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11333:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11334: #converted
1.599     albertel 11335: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11336:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11337: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11338: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11339: #1.1 only
1.870     albertel 11340: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11341: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11342: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11343: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11344:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11345:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11346:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11347:    &flushcourselogs();
                   11348:    &logthis("Shutting down");
                   11349: }
                   11350: 
1.852     albertel 11351: sub get_dns {
1.869     albertel 11352:     my ($url,$func,$ignore_cache) = @_;
                   11353:     if (!$ignore_cache) {
                   11354: 	my ($content,$cached)=
                   11355: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11356: 	if ($cached) {
                   11357: 	    &$func($content);
                   11358: 	    return;
                   11359: 	}
                   11360:     }
                   11361: 
                   11362:     my %alldns;
1.852     albertel 11363:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11364:     foreach my $dns (<$config>) {
                   11365: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11366:         my $line = $1;
                   11367:         my ($host,$protocol) = split(/:/,$line);
                   11368:         if ($protocol ne 'https') {
                   11369:             $protocol = 'http';
                   11370:         }
                   11371: 	$alldns{$host} = $protocol;
1.869     albertel 11372:     }
                   11373:     while (%alldns) {
                   11374: 	my ($dns) = keys(%alldns);
1.852     albertel 11375: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11376:         $ua->timeout(30);
1.979     raeburn  11377: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11378: 	my $response=$ua->request($request);
1.979     raeburn  11379:         delete($alldns{$dns});
1.852     albertel 11380: 	next if ($response->is_error());
                   11381: 	my @content = split("\n",$response->content);
1.869     albertel 11382: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 11383: 	&$func(\@content);
1.869     albertel 11384: 	return;
1.852     albertel 11385:     }
                   11386:     close($config);
1.871     albertel 11387:     my $which = (split('/',$url))[3];
                   11388:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11389:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11390:     my @content = <$config>;
                   11391:     &$func(\@content);
                   11392:     return;
1.852     albertel 11393: }
1.327     albertel 11394: # ------------------------------------------------------------ Read domain file
                   11395: {
1.852     albertel 11396:     my $loaded;
1.846     albertel 11397:     my %domain;
                   11398: 
1.852     albertel 11399:     sub parse_domain_tab {
                   11400: 	my ($lines) = @_;
                   11401: 	foreach my $line (@$lines) {
                   11402: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11403: 
1.846     albertel 11404: 	    chomp($line);
1.852     albertel 11405: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11406: 	    my %this_domain;
                   11407: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11408: 			       'lang_def', 'city', 'longi', 'lati',
                   11409: 			       'primary') {
                   11410: 		$this_domain{$field} = shift(@elements);
                   11411: 	    }
                   11412: 	    $domain{$name} = \%this_domain;
1.852     albertel 11413: 	}
                   11414:     }
1.864     albertel 11415: 
                   11416:     sub reset_domain_info {
                   11417: 	undef($loaded);
                   11418: 	undef(%domain);
                   11419:     }
                   11420: 
1.852     albertel 11421:     sub load_domain_tab {
1.869     albertel 11422: 	my ($ignore_cache) = @_;
                   11423: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11424: 	my $fh;
                   11425: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11426: 	    my @lines = <$fh>;
                   11427: 	    &parse_domain_tab(\@lines);
1.448     albertel 11428: 	}
1.852     albertel 11429: 	close($fh);
                   11430: 	$loaded = 1;
1.327     albertel 11431:     }
1.846     albertel 11432: 
                   11433:     sub domain {
1.852     albertel 11434: 	&load_domain_tab() if (!$loaded);
                   11435: 
1.846     albertel 11436: 	my ($name,$what) = @_;
                   11437: 	return if ( !exists($domain{$name}) );
                   11438: 
                   11439: 	if (!$what) {
                   11440: 	    return $domain{$name}{'description'};
                   11441: 	}
                   11442: 	return $domain{$name}{$what};
                   11443:     }
1.974     raeburn  11444: 
                   11445:     sub domain_info {
                   11446:         &load_domain_tab() if (!$loaded);
                   11447:         return %domain;
                   11448:     }
                   11449: 
1.327     albertel 11450: }
                   11451: 
                   11452: 
1.1       albertel 11453: # ------------------------------------------------------------- Read hosts file
                   11454: {
1.838     albertel 11455:     my %hostname;
1.844     albertel 11456:     my %hostdom;
1.845     albertel 11457:     my %libserv;
1.852     albertel 11458:     my $loaded;
1.888     albertel 11459:     my %name_to_host;
1.1074    raeburn  11460:     my %internetdom;
1.1107    raeburn  11461:     my %LC_dns_serv;
1.852     albertel 11462: 
                   11463:     sub parse_hosts_tab {
                   11464: 	my ($file) = @_;
                   11465: 	foreach my $configline (@$file) {
                   11466: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11467:             chomp($configline);
                   11468: 	    if ($configline =~ /^\^/) {
                   11469:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11470:                     $LC_dns_serv{$1} = 1;
                   11471:                 }
                   11472:                 next;
                   11473:             }
1.1074    raeburn  11474: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11475: 	    $name=~s/\s//g;
                   11476: 	    if ($id && $domain && $role && $name) {
                   11477: 		$hostname{$id}=$name;
1.888     albertel 11478: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11479: 		$hostdom{$id}=$domain;
                   11480: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11481:                 if (defined($protocol)) {
                   11482:                     if ($protocol eq 'https') {
                   11483:                         $protocol{$id} = $protocol;
                   11484:                     } else {
                   11485:                         $protocol{$id} = 'http'; 
                   11486:                     }
1.968     raeburn  11487:                 } else {
1.969     raeburn  11488:                     $protocol{$id} = 'http';
1.968     raeburn  11489:                 }
1.1074    raeburn  11490:                 if (defined($intdom)) {
                   11491:                     $internetdom{$id} = $intdom;
                   11492:                 }
1.852     albertel 11493: 	    }
                   11494: 	}
                   11495:     }
1.864     albertel 11496:     
                   11497:     sub reset_hosts_info {
1.897     albertel 11498: 	&purge_remembered();
1.864     albertel 11499: 	&reset_domain_info();
                   11500: 	&reset_hosts_ip_info();
1.892     albertel 11501: 	undef(%name_to_host);
1.864     albertel 11502: 	undef(%hostname);
                   11503: 	undef(%hostdom);
                   11504: 	undef(%libserv);
                   11505: 	undef($loaded);
                   11506:     }
1.1       albertel 11507: 
1.852     albertel 11508:     sub load_hosts_tab {
1.869     albertel 11509: 	my ($ignore_cache) = @_;
                   11510: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11511: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11512: 	my @config = <$config>;
                   11513: 	&parse_hosts_tab(\@config);
                   11514: 	close($config);
                   11515: 	$loaded=1;
1.1       albertel 11516:     }
1.852     albertel 11517: 
1.838     albertel 11518:     sub hostname {
1.852     albertel 11519: 	&load_hosts_tab() if (!$loaded);
                   11520: 
1.838     albertel 11521: 	my ($lonid) = @_;
                   11522: 	return $hostname{$lonid};
                   11523:     }
1.845     albertel 11524: 
1.838     albertel 11525:     sub all_hostnames {
1.852     albertel 11526: 	&load_hosts_tab() if (!$loaded);
                   11527: 
1.838     albertel 11528: 	return %hostname;
                   11529:     }
1.845     albertel 11530: 
1.888     albertel 11531:     sub all_names {
                   11532: 	&load_hosts_tab() if (!$loaded);
                   11533: 
                   11534: 	return %name_to_host;
                   11535:     }
                   11536: 
1.974     raeburn  11537:     sub all_host_domain {
                   11538:         &load_hosts_tab() if (!$loaded);
                   11539:         return %hostdom;
                   11540:     }
                   11541: 
1.845     albertel 11542:     sub is_library {
1.852     albertel 11543: 	&load_hosts_tab() if (!$loaded);
                   11544: 
1.845     albertel 11545: 	return exists($libserv{$_[0]});
                   11546:     }
                   11547: 
                   11548:     sub all_library {
1.852     albertel 11549: 	&load_hosts_tab() if (!$loaded);
                   11550: 
1.845     albertel 11551: 	return %libserv;
                   11552:     }
                   11553: 
1.1062    droeschl 11554:     sub unique_library {
                   11555: 	#2x reverse removes all hostnames that appear more than once
                   11556:         my %unique = reverse &all_library();
                   11557:         return reverse %unique;
                   11558:     }
                   11559: 
1.841     albertel 11560:     sub get_servers {
1.852     albertel 11561: 	&load_hosts_tab() if (!$loaded);
                   11562: 
1.841     albertel 11563: 	my ($domain,$type) = @_;
                   11564: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11565: 	                                          : %hostname;
                   11566: 	my %result;
1.842     albertel 11567: 	if (ref($domain) eq 'ARRAY') {
                   11568: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11569: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11570: 		    $result{$host} = $hostname;
                   11571: 		}
                   11572: 	    }
                   11573: 	} else {
                   11574: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11575: 		if ($hostdom{$host} eq $domain) {
                   11576: 		    $result{$host} = $hostname;
                   11577: 		}
1.841     albertel 11578: 	    }
                   11579: 	}
                   11580: 	return %result;
                   11581:     }
1.845     albertel 11582: 
1.1062    droeschl 11583:     sub get_unique_servers {
                   11584:         my %unique = reverse &get_servers(@_);
                   11585: 	return reverse %unique;
                   11586:     }
                   11587: 
1.844     albertel 11588:     sub host_domain {
1.852     albertel 11589: 	&load_hosts_tab() if (!$loaded);
                   11590: 
1.844     albertel 11591: 	my ($lonid) = @_;
                   11592: 	return $hostdom{$lonid};
                   11593:     }
                   11594: 
1.841     albertel 11595:     sub all_domains {
1.852     albertel 11596: 	&load_hosts_tab() if (!$loaded);
                   11597: 
1.841     albertel 11598: 	my %seen;
                   11599: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11600: 	return @uniq;
                   11601:     }
1.1074    raeburn  11602: 
                   11603:     sub internet_dom {
                   11604:         &load_hosts_tab() if (!$loaded);
                   11605: 
                   11606:         my ($lonid) = @_;
                   11607:         return $internetdom{$lonid};
                   11608:     }
1.1107    raeburn  11609: 
                   11610:     sub is_LC_dns {
                   11611:         &load_hosts_tab() if (!$loaded);
                   11612: 
                   11613:         my ($hostname) = @_;
                   11614:         return exists($LC_dns_serv{$hostname});
                   11615:     }
                   11616: 
1.1       albertel 11617: }
                   11618: 
1.847     albertel 11619: { 
                   11620:     my %iphost;
1.856     albertel 11621:     my %name_to_ip;
                   11622:     my %lonid_to_ip;
1.869     albertel 11623: 
1.847     albertel 11624:     sub get_hosts_from_ip {
                   11625: 	my ($ip) = @_;
                   11626: 	my %iphosts = &get_iphost();
                   11627: 	if (ref($iphosts{$ip})) {
                   11628: 	    return @{$iphosts{$ip}};
                   11629: 	}
                   11630: 	return;
1.839     albertel 11631:     }
1.864     albertel 11632:     
                   11633:     sub reset_hosts_ip_info {
                   11634: 	undef(%iphost);
                   11635: 	undef(%name_to_ip);
                   11636: 	undef(%lonid_to_ip);
                   11637:     }
1.856     albertel 11638: 
                   11639:     sub get_host_ip {
                   11640: 	my ($lonid) = @_;
                   11641: 	if (exists($lonid_to_ip{$lonid})) {
                   11642: 	    return $lonid_to_ip{$lonid};
                   11643: 	}
                   11644: 	my $name=&hostname($lonid);
                   11645:    	my $ip = gethostbyname($name);
                   11646: 	return if (!$ip || length($ip) ne 4);
                   11647: 	$ip=inet_ntoa($ip);
                   11648: 	$name_to_ip{$name}   = $ip;
                   11649: 	$lonid_to_ip{$lonid} = $ip;
                   11650: 	return $ip;
                   11651:     }
1.847     albertel 11652:     
                   11653:     sub get_iphost {
1.869     albertel 11654: 	my ($ignore_cache) = @_;
1.894     albertel 11655: 
1.869     albertel 11656: 	if (!$ignore_cache) {
                   11657: 	    if (%iphost) {
                   11658: 		return %iphost;
                   11659: 	    }
                   11660: 	    my ($ip_info,$cached)=
                   11661: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11662: 	    if ($cached) {
                   11663: 		%iphost      = %{$ip_info->[0]};
                   11664: 		%name_to_ip  = %{$ip_info->[1]};
                   11665: 		%lonid_to_ip = %{$ip_info->[2]};
                   11666: 		return %iphost;
                   11667: 	    }
                   11668: 	}
1.894     albertel 11669: 
                   11670: 	# get yesterday's info for fallback
                   11671: 	my %old_name_to_ip;
                   11672: 	my ($ip_info,$cached)=
                   11673: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11674: 	if ($cached) {
                   11675: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11676: 	}
                   11677: 
1.888     albertel 11678: 	my %name_to_host = &all_names();
                   11679: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11680: 	    my $ip;
                   11681: 	    if (!exists($name_to_ip{$name})) {
                   11682: 		$ip = gethostbyname($name);
                   11683: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11684: 		    if (defined($old_name_to_ip{$name})) {
                   11685: 			$ip = $old_name_to_ip{$name};
                   11686: 			&logthis("Can't find $name defaulting to old $ip");
                   11687: 		    } else {
                   11688: 			&logthis("Name $name no IP found");
                   11689: 			next;
                   11690: 		    }
                   11691: 		} else {
                   11692: 		    $ip=inet_ntoa($ip);
1.847     albertel 11693: 		}
                   11694: 		$name_to_ip{$name} = $ip;
                   11695: 	    } else {
                   11696: 		$ip = $name_to_ip{$name};
1.653     albertel 11697: 	    }
1.888     albertel 11698: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11699: 		$lonid_to_ip{$id} = $ip;
                   11700: 	    }
                   11701: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11702: 	}
1.869     albertel 11703: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11704: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11705: 				      48*60*60);
1.869     albertel 11706: 
1.847     albertel 11707: 	return %iphost;
1.598     albertel 11708:     }
                   11709: 
1.992     raeburn  11710:     #
                   11711:     #  Given a DNS returns the loncapa host name for that DNS 
                   11712:     # 
                   11713:     sub host_from_dns {
                   11714:         my ($dns) = @_;
                   11715:         my @hosts;
                   11716:         my $ip;
                   11717: 
1.993     raeburn  11718:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11719:             $ip = $name_to_ip{$dns};
                   11720:         }
                   11721:         if (!$ip) {
                   11722:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11723:             if (length($ip) == 4) { 
                   11724: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11725:             }
                   11726:         }
                   11727:         if ($ip) {
                   11728: 	    @hosts = get_hosts_from_ip($ip);
                   11729: 	    return $hosts[0];
                   11730:         }
                   11731:         return undef;
1.986     foxr     11732:     }
1.992     raeburn  11733: 
1.1074    raeburn  11734:     sub get_internet_names {
                   11735:         my ($lonid) = @_;
                   11736:         return if ($lonid eq '');
                   11737:         my ($idnref,$cached)=
                   11738:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11739:         if ($cached) {
                   11740:             return $idnref;
                   11741:         }
                   11742:         my $ip = &get_host_ip($lonid);
                   11743:         my @hosts = &get_hosts_from_ip($ip);
                   11744:         my %iphost = &get_iphost();
                   11745:         my (@idns,%seen);
                   11746:         foreach my $id (@hosts) {
                   11747:             my $dom = &host_domain($id);
                   11748:             my $prim_id = &domain($dom,'primary');
                   11749:             my $prim_ip = &get_host_ip($prim_id);
                   11750:             next if ($seen{$prim_ip});
                   11751:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11752:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11753:                     my $intdom = &internet_dom($id);
                   11754:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11755:                         push(@idns,$intdom);
                   11756:                     }
                   11757:                 }
                   11758:             }
                   11759:             $seen{$prim_ip} = 1;
                   11760:         }
                   11761:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11762:     }
                   11763: 
1.986     foxr     11764: }
                   11765: 
1.1079    raeburn  11766: sub all_loncaparevs {
                   11767:     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);
                   11768: }
                   11769: 
1.862     albertel 11770: BEGIN {
                   11771: 
                   11772: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11773:     unless ($readit) {
                   11774: {
                   11775:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11776:     %perlvar = (%perlvar,%{$configvars});
                   11777: }
                   11778: 
                   11779: 
1.1       albertel 11780: # ------------------------------------------------------ Read spare server file
                   11781: {
1.448     albertel 11782:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11783: 
                   11784:     while (my $configline=<$config>) {
                   11785:        chomp($configline);
1.284     matthew  11786:        if ($configline) {
1.784     albertel 11787: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11788: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11789: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11790:        }
                   11791:     }
1.448     albertel 11792:     close($config);
1.1       albertel 11793: }
1.11      www      11794: # ------------------------------------------------------------ Read permissions
                   11795: {
1.448     albertel 11796:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11797: 
                   11798:     while (my $configline=<$config>) {
1.448     albertel 11799: 	chomp($configline);
                   11800: 	if ($configline) {
                   11801: 	    my ($role,$perm)=split(/ /,$configline);
                   11802: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11803: 	}
1.11      www      11804:     }
1.448     albertel 11805:     close($config);
1.11      www      11806: }
                   11807: 
                   11808: # -------------------------------------------- Read plain texts for permissions
                   11809: {
1.448     albertel 11810:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11811: 
                   11812:     while (my $configline=<$config>) {
1.448     albertel 11813: 	chomp($configline);
                   11814: 	if ($configline) {
1.742     raeburn  11815: 	    my ($short,@plain)=split(/:/,$configline);
                   11816:             %{$prp{$short}} = ();
                   11817: 	    if (@plain > 0) {
                   11818:                 $prp{$short}{'std'} = $plain[0];
                   11819:                 for (my $i=1; $i<@plain; $i++) {
                   11820:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11821:                 }
                   11822:             }
1.448     albertel 11823: 	}
1.135     www      11824:     }
1.448     albertel 11825:     close($config);
1.135     www      11826: }
                   11827: 
                   11828: # ---------------------------------------------------------- Read package table
                   11829: {
1.448     albertel 11830:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11831: 
                   11832:     while (my $configline=<$config>) {
1.483     albertel 11833: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11834: 	chomp($configline);
                   11835: 	my ($short,$plain)=split(/:/,$configline);
                   11836: 	my ($pack,$name)=split(/\&/,$short);
                   11837: 	if ($plain ne '') {
                   11838: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11839: 	    $packagetab{$short}=$plain; 
                   11840: 	}
1.11      www      11841:     }
1.448     albertel 11842:     close($config);
1.329     matthew  11843: }
                   11844: 
1.1073    raeburn  11845: # ---------------------------------------------------------- Read loncaparev table
                   11846: {
                   11847:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11848:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11849:             while (my $configline=<$config>) {
                   11850:                 chomp($configline);
                   11851:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11852:                 $loncaparevs{$hostid}=$loncaparev;
                   11853:             }
                   11854:             close($config);
                   11855:         }
                   11856:     }
                   11857: }
                   11858: 
1.1074    raeburn  11859: # ---------------------------------------------------------- Read serverhostID table
                   11860: {
                   11861:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11862:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11863:             while (my $configline=<$config>) {
                   11864:                 chomp($configline);
                   11865:                 my ($name,$id)=split(/:/,$configline);
                   11866:                 $serverhomeIDs{$name}=$id;
                   11867:             }
                   11868:             close($config);
                   11869:         }
                   11870:     }
                   11871: }
                   11872: 
1.1079    raeburn  11873: {
                   11874:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11875:     if (-e $file) {
                   11876:         my $parser = HTML::LCParser->new($file);
                   11877:         while (my $token = $parser->get_token()) {
                   11878:             if ($token->[0] eq 'S') {
                   11879:                 my $item = $token->[1];
                   11880:                 my $name = $token->[2]{'name'};
                   11881:                 my $value = $token->[2]{'value'};
                   11882:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11883:                     my $release = $parser->get_text();
                   11884:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11885:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11886:                 }
                   11887:             }
                   11888:         }
                   11889:     }
1.1073    raeburn  11890: }
                   11891: 
1.1138    raeburn  11892: # ---------------------------------------------------------- Read managers table
                   11893: {
                   11894:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11895:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11896:             while (my $configline=<$config>) {
                   11897:                 chomp($configline);
                   11898:                 next if ($configline =~ /^\#/);
                   11899:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11900:                     $managerstab{$configline} = 1;
                   11901:                 }
                   11902:             }
                   11903:             close($config);
                   11904:         }
                   11905:     }
                   11906: }
                   11907: 
1.329     matthew  11908: # ------------- set up temporary directory
                   11909: {
1.1117    foxr     11910:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11911: 
1.11      www      11912: }
                   11913: 
1.794     albertel 11914: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11915: 				'compress_threshold'=> 20_000,
                   11916:  			        });
1.185     www      11917: 
1.281     www      11918: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11919: $dumpcount=0;
1.958     www      11920: $locknum=0;
1.22      www      11921: 
1.163     harris41 11922: &logtouch();
1.672     albertel 11923: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11924: $readit=1;
1.564     albertel 11925:     {
                   11926: 	use integer;
                   11927: 	my $test=(2**32)+1;
1.568     albertel 11928: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11929: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11930:     }
1.195     www      11931: }
1.1       albertel 11932: }
1.179     www      11933: 
1.1       albertel 11934: 1;
1.191     harris41 11935: __END__
                   11936: 
1.243     albertel 11937: =pod
                   11938: 
1.191     harris41 11939: =head1 NAME
                   11940: 
1.243     albertel 11941: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11942: 
                   11943: =head1 SYNOPSIS
                   11944: 
1.243     albertel 11945: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11946: 
                   11947:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11948: 
1.243     albertel 11949: Common parameters:
                   11950: 
                   11951: =over 4
                   11952: 
                   11953: =item *
                   11954: 
                   11955: $uname : an internal username (if $cname expecting a course Id specifically)
                   11956: 
                   11957: =item *
                   11958: 
                   11959: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11960: 
                   11961: =item *
                   11962: 
                   11963: $symb : a resource instance identifier
                   11964: 
                   11965: =item *
                   11966: 
                   11967: $namespace : the name of a .db file that contains the data needed or
                   11968: being set.
                   11969: 
                   11970: =back
                   11971: 
1.394     bowersj2 11972: =head1 OVERVIEW
1.191     harris41 11973: 
1.394     bowersj2 11974: lonnet provides subroutines which interact with the
                   11975: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11976: about classes, users, and resources.
1.243     albertel 11977: 
                   11978: For many of these objects you can also use this to store data about
                   11979: them or modify them in various ways.
1.191     harris41 11980: 
1.394     bowersj2 11981: =head2 Symbs
1.191     harris41 11982: 
1.394     bowersj2 11983: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11984: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11985: map, the resource number of the resource in the map, and the URL of
                   11986: the resource itself. The latter is somewhat redundant, but might help
                   11987: if maps change.
                   11988: 
                   11989: An example is
                   11990: 
                   11991:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11992: 
                   11993: The respective map entry is
                   11994: 
                   11995:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11996:   title="Problem 2">
                   11997:  </resource>
                   11998: 
                   11999: Symbs are used by the random number generator, as well as to store and
                   12000: restore data specific to a certain instance of for example a problem.
                   12001: 
                   12002: =head2 Storing And Retrieving Data
                   12003: 
                   12004: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12005: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12006: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12007: is is the non-critical message twin of cstore. These functions are for
                   12008: handlers to store a perl hash to a user's permanent data space in an
                   12009: easy manner, and to retrieve it again on another call. It is expected
                   12010: that a handler would use this once at the beginning to retrieve data,
                   12011: and then again once at the end to send only the new data back.
                   12012: 
                   12013: The data is stored in the user's data directory on the user's
                   12014: homeserver under the ID of the course.
                   12015: 
                   12016: The hash that is returned by restore will have all of the previous
                   12017: value for all of the elements of the hash.
                   12018: 
                   12019: Example:
                   12020: 
                   12021:  #creating a hash
                   12022:  my %hash;
                   12023:  $hash{'foo'}='bar';
                   12024: 
                   12025:  #storing it
                   12026:  &Apache::lonnet::cstore(\%hash);
                   12027: 
                   12028:  #changing a value
                   12029:  $hash{'foo'}='notbar';
                   12030: 
                   12031:  #adding a new value
                   12032:  $hash{'bar'}='foo';
                   12033:  &Apache::lonnet::cstore(\%hash);
                   12034: 
                   12035:  #retrieving the hash
                   12036:  my %history=&Apache::lonnet::restore();
                   12037: 
                   12038:  #print the hash
                   12039:  foreach my $key (sort(keys(%history))) {
                   12040:    print("\%history{$key} = $history{$key}");
                   12041:  }
                   12042: 
                   12043: Will print out:
1.191     harris41 12044: 
1.394     bowersj2 12045:  %history{1:foo} = bar
                   12046:  %history{1:keys} = foo:timestamp
                   12047:  %history{1:timestamp} = 990455579
                   12048:  %history{2:bar} = foo
                   12049:  %history{2:foo} = notbar
                   12050:  %history{2:keys} = foo:bar:timestamp
                   12051:  %history{2:timestamp} = 990455580
                   12052:  %history{bar} = foo
                   12053:  %history{foo} = notbar
                   12054:  %history{timestamp} = 990455580
                   12055:  %history{version} = 2
                   12056: 
                   12057: Note that the special hash entries C<keys>, C<version> and
                   12058: C<timestamp> were added to the hash. C<version> will be equal to the
                   12059: total number of versions of the data that have been stored. The
                   12060: C<timestamp> attribute will be the UNIX time the hash was
                   12061: stored. C<keys> is available in every historical section to list which
                   12062: keys were added or changed at a specific historical revision of a
                   12063: hash.
                   12064: 
                   12065: B<Warning>: do not store the hash that restore returns directly. This
                   12066: will cause a mess since it will restore the historical keys as if the
                   12067: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12068: 
1.394     bowersj2 12069: Calling convention:
1.191     harris41 12070: 
1.394     bowersj2 12071:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12072:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12073: 
1.394     bowersj2 12074: For more detailed information, see lonnet specific documentation.
1.191     harris41 12075: 
1.394     bowersj2 12076: =head1 RETURN MESSAGES
1.191     harris41 12077: 
1.394     bowersj2 12078: =over 4
1.191     harris41 12079: 
1.394     bowersj2 12080: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12081: 
1.394     bowersj2 12082: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12083: when the connection is brought back up
1.191     harris41 12084: 
1.394     bowersj2 12085: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12086: for later delivery
1.191     harris41 12087: 
1.967     bisitz   12088: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12089: 
1.394     bowersj2 12090: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12091: that was requested
1.191     harris41 12092: 
1.243     albertel 12093: =back
1.191     harris41 12094: 
1.243     albertel 12095: =head1 PUBLIC SUBROUTINES
1.191     harris41 12096: 
1.243     albertel 12097: =head2 Session Environment Functions
1.191     harris41 12098: 
1.243     albertel 12099: =over 4
1.191     harris41 12100: 
1.394     bowersj2 12101: =item * 
                   12102: X<appenv()>
1.949     raeburn  12103: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12104: the user envirnoment file, and will be restored for each access this
1.620     albertel 12105: user makes during this session, also modifies the %env for the current
1.949     raeburn  12106: process. Optional rolesarrayref - if defined contains a reference to an array
                   12107: of roles which are exempt from the restriction on modifying user.role entries 
                   12108: in the user's environment.db and in %env.    
1.191     harris41 12109: 
                   12110: =item *
1.394     bowersj2 12111: X<delenv()>
1.987     raeburn  12112: B<delenv($delthis,$regexp)>: removes all items from the session
                   12113: environment file that begin with $delthis. If the 
                   12114: optional second arg - $regexp - is true, $delthis is treated as a 
                   12115: regular expression, otherwise \Q$delthis\E is used. 
                   12116: The values are also deleted from the current processes %env.
1.191     harris41 12117: 
1.795     albertel 12118: =item * get_env_multiple($name) 
                   12119: 
                   12120: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12121: values may be defined and end up as an array ref.
                   12122: 
                   12123: returns an array of values
                   12124: 
1.243     albertel 12125: =back
                   12126: 
                   12127: =head2 User Information
1.191     harris41 12128: 
1.243     albertel 12129: =over 4
1.191     harris41 12130: 
                   12131: =item *
1.394     bowersj2 12132: X<queryauthenticate()>
                   12133: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12134: authentication scheme
                   12135: 
                   12136: =item *
1.394     bowersj2 12137: X<authenticate()>
1.1073    raeburn  12138: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12139: authenticate user from domain's lib servers (first use the current
                   12140: one). C<$upass> should be the users password.
1.1073    raeburn  12141: $checkdefauth is optional (value is 1 if a check should be made to
                   12142:    authenticate user using default authentication method, and allow
                   12143:    account creation if username does not have account in the domain).
                   12144: $clientcancheckhost is optional (value is 1 if checking whether the
                   12145:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12146: 
                   12147: =item *
1.394     bowersj2 12148: X<homeserver()>
                   12149: B<homeserver($uname,$udom)>: find the server which has
                   12150: the user's directory and files (there must be only one), this caches
                   12151: the answer, and also caches if there is a borken connection.
1.191     harris41 12152: 
                   12153: =item *
1.394     bowersj2 12154: X<idget()>
                   12155: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12156: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12157: username, and only 1 username per ID in a specific domain) (returns
                   12158: hash: id=>name,id=>name)
1.191     harris41 12159: 
                   12160: =item *
1.394     bowersj2 12161: X<idrget()>
                   12162: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12163: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12164: 
                   12165: =item *
1.394     bowersj2 12166: X<idput()>
                   12167: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12168: 
                   12169: =item *
1.394     bowersj2 12170: X<rolesinit()>
1.1169    droeschl 12171: B<rolesinit($udom,$username)>: get user privileges.
                   12172: returns user role, first access and timer interval hashes
1.243     albertel 12173: 
                   12174: =item *
1.1171    droeschl 12175: X<privileged()>
                   12176: B<privileged($username,$domain)>: returns a true if user has a
                   12177: privileged and active role (i.e. su or dc), false otherwise.
                   12178: 
                   12179: =item *
1.551     albertel 12180: X<getsection()>
                   12181: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12182: course $cname, return section name/number or '' for "not in course"
                   12183: and '-1' for "no section"
                   12184: 
                   12185: =item *
1.394     bowersj2 12186: X<userenvironment()>
                   12187: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12188: passed in @what from the requested user's environment, returns a hash
                   12189: 
1.858     raeburn  12190: =item * 
                   12191: X<userlog_query()>
1.859     albertel 12192: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12193: activity.log file. %filters defines filters applied when parsing the
                   12194: log file. These can be start or end timestamps, or the type of action
                   12195: - log to look for Login or Logout events, check for Checkin or
                   12196: Checkout, role for role selection. The response is in the form
                   12197: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12198: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12199: 
1.243     albertel 12200: =back
                   12201: 
                   12202: =head2 User Roles
                   12203: 
                   12204: =over 4
                   12205: 
                   12206: =item *
                   12207: 
1.810     raeburn  12208: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12209:  F: full access
                   12210:  U,I,K: authentication modes (cxx only)
                   12211:  '': forbidden
                   12212:  1: user needs to choose course
                   12213:  2: browse allowed
1.766     albertel 12214:  A: passphrase authentication needed
1.243     albertel 12215: 
                   12216: =item *
                   12217: 
1.1192    raeburn  12218: constructaccess($url,$setpriv) : check for access to construction space URL
                   12219: 
                   12220: See if the owner domain and name in the URL match those in the
                   12221: expected environment.  If so, return three element list
                   12222: ($ownername,$ownerdomain,$ownerhome).
                   12223: 
                   12224: Otherwise return the null string.
                   12225: 
                   12226: If second argument 'setpriv' is true, it assigns the privileges,
                   12227: and returns the same three element list, unless the owner has
                   12228: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12229: in which case the null string is returned.
                   12230: 
                   12231: =item *
                   12232: 
1.243     albertel 12233: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12234: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12235: and course level
                   12236: 
                   12237: =item *
                   12238: 
1.988     raeburn  12239: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12240: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12241: $type is Course (default) or Community.
1.988     raeburn  12242: If $forcedefault evaluates to true, text returned will be default 
                   12243: text for $type. Otherwise, if this is a course, the text returned 
                   12244: will be a custom name for the role (if defined in the course's 
                   12245: environment).  If no custom name is defined the default is returned.
                   12246:    
1.832     raeburn  12247: =item *
                   12248: 
1.935     raeburn  12249: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12250: All arguments are optional. Returns a hash of a roles, either for
                   12251: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12252: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12253: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12254: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12255: For each key, value is set to colon-separated start and end times for
                   12256: the role.  If no username and domain are specified, will default to
1.934     raeburn  12257: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12258: of role statuses (active, future or previous), roles 
                   12259: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12260: to restrict the list of roles reported. If no array ref is 
                   12261: provided for types, will default to return only active roles.
1.834     albertel 12262: 
1.1195    raeburn  12263: =item *
                   12264: 
                   12265: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12266: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12267: 
                   12268: Additional optional arguments are: $type (if role checking is to be restricted 
                   12269: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12270: available roles) or future (roles available in the future), and
                   12271: $hideprivileged -- if true will not report course roles for users who
                   12272: have active Domain Coordinator or Super User roles.
                   12273: 
1.243     albertel 12274: =back
                   12275: 
                   12276: =head2 User Modification
                   12277: 
                   12278: =over 4
                   12279: 
                   12280: =item *
                   12281: 
1.957     raeburn  12282: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12283: user for the level given by URL.  Optional start and end dates (leave empty
                   12284: string or zero for "no date")
1.191     harris41 12285: 
                   12286: =item *
                   12287: 
1.243     albertel 12288: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12289: change a users, password, possible return values are: ok,
                   12290: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12291: refused
1.191     harris41 12292: 
                   12293: =item *
                   12294: 
1.243     albertel 12295: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12296: 
                   12297: =item *
                   12298: 
1.1058    raeburn  12299: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12300:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12301: 
                   12302: will update user information (firstname,middlename,lastname,generation,
                   12303: permanentemail), and if forceid is true, student/employee ID also.
                   12304: A user's institutional affiliation(s) can also be updated.
                   12305: User information fields will not be overwritten with empty entries 
                   12306: unless the field is included in the $candelete array reference.
                   12307: This array is included when a single user is modified via "Manage Users",
                   12308: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12309: 
                   12310: =item *
                   12311: 
1.286     matthew  12312: modifystudent
                   12313: 
1.957     raeburn  12314: modify a student's enrollment and identification information.
1.286     matthew  12315: The course id is resolved based on the current users environment.  
                   12316: This means the envoking user must be a course coordinator or otherwise
                   12317: associated with a course.
                   12318: 
1.297     matthew  12319: This call is essentially a wrapper for lonnet::modifyuser and
                   12320: lonnet::modify_student_enrollment
1.286     matthew  12321: 
                   12322: Inputs: 
                   12323: 
                   12324: =over 4
                   12325: 
1.957     raeburn  12326: =item B<$udom> Student's loncapa domain
1.286     matthew  12327: 
1.957     raeburn  12328: =item B<$uname> Student's loncapa login name
1.286     matthew  12329: 
1.964     bisitz   12330: =item B<$uid> Student/Employee ID
1.286     matthew  12331: 
1.957     raeburn  12332: =item B<$umode> Student's authentication mode
1.286     matthew  12333: 
1.957     raeburn  12334: =item B<$upass> Student's password
1.286     matthew  12335: 
1.957     raeburn  12336: =item B<$first> Student's first name
1.286     matthew  12337: 
1.957     raeburn  12338: =item B<$middle> Student's middle name
1.286     matthew  12339: 
1.957     raeburn  12340: =item B<$last> Student's last name
1.286     matthew  12341: 
1.957     raeburn  12342: =item B<$gene> Student's generation
1.286     matthew  12343: 
1.957     raeburn  12344: =item B<$usec> Student's section in course
1.286     matthew  12345: 
                   12346: =item B<$end> Unix time of the roles expiration
                   12347: 
                   12348: =item B<$start> Unix time of the roles start date
                   12349: 
                   12350: =item B<$forceid> If defined, allow $uid to be changed
                   12351: 
                   12352: =item B<$desiredhome> server to use as home server for student
                   12353: 
1.957     raeburn  12354: =item B<$email> Student's permanent e-mail address
                   12355: 
                   12356: =item B<$type> Type of enrollment (auto or manual)
                   12357: 
1.963     raeburn  12358: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12359: 
                   12360: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12361: 
1.963     raeburn  12362: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12363: 
1.963     raeburn  12364: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12365: 
1.963     raeburn  12366: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  12367: 
1.286     matthew  12368: =back
1.297     matthew  12369: 
                   12370: =item *
                   12371: 
                   12372: modify_student_enrollment
                   12373: 
                   12374: Change a students enrollment status in a class.  The environment variable
                   12375: 'role.request.course' must be defined for this function to proceed.
                   12376: 
                   12377: Inputs:
                   12378: 
                   12379: =over 4
                   12380: 
                   12381: =item $udom, students domain
                   12382: 
                   12383: =item $uname, students name
                   12384: 
                   12385: =item $uid, students user id
                   12386: 
                   12387: =item $first, students first name
                   12388: 
                   12389: =item $middle
                   12390: 
                   12391: =item $last
                   12392: 
                   12393: =item $gene
                   12394: 
                   12395: =item $usec
                   12396: 
                   12397: =item $end
                   12398: 
                   12399: =item $start
                   12400: 
1.957     raeburn  12401: =item $type
                   12402: 
                   12403: =item $locktype
                   12404: 
                   12405: =item $cid
                   12406: 
                   12407: =item $selfenroll
                   12408: 
                   12409: =item $context
                   12410: 
1.297     matthew  12411: =back
                   12412: 
1.191     harris41 12413: 
                   12414: =item *
                   12415: 
1.243     albertel 12416: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12417: custom role; give a custom role to a user for the level given by URL.  Specify
                   12418: name and domain of role author, and role name
1.191     harris41 12419: 
                   12420: =item *
                   12421: 
1.243     albertel 12422: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12423: 
                   12424: =item *
                   12425: 
1.243     albertel 12426: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12427: 
                   12428: =back
                   12429: 
                   12430: =head2 Course Infomation
                   12431: 
                   12432: =over 4
1.191     harris41 12433: 
                   12434: =item *
                   12435: 
1.1118    foxr     12436: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12437: specified course id, including all environment settings for the
                   12438: course, the description of the course will be in the hash under the
                   12439: key 'description'
1.191     harris41 12440: 
1.1118    foxr     12441: $options is an optional parameter that if supplied is a hash reference that controls
                   12442: what how this function works.  It has the following key/values:
                   12443: 
                   12444: =over 4
                   12445: 
                   12446: =item freshen_cache
                   12447: 
                   12448: If defined, and the environment cache for the course is valid, it is 
                   12449: returned in the returned hash.
                   12450: 
                   12451: =item one_time
                   12452: 
                   12453: If defined, the last cache time is set to _now_
                   12454: 
                   12455: =item user
                   12456: 
                   12457: If defined, the supplied username is used instead of the current user.
                   12458: 
                   12459: 
                   12460: =back
                   12461: 
1.191     harris41 12462: =item *
                   12463: 
1.624     albertel 12464: resdata($name,$domain,$type,@which) : request for current parameter
                   12465: setting for a specific $type, where $type is either 'course' or 'user',
                   12466: @what should be a list of parameters to ask about. This routine caches
                   12467: answers for 5 minutes.
1.243     albertel 12468: 
1.877     foxr     12469: =item *
                   12470: 
                   12471: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12472: data base, returning a hash that is keyed by the resource name and has
                   12473: values that are the resource value.  I believe that the timestamps and
                   12474: versions are also returned.
                   12475: 
1.243     albertel 12476: =back
                   12477: 
                   12478: =head2 Course Modification
                   12479: 
                   12480: =over 4
1.191     harris41 12481: 
                   12482: =item *
                   12483: 
1.243     albertel 12484: writecoursepref($courseid,%prefs) : write preferences (environment
                   12485: database) for a course
1.191     harris41 12486: 
                   12487: =item *
                   12488: 
1.1011    raeburn  12489: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12490: 
                   12491: =item *
                   12492: 
1.1038    raeburn  12493: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12494: 
1.1167    droeschl 12495: =item *
                   12496: 
                   12497: is_course($courseid), is_course($cdom, $cnum)
                   12498: 
                   12499: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12500: two component version $cdom, $cnum. It checks if the specified course exists.
                   12501: 
                   12502: Returns:
                   12503:     undef if the course doesn't exist, otherwise
                   12504:     in scalar context the combined courseid.
                   12505:     in list context the two components of the course identifier, domain and 
                   12506:     courseid.    
                   12507: 
1.243     albertel 12508: =back
                   12509: 
                   12510: =head2 Resource Subroutines
                   12511: 
                   12512: =over 4
1.191     harris41 12513: 
                   12514: =item *
                   12515: 
1.243     albertel 12516: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12517: 
                   12518: =item *
                   12519: 
1.243     albertel 12520: repcopy($filename) : subscribes to the requested file, and attempts to
                   12521: replicate from the owning library server, Might return
1.607     raeburn  12522: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12523: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12524: resource. Expects the local filesystem pathname
                   12525: (/home/httpd/html/res/....)
                   12526: 
                   12527: =back
                   12528: 
                   12529: =head2 Resource Information
                   12530: 
                   12531: =over 4
1.191     harris41 12532: 
                   12533: =item *
                   12534: 
1.243     albertel 12535: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12536: a vairety of different possible values, $varname should be a request
                   12537: string, and the other parameters can be used to specify who and what
                   12538: one is asking about.
                   12539: 
                   12540: Possible values for $varname are environment.lastname (or other item
                   12541: from the envirnment hash), user.name (or someother aspect about the
                   12542: user), resource.0.maxtries (or some other part and parameter of a
                   12543: resource)
1.204     albertel 12544: 
                   12545: =item *
                   12546: 
1.243     albertel 12547: directcondval($number) : get current value of a condition; reads from a state
                   12548: string
1.204     albertel 12549: 
                   12550: =item *
                   12551: 
1.243     albertel 12552: condval($condidx) : value of condition index based on state
1.204     albertel 12553: 
                   12554: =item *
                   12555: 
1.243     albertel 12556: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12557: resource's metadata, $what should be either a specific key, or either
                   12558: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12559: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12560: 
                   12561: this function automatically caches all requests
1.191     harris41 12562: 
                   12563: =item *
                   12564: 
1.243     albertel 12565: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12566: network of library servers; returns file handle of where SQL and regex results
                   12567: will be stored for query
1.191     harris41 12568: 
                   12569: =item *
                   12570: 
1.243     albertel 12571: symbread($filename) : return symbolic list entry (filename argument optional);
                   12572: returns the data handle
1.191     harris41 12573: 
                   12574: =item *
                   12575: 
1.1190    raeburn  12576: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12577: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12578: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12579: on failure, user must be in a course, as it assumes the existence of
                   12580: the course initial hash, and uses $env('request.course.id'}.  The third
                   12581: arg is an optional reference to a scalar.  If this arg is passed in the 
                   12582: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12583: encrypted; otherwise it will be null.  
1.191     harris41 12584: 
                   12585: =item *
                   12586: 
1.243     albertel 12587: symbclean($symb) : removes versions numbers from a symb, returns the
                   12588: cleaned symb
1.191     harris41 12589: 
                   12590: =item *
                   12591: 
1.243     albertel 12592: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12593: course map, user must be in a course for it to work.
1.191     harris41 12594: 
                   12595: =item *
                   12596: 
1.243     albertel 12597: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12598: 
                   12599: =item *
                   12600: 
1.243     albertel 12601: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12602: a random seed, all arguments are optional, if they aren't sent it uses the
                   12603: environment to derive them. Note: if symb isn't sent and it can't get one
                   12604: from &symbread it will use the current time as its return value
1.191     harris41 12605: 
                   12606: =item *
                   12607: 
1.243     albertel 12608: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12609: unfakeable, receipt
1.191     harris41 12610: 
                   12611: =item *
                   12612: 
1.620     albertel 12613: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12614: 
                   12615: =item *
                   12616: 
1.243     albertel 12617: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12618: 
                   12619: =item *
                   12620: 
1.243     albertel 12621: 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 12622: 
                   12623: =item *
                   12624: 
1.243     albertel 12625: 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 12626: 
                   12627: =item *
                   12628: 
1.243     albertel 12629: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12630: 
                   12631: =item *
                   12632: 
1.243     albertel 12633: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12634: forcing spreadsheet to reevaluate the resource scores next time.
                   12635: 
1.1195    raeburn  12636: =item * 
                   12637: 
1.1196    raeburn  12638: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12639: when viewing in course context.
1.1195    raeburn  12640: 
1.1196    raeburn  12641:  input: six args -- filename (decluttered), course number, course domain,
                   12642:                     url, symb (if registered) and group (if this is a 
                   12643:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  12644: 
1.1196    raeburn  12645:  output: array of five scalars --
1.1195    raeburn  12646:          $cfile -- url for file editing if editable on current server
                   12647:          $home -- homeserver of resource (i.e., for author if published,
                   12648:                                           or course if uploaded.).
                   12649:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  12650:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   12651:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  12652: 
                   12653: =item *
                   12654: 
                   12655: is_course_upload($file,$cnum,$cdom)
                   12656: 
                   12657: Used in course context to determine if current file was uploaded to 
                   12658: the course (i.e., would be found in /userfiles/docs on the course's 
                   12659: homeserver.
                   12660: 
                   12661:   input: 3 args -- filename (decluttered), course number and course domain.
                   12662:   output: boolean -- 1 if file was uploaded.
                   12663: 
1.243     albertel 12664: =back
                   12665: 
                   12666: =head2 Storing/Retreiving Data
                   12667: 
                   12668: =over 4
1.191     harris41 12669: 
                   12670: =item *
                   12671: 
1.243     albertel 12672: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12673: for this url; hashref needs to be given and should be a \%hashname; the
                   12674: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12675: be derived from the env
1.191     harris41 12676: 
                   12677: =item *
                   12678: 
1.243     albertel 12679: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12680: uses critical subroutine
1.191     harris41 12681: 
                   12682: =item *
                   12683: 
1.243     albertel 12684: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12685: all args are optional
1.191     harris41 12686: 
                   12687: =item *
                   12688: 
1.717     albertel 12689: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12690: dumps the complete (or key matching regexp) namespace into a hash
                   12691: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12692: normally &store()ed into
                   12693: 
                   12694: $range should be either an integer '100' (give me the first 100
                   12695:                                            matching records)
                   12696:               or be  two integers sperated by a - with no spaces
                   12697:                  '30-50' (give me the 30th through the 50th matching
                   12698:                           records)
                   12699: 
                   12700: 
                   12701: =item *
                   12702: 
                   12703: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12704: replaces a &store() version of data with a replacement set of data
                   12705: for a particular resource in a namespace passed in the $storehash hash 
                   12706: reference
                   12707: 
                   12708: =item *
                   12709: 
1.243     albertel 12710: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12711: works very similar to store/cstore, but all data is stored in a
                   12712: temporary location and can be reset using tmpreset, $storehash should
                   12713: be a hash reference, returns nothing on success
1.191     harris41 12714: 
                   12715: =item *
                   12716: 
1.243     albertel 12717: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12718: similar to restore, but all data is stored in a temporary location and
                   12719: can be reset using tmpreset. Returns a hash of values on success,
                   12720: error string otherwise.
1.191     harris41 12721: 
                   12722: =item *
                   12723: 
1.243     albertel 12724: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12725: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12726: 
                   12727: =item *
                   12728: 
1.243     albertel 12729: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12730: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12731: 
                   12732: =item *
                   12733: 
1.243     albertel 12734: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12735: namesp ($udom and $uname are optional)
1.191     harris41 12736: 
                   12737: =item *
                   12738: 
1.702     albertel 12739: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12740: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12741: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12742: 
1.702     albertel 12743: $range should be either an integer '100' (give me the first 100
                   12744:                                            matching records)
                   12745:               or be  two integers sperated by a - with no spaces
                   12746:                  '30-50' (give me the 30th through the 50th matching
                   12747:                           records)
1.449     matthew  12748: =item *
                   12749: 
                   12750: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12751: $store can be a scalar, an array reference, or if the amount to be 
                   12752: incremented is > 1, a hash reference.
                   12753: 
                   12754: ($udom and $uname are optional)
1.191     harris41 12755: 
                   12756: =item *
                   12757: 
1.243     albertel 12758: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12759: ($udom and $uname are optional)
1.191     harris41 12760: 
                   12761: =item *
                   12762: 
1.243     albertel 12763: cput($namespace,$storehash,$udom,$uname) : critical put
                   12764: ($udom and $uname are optional)
1.191     harris41 12765: 
                   12766: =item *
                   12767: 
1.748     albertel 12768: newput($namespace,$storehash,$udom,$uname) :
                   12769: 
                   12770: Attempts to store the items in the $storehash, but only if they don't
                   12771: currently exist, if this succeeds you can be certain that you have 
                   12772: successfully created a new key value pair in the $namespace db.
                   12773: 
                   12774: 
                   12775: Args:
                   12776:  $namespace: name of database to store values to
                   12777:  $storehash: hashref to store to the db
                   12778:  $udom: (optional) domain of user containing the db
                   12779:  $uname: (optional) name of user caontaining the db
                   12780: 
                   12781: Returns:
                   12782:  'ok' -> succeeded in storing all keys of $storehash
                   12783:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12784:                         least <key> already existed in the db (other
                   12785:                         requested keys may also already exist)
1.967     bisitz   12786:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12787:  'con_lost' -> unable to contact request server
                   12788:  'refused' -> action was not allowed by remote machine
                   12789: 
                   12790: 
                   12791: =item *
                   12792: 
1.243     albertel 12793: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12794: reference filled in from namesp (encrypts the return communication)
                   12795: ($udom and $uname are optional)
1.191     harris41 12796: 
                   12797: =item *
                   12798: 
1.243     albertel 12799: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12800: critical subroutine
                   12801: 
1.806     raeburn  12802: =item *
                   12803: 
1.860     raeburn  12804: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12805: array reference filled in from namespace found in domain level on either
                   12806: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12807: 
                   12808: =item *
                   12809: 
1.860     raeburn  12810: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12811: domain level either on specified domain server ($uhome) or primary domain 
                   12812: server ($udom and $uhome are optional)
1.806     raeburn  12813: 
1.943     raeburn  12814: =item * 
                   12815: 
                   12816: get_domain_defaults($target_domain) : returns hash with defaults for
                   12817: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12818: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12819: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12820: Values are retrieved from cache (if current), or from domain's configuration.db
                   12821: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12822: or lonTabs/domain.tab. 
                   12823: 
                   12824: %domdefaults = &get_auth_defaults($target_domain);
                   12825: 
1.243     albertel 12826: =back
                   12827: 
                   12828: =head2 Network Status Functions
                   12829: 
                   12830: =over 4
1.191     harris41 12831: 
                   12832: =item *
                   12833: 
1.1137    raeburn  12834: dirlist() : return directory list based on URI (first arg).
                   12835: 
                   12836: Inputs: 1 required, 5 optional.
                   12837: 
                   12838: =over
                   12839: 
                   12840: =item 
                   12841: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12842: 
                   12843: =item
                   12844: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12845: 
                   12846: =item
                   12847: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12848: 
                   12849: =item
                   12850: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12851: 
                   12852: =item
                   12853: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12854: 
                   12855: =item 
                   12856: $alternateRoot - path to prepend in place of path from $uri.
                   12857: 
                   12858: =back
                   12859: 
                   12860: Returns: Array of up to two items.
                   12861: 
                   12862: =over
                   12863: 
                   12864: a reference to an array of files/subdirectories
                   12865: 
                   12866: =over
                   12867: 
                   12868: Each element in the array of files/subdirectories is a & separated list of
                   12869: item name and the result of running stat on the item.  If dirlist was requested
                   12870: for a file instead of a directory, the item name will be ''. For a directory 
                   12871: listing, if the item is a metadata file, the element will end &N&M 
                   12872: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12873: default copyright set (1).  
                   12874: 
                   12875: =back
                   12876: 
                   12877: a scalar containing error condition (if encountered).
                   12878: 
                   12879: =over
                   12880: 
                   12881: =item 
                   12882: no_host (no homeserver identified for $username:$domain).
                   12883: 
                   12884: =item 
                   12885: no_such_host (server contacted for listing not identified as valid host).
                   12886: 
                   12887: =item 
                   12888: con_lost (connection to remote server failed).
                   12889: 
                   12890: =item 
                   12891: refused (invalid $username:$domain received on lond side).
                   12892: 
                   12893: =item 
                   12894: no_such_dir (directory at specified path on lond side does not exist). 
                   12895: 
                   12896: =item 
                   12897: empty (directory at specified path on lond side is empty).
                   12898: 
                   12899: =over
                   12900: 
                   12901: This is currently not encountered because the &ls3, &ls2, 
                   12902: &ls (_handler) routines on the lond side do not filter out
                   12903: . and .. from a directory listing. 
                   12904: 
                   12905: =back
                   12906: 
                   12907: =back
                   12908: 
                   12909: =back
1.191     harris41 12910: 
                   12911: =item *
                   12912: 
1.243     albertel 12913: spareserver() : find server with least workload from spare.tab
                   12914: 
1.986     foxr     12915: 
                   12916: =item *
                   12917: 
                   12918: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12919: if there is no corresponding loncapa host.
                   12920: 
1.243     albertel 12921: =back
                   12922: 
1.986     foxr     12923: 
1.243     albertel 12924: =head2 Apache Request
                   12925: 
                   12926: =over 4
1.191     harris41 12927: 
                   12928: =item *
                   12929: 
1.243     albertel 12930: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12931: localhost, posts hash
                   12932: 
                   12933: =back
                   12934: 
                   12935: =head2 Data to String to Data
                   12936: 
                   12937: =over 4
1.191     harris41 12938: 
                   12939: =item *
                   12940: 
1.243     albertel 12941: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12942: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12943: 
                   12944: =item *
                   12945: 
1.243     albertel 12946: hashref2str($hashref) : convert a hashref into a string complete with
                   12947: escaping and '=' and '&' separators, supports elements that are
                   12948: arrayrefs and hashrefs
1.191     harris41 12949: 
                   12950: =item *
                   12951: 
1.243     albertel 12952: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12953: with escaping and '&' separators, supports elements that are arrayrefs
                   12954: and hashrefs
1.191     harris41 12955: 
                   12956: =item *
                   12957: 
1.243     albertel 12958: str2hash($string) : convert string to hash using unescaping and
                   12959: splitting on '=' and '&', supports elements that are arrayrefs and
                   12960: hashrefs
1.191     harris41 12961: 
                   12962: =item *
                   12963: 
1.243     albertel 12964: str2array($string) : convert string to hash using unescaping and
                   12965: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12966: 
                   12967: =back
                   12968: 
                   12969: =head2 Logging Routines
                   12970: 
                   12971: 
                   12972: These routines allow one to make log messages in the lonnet.log and
                   12973: lonnet.perm logfiles.
1.191     harris41 12974: 
1.1119    foxr     12975: =over 4
                   12976: 
1.191     harris41 12977: =item *
                   12978: 
1.243     albertel 12979: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12980: 
                   12981: =item *
                   12982: 
1.243     albertel 12983: logthis() : append message to the normal lonnet.log file, it gets
                   12984: preiodically rolled over and deleted.
1.191     harris41 12985: 
                   12986: =item *
                   12987: 
1.243     albertel 12988: logperm() : append a permanent message to lonnet.perm.log, this log
                   12989: file never gets deleted by any automated portion of the system, only
                   12990: messages of critical importance should go in here.
                   12991: 
1.1119    foxr     12992: 
1.243     albertel 12993: =back
                   12994: 
                   12995: =head2 General File Helper Routines
                   12996: 
                   12997: =over 4
1.191     harris41 12998: 
                   12999: =item *
                   13000: 
1.481     raeburn  13001: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13002: (a) files in /uploaded
                   13003:   (i) If a local copy of the file exists - 
                   13004:       compares modification date of local copy with last-modified date for 
                   13005:       definitive version stored on home server for course. If local copy is 
                   13006:       stale, requests a new version from the home server and stores it. 
                   13007:       If the original has been removed from the home server, then local copy 
                   13008:       is unlinked.
                   13009:   (ii) If local copy does not exist -
                   13010:       requests the file from the home server and stores it. 
                   13011:   
                   13012:   If $caller is 'uploadrep':  
                   13013:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13014:     for request for files originally uploaded via DOCS. 
                   13015:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13016:   
                   13017:   Otherwise:
                   13018:      This indicates a call from the content generation phase of the request.
                   13019:      -  returns the entire contents of the file or -1.
                   13020:      
                   13021: (b) files in /res
                   13022:    - returns the entire contents of a file or -1; 
                   13023:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13024: 
1.712     albertel 13025: 
                   13026: =item *
                   13027: 
                   13028: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13029:                   reference
                   13030: 
                   13031: returns either a stat() list of data about the file or an empty list
                   13032: if the file doesn't exist or couldn't find out about it (connection
                   13033: problems or user unknown)
                   13034: 
1.191     harris41 13035: =item *
                   13036: 
1.243     albertel 13037: filelocation($dir,$file) : returns file system location of a file
                   13038: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13039: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13040: and a file of ../bob will become /a/bob)
1.191     harris41 13041: 
                   13042: =item *
                   13043: 
                   13044: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13045: filelocation except for hrefs
                   13046: 
                   13047: =item *
                   13048: 
                   13049: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13050: 
1.243     albertel 13051: =back
                   13052: 
1.608     albertel 13053: =head2 Usererfile file routines (/uploaded*)
                   13054: 
                   13055: =over 4
                   13056: 
                   13057: =item *
                   13058: 
                   13059: userfileupload(): main rotine for putting a file in a user or course's
                   13060:                   filespace, arguments are,
                   13061: 
1.620     albertel 13062:  formname - required - this is the name of the element in $env where the
1.608     albertel 13063:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13064:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13065:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13066:  context - if coursedoc, store the file in the course of the active role
                   13067:              of the current user; 
                   13068:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13069:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13070:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13071:          if undefined, it will be placed in "unknown"
                   13072: 
                   13073:  (This routine calls clean_filename() to remove any dangerous
                   13074:  characters from the filename, and then calls finuserfileupload() to
                   13075:  complete the transaction)
                   13076: 
                   13077:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13078:  and /adm/notfound.html if unsuccessful
                   13079: 
                   13080: =item *
                   13081: 
                   13082: clean_filename(): routine for cleaing a filename up for storage in
                   13083:                  userfile space, argument is:
                   13084: 
                   13085:  filename - proposed filename
                   13086: 
                   13087: returns: the new clean filename
                   13088: 
                   13089: =item *
                   13090: 
1.1090    raeburn  13091: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13092: userspace, probably shouldn't be called directly
                   13093: 
                   13094:   docuname: username or courseid of destination for the file
                   13095:   docudom: domain of user/course of destination for the file
                   13096:   formname: same as for userfileupload()
1.1090    raeburn  13097:   fname: filename (including subdirectories) for the file
                   13098:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13099:   allfiles: reference to hash used to store objects found by parser
                   13100:   codebase: reference to hash used for codebases of java objects found by parser
                   13101:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13102:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13103:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13104:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13105:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13106:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13107:   mimetype: reference to scalar to accommodate mime type determined
                   13108:             from File::MMagic if $parser = parse.
1.608     albertel 13109: 
                   13110:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13111:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13112:  was 'overwrite').
                   13113:  
1.608     albertel 13114: 
                   13115: =item *
                   13116: 
                   13117: renameuserfile(): renames an existing userfile to a new name
                   13118: 
                   13119:   Args:
                   13120:    docuname: username or courseid of destination for the file
                   13121:    docudom: domain of user/course of destination for the file
                   13122:    old: current file name (including any subdirs under userfiles)
                   13123:    new: desired file name (including any subdirs under userfiles)
                   13124: 
                   13125: =item *
                   13126: 
                   13127: mkdiruserfile(): creates a directory is a userfiles dir
                   13128: 
                   13129:   Args:
                   13130:    docuname: username or courseid of destination for the file
                   13131:    docudom: domain of user/course of destination for the file
                   13132:    dir: dir to create (including any subdirs under userfiles)
                   13133: 
                   13134: =item *
                   13135: 
                   13136: removeuserfile(): removes a file that exists in userfiles
                   13137: 
                   13138:   Args:
                   13139:    docuname: username or courseid of destination for the file
                   13140:    docudom: domain of user/course of destination for the file
                   13141:    fname: filname to delete (including any subdirs under userfiles)
                   13142: 
                   13143: =item *
                   13144: 
                   13145: removeuploadedurl(): convience function for removeuserfile()
                   13146: 
                   13147:   Args:
                   13148:    url:  a full /uploaded/... url to delete
                   13149: 
1.747     albertel 13150: =item * 
                   13151: 
                   13152: get_portfile_permissions():
                   13153:   Args:
                   13154:     domain: domain of user or course contain the portfolio files
                   13155:     user: name of user or num of course contain the portfolio files
                   13156:   Returns:
                   13157:     hashref of a dump of the proper file_permissions.db
                   13158:    
                   13159: 
                   13160: =item * 
                   13161: 
                   13162: get_access_controls():
                   13163: 
                   13164: Args:
                   13165:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13166:   group: (optional) the group you want the files associated with
                   13167:   file: (optional) the file you want access info on
                   13168: 
                   13169: Returns:
1.749     raeburn  13170:     a hash (keys are file names) of hashes containing
                   13171:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13172:         values are XML containing access control settings (see below) 
1.747     albertel 13173: 
                   13174: Internal notes:
                   13175: 
1.749     raeburn  13176:  access controls are stored in file_permissions.db as key=value pairs.
                   13177:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13178:         where scope -> public,guest,course,group,domains or users.
                   13179:               end -> UNIX time for end of access (0 -> no end date)
                   13180:               start -> UNIX time for start of access
                   13181: 
                   13182:     value -> XML description of access control
                   13183:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13184:             <start></start>
                   13185:             <end></end>
                   13186: 
                   13187:             <password></password>  for scope type = guest
                   13188: 
                   13189:             <domain></domain>     for scope type = course or group
                   13190:             <number></number>
                   13191:             <roles id="">
                   13192:              <role></role>
                   13193:              <access></access>
                   13194:              <section></section>
                   13195:              <group></group>
                   13196:             </roles>
                   13197: 
                   13198:             <dom></dom>         for scope type = domains
                   13199: 
                   13200:             <users>             for scope type = users
                   13201:              <user>
                   13202:               <uname></uname>
                   13203:               <udom></udom>
                   13204:              </user>
                   13205:             </users>
                   13206:            </scope> 
                   13207:               
                   13208:  Access data is also aggregated for each file in an additional key=value pair:
                   13209:  key -> path to file/file_name\0accesscontrol 
                   13210:  value -> reference to hash
                   13211:           hash contains key = value pairs
                   13212:           where key = uniqueID:scope_end_start
                   13213:                 value = UNIX time record was last updated
                   13214: 
                   13215:           Used to improve speed of look-ups of access controls for each file.  
                   13216:  
                   13217:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13218: 
                   13219: modify_access_controls():
                   13220: 
                   13221: Modifies access controls for a portfolio file
                   13222: Args
                   13223: 1. file name
                   13224: 2. reference to hash of required changes,
                   13225: 3. domain
                   13226: 4. username
                   13227:   where domain,username are the domain of the portfolio owner 
                   13228:   (either a user or a course) 
                   13229: 
                   13230: Returns:
                   13231: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13232: 2. result of deletions ('ok' or 'error', with error message).
                   13233: 3. reference to hash of any new or updated access controls.
                   13234: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13235:    key = integer (inbound ID)
                   13236:    value = uniqueID  
1.747     albertel 13237: 
1.608     albertel 13238: =back
                   13239: 
1.243     albertel 13240: =head2 HTTP Helper Routines
                   13241: 
                   13242: =over 4
                   13243: 
1.191     harris41 13244: =item *
                   13245: 
                   13246: escape() : unpack non-word characters into CGI-compatible hex codes
                   13247: 
                   13248: =item *
                   13249: 
                   13250: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13251: 
1.243     albertel 13252: =back
                   13253: 
                   13254: =head1 PRIVATE SUBROUTINES
                   13255: 
                   13256: =head2 Underlying communication routines (Shouldn't call)
                   13257: 
                   13258: =over 4
                   13259: 
                   13260: =item *
                   13261: 
                   13262: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13263: 
                   13264: =item *
                   13265: 
                   13266: reply() : uses subreply to send a message to remote machine, logs all failures
                   13267: 
                   13268: =item *
                   13269: 
                   13270: critical() : passes a critical message to another server; if cannot
                   13271: get through then place message in connection buffer directory and
                   13272: returns con_delayed, if incapable of saving message, returns
                   13273: con_failed
                   13274: 
                   13275: =item *
                   13276: 
                   13277: reconlonc() : tries to reconnect lonc client processes.
                   13278: 
                   13279: =back
                   13280: 
                   13281: =head2 Resource Access Logging
                   13282: 
                   13283: =over 4
                   13284: 
                   13285: =item *
                   13286: 
                   13287: flushcourselogs() : flush (save) buffer logs and access logs
                   13288: 
                   13289: =item *
                   13290: 
                   13291: courselog($what) : save message for course in hash
                   13292: 
                   13293: =item *
                   13294: 
                   13295: courseacclog($what) : save message for course using &courselog().  Perform
                   13296: special processing for specific resource types (problems, exams, quizzes, etc).
                   13297: 
1.191     harris41 13298: =item *
                   13299: 
                   13300: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13301: as a PerlChildExitHandler
1.243     albertel 13302: 
                   13303: =back
                   13304: 
                   13305: =head2 Other
                   13306: 
                   13307: =over 4
                   13308: 
                   13309: =item *
                   13310: 
                   13311: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13312: 
                   13313: =back
                   13314: 
                   13315: =cut
1.877     foxr     13316: 

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