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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1221  ! raeburn     4: # $Id: lonnet.pm,v 1.1220 2013/04/24 02:44:05 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1213    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.539     albertel   95: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.550     foxr      108: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.993     raeburn   232: sub get_server_loncaparev {
1.1073    raeburn   233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   234:     if (defined($lonhost)) {
                    235:         if (!defined(&hostname($lonhost))) {
                    236:             undef($lonhost);
                    237:         }
                    238:     }
                    239:     if (!defined($lonhost)) {
                    240:         if (defined(&domain($dom,'primary'))) {
                    241:             $lonhost=&domain($dom,'primary');
                    242:             if ($lonhost eq 'no_host') {
                    243:                 undef($lonhost);
                    244:             }
                    245:         }
                    246:     }
                    247:     if (defined($lonhost)) {
1.1073    raeburn   248:         my $cachetime = 12*3600;
                    249:         if (!$ignore_cache) {
                    250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    251:             if (defined($cached)) {
                    252:                 return $loncaparev;
                    253:             }
                    254:         }
                    255:         my ($answer,$loncaparev);
                    256:         my @ids=&current_machine_ids();
                    257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    258:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   260:                 $loncaparev = $1;
                    261:             }
                    262:         } else {
                    263:             $answer = &reply('serverloncaparev',$lonhost);
                    264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    265:                 if ($caller eq 'loncron') {
                    266:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   267:                     $ua->timeout(4);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
                    270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
                    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:     }
1.1213    raeburn   637:     if (($r->user() eq '') && ($apache >= 2.4)) {
1.1212    raeburn   638:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    639:             $r->user($disk_env{'user.name'});
                    640:         } else {
                    641:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    642:         }
                    643:     }
1.916     albertel  644:     return $handle;
                    645: }
                    646: 
1.830     albertel  647: sub timed_flock {
                    648:     my ($file,$lock_type) = @_;
                    649:     my $failed=0;
                    650:     eval {
                    651: 	local $SIG{__DIE__}='DEFAULT';
                    652: 	local $SIG{ALRM}=sub {
                    653: 	    $failed=1;
                    654: 	    die("failed lock");
                    655: 	};
                    656: 	alarm(13);
                    657: 	flock($file,$lock_type);
                    658: 	alarm(0);
                    659:     };
                    660:     if ($failed) {
                    661: 	return undef;
                    662:     } else {
                    663: 	return 1;
                    664:     }
                    665: }
                    666: 
1.5       www       667: # ---------------------------------------------------------- Append Environment
                    668: 
                    669: sub appenv {
1.949     raeburn   670:     my ($newenv,$roles) = @_;
                    671:     if (ref($newenv) eq 'HASH') {
                    672:         foreach my $key (keys(%{$newenv})) {
                    673:             my $refused = 0;
                    674: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    675:                 $refused = 1;
                    676:                 if (ref($roles) eq 'ARRAY') {
                    677:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    678:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    679:                         $refused = 0;
                    680:                     }
                    681:                 }
                    682:             }
                    683:             if ($refused) {
                    684:                 &logthis("<font color=\"blue\">WARNING: ".
                    685:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    686:                          .'</font>');
                    687: 	        delete($newenv->{$key});
                    688:             } else {
                    689:                 $env{$key}=$newenv->{$key};
                    690:             }
                    691:         }
                    692:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    693:         if ($opened
                    694: 	    && &timed_flock($env_file,LOCK_EX)
                    695: 	    &&
                    696: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    697: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    698: 	    while (my ($key,$value) = each(%{$newenv})) {
                    699: 	        $disk_env{$key} = $value;
                    700: 	    }
                    701: 	    untie(%disk_env);
1.35      www       702:         }
1.191     harris41  703:     }
1.56      www       704:     return 'ok';
                    705: }
                    706: # ----------------------------------------------------- Delete from Environment
                    707: 
                    708: sub delenv {
1.1104    raeburn   709:     my ($delthis,$regexp,$roles) = @_;
                    710:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    711:         my $refused = 1;
                    712:         if (ref($roles) eq 'ARRAY') {
                    713:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    714:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    715:                 $refused = 0;
                    716:             }
                    717:         }
                    718:         if ($refused) {
                    719:             &logthis("<font color=\"blue\">WARNING: ".
                    720:                      "Attempt to delete from environment ".$delthis);
                    721:             return 'error';
                    722:         }
1.56      www       723:     }
1.917     albertel  724:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    725:     if ($opened
1.915     albertel  726: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  727: 	&&
                    728: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    729: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  730: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   731: 	    if ($regexp) {
                    732:                 if ($key=~/^$delthis/) {
                    733:                     delete($env{$key});
                    734:                     delete($disk_env{$key});
                    735:                 } 
                    736:             } else {
                    737:                 if ($key=~/^\Q$delthis\E/) {
                    738: 		    delete($env{$key});
                    739: 		    delete($disk_env{$key});
                    740: 	        }
                    741:             }
1.448     albertel  742: 	}
1.783     albertel  743: 	untie(%disk_env);
1.5       www       744:     }
                    745:     return 'ok';
1.369     albertel  746: }
                    747: 
1.790     albertel  748: sub get_env_multiple {
                    749:     my ($name) = @_;
                    750:     my @values;
                    751:     if (defined($env{$name})) {
                    752:         # exists is it an array
                    753:         if (ref($env{$name})) {
                    754:             @values=@{ $env{$name} };
                    755:         } else {
                    756:             $values[0]=$env{$name};
                    757:         }
                    758:     }
                    759:     return(@values);
                    760: }
                    761: 
1.958     www       762: # ------------------------------------------------------------------- Locking
                    763: 
                    764: sub set_lock {
                    765:     my ($text)=@_;
                    766:     $locknum++;
                    767:     my $id=$$.'-'.$locknum;
                    768:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    769:              'session.lock.'.$id => $text});
                    770:     return $id;
                    771: }
                    772: 
                    773: sub get_locks {
                    774:     my $num=0;
                    775:     my %texts=();
                    776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    777:        if ($lock=~/\w/) {
                    778:           $num++;
                    779:           $texts{$lock}=$env{'session.lock.'.$lock};
                    780:        }
                    781:    }
                    782:    return ($num,%texts);
                    783: }
                    784: 
                    785: sub remove_lock {
                    786:     my ($id)=@_;
                    787:     my $newlocks='';
                    788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    789:        if (($lock=~/\w/) && ($lock ne $id)) {
                    790:           $newlocks.=','.$lock;
                    791:        }
                    792:     }
                    793:     &appenv({'session.locks' => $newlocks});
                    794:     &delenv('session.lock.'.$id);
                    795: }
                    796: 
                    797: sub remove_all_locks {
                    798:     my $activelocks=$env{'session.locks'};
                    799:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    800:        if ($lock=~/\w/) {
                    801:           &remove_lock($lock);
                    802:        }
                    803:     }
                    804: }
                    805: 
                    806: 
1.369     albertel  807: # ------------------------------------------ Find out current server userload
                    808: sub userload {
                    809:     my $numusers=0;
                    810:     {
                    811: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    812: 	my $filename;
                    813: 	my $curtime=time;
                    814: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  815: 	    next if ($filename eq '.' || $filename eq '..');
                    816: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  817: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  818: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  819: 	}
                    820: 	closedir(LONIDS);
                    821:     }
                    822:     my $userloadpercent=0;
                    823:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    824:     if ($maxuserload) {
1.371     albertel  825: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  826:     }
1.372     albertel  827:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  828:     return $userloadpercent;
1.283     www       829: }
                    830: 
1.1       albertel  831: # ------------------------------ Find server with least workload from spare.tab
1.11      www       832: 
1.1       albertel  833: sub spareserver {
1.1083    raeburn   834:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  835:     my $spare_server;
1.370     albertel  836:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  837:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    838:                                                      :  $userloadpercent;
1.1083    raeburn   839:     my ($uint_dom,$remotesessions);
                    840:     if (($udom ne '') && (&domain($udom) ne '')) {
                    841:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    842:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    843:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    844:         $remotesessions = $udomdefaults{'remotesessions'};
                    845:     }
1.1123    raeburn   846:     my $spareshash = &this_host_spares($udom);
                    847:     if (ref($spareshash) eq 'HASH') {
                    848:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    849:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    850:                 if ($uint_dom) {
                    851:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    852:                                                  $try_server));
                    853:                 }
                    854: 	        ($spare_server, $lowest_load) =
                    855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:             }
1.1083    raeburn   857:         }
1.784     albertel  858: 
1.1123    raeburn   859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    860: 
                    861:         if (!$found_server) {
                    862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    864:                     if ($uint_dom) {
                    865:                         next unless (&spare_can_host($udom,$uint_dom,
                    866:                                                      $remotesessions,$try_server));
                    867:                     }
                    868: 	            ($spare_server, $lowest_load) =
                    869: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    870:                 }
                    871: 	    }
                    872:         }
1.784     albertel  873:     }
                    874: 
                    875:     if (!$want_server_name) {
1.968     raeburn   876:         my $protocol = 'http';
                    877:         if ($protocol{$spare_server} eq 'https') {
                    878:             $protocol = $protocol{$spare_server};
                    879:         }
1.1001    raeburn   880:         if (defined($spare_server)) {
                    881:             my $hostname = &hostname($spare_server);
1.1083    raeburn   882:             if (defined($hostname)) {
1.1001    raeburn   883: 	        $spare_server = $protocol.'://'.$hostname;
                    884:             }
                    885:         }
1.784     albertel  886:     }
                    887:     return $spare_server;
                    888: }
                    889: 
                    890: sub compare_server_load {
                    891:     my ($try_server, $spare_server, $lowest_load) = @_;
                    892: 
                    893:     my $loadans     = &reply('load',    $try_server);
                    894:     my $userloadans = &reply('userload',$try_server);
                    895: 
                    896:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   897: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  898:     }
                    899: 
                    900:     my $load;
                    901:     if ($loadans =~ /\d/) {
                    902: 	if ($userloadans =~ /\d/) {
                    903: 	    #both are numbers, pick the bigger one
                    904: 	    $load = ($loadans > $userloadans) ? $loadans 
                    905: 		                              : $userloadans;
1.411     albertel  906: 	} else {
1.784     albertel  907: 	    $load = $loadans;
1.411     albertel  908: 	}
1.784     albertel  909:     } else {
                    910: 	$load = $userloadans;
                    911:     }
                    912: 
                    913:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    914: 	$spare_server = $try_server;
                    915: 	$lowest_load  = $load;
1.370     albertel  916:     }
1.784     albertel  917:     return ($spare_server,$lowest_load);
1.202     matthew   918: }
1.914     albertel  919: 
                    920: # --------------------------- ask offload servers if user already has a session
                    921: sub find_existing_session {
                    922:     my ($udom,$uname) = @_;
1.1123    raeburn   923:     my $spareshash = &this_host_spares($udom);
                    924:     if (ref($spareshash) eq 'HASH') {
                    925:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    926:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    927:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    928:             }
                    929:         }
                    930:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    931:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    932:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    933:             }
                    934:         }
1.914     albertel  935:     }
                    936:     return;
                    937: }
                    938: 
                    939: # -------------------------------- ask if server already has a session for user
                    940: sub has_user_session {
                    941:     my ($lonid,$udom,$uname) = @_;
                    942:     my $result = &reply(join(':','userhassession',
                    943: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    944:     return 1 if ($result eq 'ok');
                    945: 
                    946:     return 0;
                    947: }
                    948: 
1.1076    raeburn   949: # --------- determine least loaded server in a user's domain which allows login
                    950: 
                    951: sub choose_server {
1.1115    raeburn   952:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   953:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   954:     my %servers = &get_servers($udom);
1.1076    raeburn   955:     my $lowest_load = 30000;
1.1151    raeburn   956:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   957:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   958:         my $loginvia;
                    959:         if ($checkloginvia) {
                    960:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   961:             if ($loginvia) {
                    962:                 my ($server,$path) = split(/:/,$loginvia);
                    963:                 ($login_host, $lowest_load) =
                    964:                     &compare_server_load($server, $login_host, $lowest_load);
                    965:                 if ($login_host eq $server) {
                    966:                     $portal_path = $path;
1.1151    raeburn   967:                     $isredirect = 1;
1.1116    raeburn   968:                 }
                    969:             } else {
                    970:                 ($login_host, $lowest_load) =
                    971:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    972:                 if ($login_host eq $lonhost) {
                    973:                     $portal_path = '';
1.1151    raeburn   974:                     $isredirect = ''; 
1.1116    raeburn   975:                 }
                    976:             }
                    977:         } else {
1.1076    raeburn   978:             ($login_host, $lowest_load) =
1.1116    raeburn   979:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   980:         }
                    981:     }
                    982:     if ($login_host ne '') {
1.1116    raeburn   983:         $hostname = &hostname($login_host);
1.1076    raeburn   984:     }
1.1151    raeburn   985:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   986: }
                    987: 
1.202     matthew   988: # --------------------------------------------- Try to change a user's password
                    989: 
                    990: sub changepass {
1.799     raeburn   991:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   992:     $currentpass = &escape($currentpass);
                    993:     $newpass     = &escape($newpass);
1.1030    raeburn   994:     my $lonhost = $perlvar{'lonHostID'};
                    995:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   996: 		       $server);
                    997:     if (! $answer) {
                    998: 	&logthis("No reply on password change request to $server ".
                    999: 		 "by $uname in domain $udom.");
                   1000:     } elsif ($answer =~ "^ok") {
                   1001:         &logthis("$uname in $udom successfully changed their password ".
                   1002: 		 "on $server.");
                   1003:     } elsif ($answer =~ "^pwchange_failure") {
                   1004: 	&logthis("$uname in $udom was unable to change their password ".
                   1005: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1006: 		 "or pwchange");
                   1007:     } elsif ($answer =~ "^non_authorized") {
                   1008:         &logthis("$uname in $udom did not get their password correct when ".
                   1009: 		 "attempting to change it on $server.");
                   1010:     } elsif ($answer =~ "^auth_mode_error") {
                   1011:         &logthis("$uname in $udom attempted to change their password despite ".
                   1012: 		 "not being locally or internally authenticated on $server.");
                   1013:     } elsif ($answer =~ "^unknown_user") {
                   1014:         &logthis("$uname in $udom attempted to change their password ".
                   1015: 		 "on $server but were unable to because $server is not ".
                   1016: 		 "their home server.");
                   1017:     } elsif ($answer =~ "^refused") {
                   1018: 	&logthis("$server refused to change $uname in $udom password because ".
                   1019: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1020:     } elsif ($answer =~ "invalid_client") {
                   1021:         &logthis("$server refused to change $uname in $udom password because ".
                   1022:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1023:     }
                   1024:     return $answer;
1.1       albertel 1025: }
                   1026: 
1.169     harris41 1027: # ----------------------- Try to determine user's current authentication scheme
                   1028: 
                   1029: sub queryauthenticate {
                   1030:     my ($uname,$udom)=@_;
1.456     albertel 1031:     my $uhome=&homeserver($uname,$udom);
                   1032:     if (!$uhome) {
                   1033: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1034: 	return 'no_host';
                   1035:     }
                   1036:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1037:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1038: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1039:     }
1.456     albertel 1040:     return $answer;
1.169     harris41 1041: }
                   1042: 
1.1       albertel 1043: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1044: 
1.1       albertel 1045: sub authenticate {
1.1073    raeburn  1046:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1047:     $upass=&escape($upass);
                   1048:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1049:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1050:     my $newhome;
1.836     www      1051:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1052: # Maybe the machine was offline and only re-appeared again recently?
                   1053:         &reconlonc();
                   1054: # One more
1.952     raeburn  1055: 	$uhome=&homeserver($uname,$udom,1);
                   1056:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1057:             if (defined(&domain($udom,'primary'))) {
                   1058:                 $newhome=&domain($udom,'primary');
                   1059:             }
                   1060:             if ($newhome ne '') {
                   1061:                 $uhome = $newhome;
                   1062:             }
                   1063:         }
1.836     www      1064: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1065: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1066: 	    return 'no_host';
                   1067:         }
1.1       albertel 1068:     }
1.1073    raeburn  1069:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1070:     if ($answer eq 'authorized') {
1.952     raeburn  1071:         if ($newhome) {
                   1072:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1073:             return 'no_account_on_host'; 
                   1074:         } else {
                   1075:             &logthis("User $uname at $udom authorized by $uhome");
                   1076:             return $uhome;
                   1077:         }
1.471     albertel 1078:     }
                   1079:     if ($answer eq 'non_authorized') {
                   1080: 	&logthis("User $uname at $udom rejected by $uhome");
                   1081: 	return 'no_host'; 
1.9       www      1082:     }
1.471     albertel 1083:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1084:     return 'no_host';
                   1085: }
                   1086: 
1.1073    raeburn  1087: sub can_host_session {
1.1074    raeburn  1088:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1089:     my $canhost = 1;
1.1074    raeburn  1090:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1091:     if (ref($remotesessions) eq 'HASH') {
                   1092:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1094:                 $canhost = 0;
                   1095:             } else {
                   1096:                 $canhost = 1;
                   1097:             }
                   1098:         }
                   1099:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1100:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1101:                 $canhost = 1;
                   1102:             } else {
                   1103:                 $canhost = 0;
                   1104:             }
                   1105:         }
                   1106:         if ($canhost) {
                   1107:             if ($remotesessions->{'version'} ne '') {
                   1108:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1109:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1110:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1111:                         my $major = $1;
                   1112:                         my $minor = $2;
                   1113:                         if (($major < $reqmajor ) ||
                   1114:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1115:                             $canhost = 0;
                   1116:                         }
                   1117:                     } else {
                   1118:                         $canhost = 0;
                   1119:                     }
                   1120:                 }
                   1121:             }
                   1122:         }
                   1123:     }
                   1124:     if ($canhost) {
                   1125:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1126:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1127:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1128:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1129:                 if (($uint_dom ne '') && 
                   1130:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1131:                     $canhost = 0;
                   1132:                 } else {
                   1133:                     $canhost = 1;
                   1134:                 }
                   1135:             }
                   1136:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1137:                 if (($uint_dom ne '') && 
                   1138:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1139:                     $canhost = 1;
                   1140:                 } else {
                   1141:                     $canhost = 0;
                   1142:                 }
                   1143:             }
                   1144:         }
                   1145:     }
                   1146:     return $canhost;
                   1147: }
                   1148: 
1.1083    raeburn  1149: sub spare_can_host {
                   1150:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1151:     my $canhost=1;
                   1152:     my @intdoms;
                   1153:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1154:     if (ref($internet_names) eq 'ARRAY') {
                   1155:         @intdoms = @{$internet_names};
                   1156:     }
                   1157:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1158:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1159:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1160:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1161:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1162:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1163:                                      $remotesessions,
                   1164:                                      $defdomdefaults{'hostedsessions'});
                   1165:     }
                   1166:     return $canhost;
                   1167: }
                   1168: 
1.1123    raeburn  1169: sub this_host_spares {
                   1170:     my ($dom) = @_;
1.1126    raeburn  1171:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1172:     my @hosts = &current_machine_ids();
                   1173:     foreach my $lonhost (@hosts) {
                   1174:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1175:             $dom_in_use = $dom;
                   1176:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1177:             last;
                   1178:         }
                   1179:     }
1.1126    raeburn  1180:     if ($dom_in_use ne '') {
                   1181:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1182:     }
                   1183:     if (ref($result) ne 'HASH') {
                   1184:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1185:         $dom_in_use = &host_domain($lonhost_in_use);
                   1186:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1187:         if (ref($result) ne 'HASH') {
                   1188:             $result = \%spareid;
                   1189:         }
                   1190:     }
                   1191:     return $result;
                   1192: }
                   1193: 
                   1194: sub spares_for_offload  {
                   1195:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1196:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1197:     if (defined($cached)) {
                   1198:         return $result;
                   1199:     } else {
1.1126    raeburn  1200:         my $cachetime = 60*60*24;
                   1201:         my %domconfig =
                   1202:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1203:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1204:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1205:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1206:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1207:                 }
                   1208:             }
                   1209:         }
                   1210:     }
1.1126    raeburn  1211:     return;
1.1123    raeburn  1212: }
                   1213: 
1.1129    raeburn  1214: sub get_lonbalancer_config {
                   1215:     my ($servers) = @_;
                   1216:     my ($currbalancer,$currtargets);
                   1217:     if (ref($servers) eq 'HASH') {
                   1218:         foreach my $server (keys(%{$servers})) {
                   1219:             my %what = (
                   1220:                          spareid => 1,
                   1221:                          perlvar => 1,
                   1222:                        );
                   1223:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1224:             if ($result eq 'ok') {
                   1225:                 if (ref($returnhash) eq 'HASH') {
                   1226:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1227:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1228:                             $currbalancer = $server;
                   1229:                             $currtargets = {};
                   1230:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1231:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1232:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1233:                                 }
                   1234:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1235:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1236:                                 }
                   1237:                             }
                   1238:                             last;
                   1239:                         }
                   1240:                     }
                   1241:                 }
                   1242:             }
                   1243:         }
                   1244:     }
                   1245:     return ($currbalancer,$currtargets);
                   1246: }
                   1247: 
                   1248: sub check_loadbalancing {
                   1249:     my ($uname,$udom) = @_;
1.1191    raeburn  1250:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1251:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1252:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1253:     my @hosts = &current_machine_ids();
1.1129    raeburn  1254:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1255:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1256:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1257:     my $serverhomedom = &host_domain($lonhost);
                   1258: 
                   1259:     my $cachetime = 60*60*24;
                   1260: 
                   1261:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1262:         $dom_in_use = $udom;
                   1263:         $homeintdom = 1;
                   1264:     } else {
                   1265:         $dom_in_use = $serverhomedom;
                   1266:     }
                   1267:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1268:     unless (defined($cached)) {
                   1269:         my %domconfig =
                   1270:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1271:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1272:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1273:         }
                   1274:     }
                   1275:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1276:         ($is_balancer,$currtargets,$currrules) = 
                   1277:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1278:         if ($is_balancer) {
                   1279:             if (ref($currrules) eq 'HASH') {
                   1280:                 if ($homeintdom) {
                   1281:                     if ($uname ne '') {
                   1282:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1283:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1284:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1285:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1286:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1287:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1288:                             }
                   1289:                         }
                   1290:                         if ($rule_in_effect eq '') {
                   1291:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1292:                             if ($userenv{'inststatus'} ne '') {
                   1293:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1294:                                 my ($othertitle,$usertypes,$types) =
                   1295:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1296:                                 if (ref($types) eq 'ARRAY') {
                   1297:                                     foreach my $type (@{$types}) {
                   1298:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1299:                                             if (exists($currrules->{$type})) {
                   1300:                                                 $rule_in_effect = $currrules->{$type};
                   1301:                                             }
                   1302:                                         }
                   1303:                                     }
                   1304:                                 }
                   1305:                             } else {
                   1306:                                 if (exists($currrules->{'default'})) {
                   1307:                                     $rule_in_effect = $currrules->{'default'};
                   1308:                                 }
                   1309:                             }
                   1310:                         }
                   1311:                     } else {
                   1312:                         if (exists($currrules->{'default'})) {
                   1313:                             $rule_in_effect = $currrules->{'default'};
                   1314:                         }
                   1315:                     }
                   1316:                 } else {
                   1317:                     if ($currrules->{'_LC_external'} ne '') {
                   1318:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1319:                     }
                   1320:                 }
                   1321:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1322:                                                        $uname,$udom);
                   1323:             }
                   1324:         }
                   1325:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1326:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1327:         unless (defined($cached)) {
                   1328:             my %domconfig =
                   1329:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1330:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1331:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1332:             }
                   1333:         }
                   1334:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1335:             ($is_balancer,$currtargets,$currrules) = 
                   1336:                 &check_balancer_result($result,@hosts);
                   1337:             if ($is_balancer) {
1.1129    raeburn  1338:                 if (ref($currrules) eq 'HASH') {
                   1339:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1340:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1341:                     }
                   1342:                 }
                   1343:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1344:                                                        $uname,$udom);
                   1345:             }
                   1346:         } else {
                   1347:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1348:                 $is_balancer = 1;
                   1349:                 $offloadto = &this_host_spares($dom_in_use);
                   1350:             }
                   1351:         }
                   1352:     } else {
                   1353:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1354:             $is_balancer = 1;
                   1355:             $offloadto = &this_host_spares($dom_in_use);
                   1356:         }
                   1357:     }
1.1176    raeburn  1358:     if ($is_balancer) {
                   1359:         my $lowest_load = 30000;
                   1360:         if (ref($offloadto) eq 'HASH') {
                   1361:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1362:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1363:                     ($otherserver,$lowest_load) =
                   1364:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1365:                 }
1.1129    raeburn  1366:             }
1.1176    raeburn  1367:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1368: 
1.1176    raeburn  1369:             if (!$found_server) {
                   1370:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1371:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1372:                         ($otherserver,$lowest_load) =
                   1373:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1374:                     }
                   1375:                 }
                   1376:             }
                   1377:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1378:             if (@{$offloadto} == 1) {
                   1379:                 $otherserver = $offloadto->[0];
                   1380:             } elsif (@{$offloadto} > 1) {
                   1381:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1382:                     ($otherserver,$lowest_load) =
                   1383:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1384:                 }
                   1385:             }
                   1386:         }
1.1176    raeburn  1387:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1388:             $is_balancer = 0;
                   1389:             if ($uname ne '' && $udom ne '') {
                   1390:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1391:                     
                   1392:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1393:                              'user.loadbalcheck.time' => time});
                   1394:                 }
1.1129    raeburn  1395:             }
                   1396:         }
                   1397:     }
                   1398:     return ($is_balancer,$otherserver);
                   1399: }
                   1400: 
1.1191    raeburn  1401: sub check_balancer_result {
                   1402:     my ($result,@hosts) = @_;
                   1403:     my ($is_balancer,$currtargets,$currrules);
                   1404:     if (ref($result) eq 'HASH') {
                   1405:         if ($result->{'lonhost'} ne '') {
                   1406:             my $currbalancer = $result->{'lonhost'};
                   1407:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1408:                 $is_balancer = 1;
                   1409:                 $currtargets = $result->{'targets'};
                   1410:                 $currrules = $result->{'rules'};
                   1411:             }
                   1412:         } else {
                   1413:             foreach my $key (keys(%{$result})) {
                   1414:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1415:                     (ref($result->{$key}) eq 'HASH')) {
                   1416:                     $is_balancer = 1;
                   1417:                     $currrules = $result->{$key}{'rules'};
                   1418:                     $currtargets = $result->{$key}{'targets'};
                   1419:                     last;
                   1420:                 }
                   1421:             }
                   1422:         }
                   1423:     }
                   1424:     return ($is_balancer,$currtargets,$currrules);
                   1425: }
                   1426: 
1.1129    raeburn  1427: sub get_loadbalancer_targets {
                   1428:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1429:     my $offloadto;
1.1175    raeburn  1430:     if ($rule_in_effect eq 'none') {
                   1431:         return [$perlvar{'lonHostID'}];
                   1432:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1433:         $offloadto = $currtargets;
                   1434:     } else {
                   1435:         if ($rule_in_effect eq 'homeserver') {
                   1436:             my $homeserver = &homeserver($uname,$udom);
                   1437:             if ($homeserver ne 'no_host') {
                   1438:                 $offloadto = [$homeserver];
                   1439:             }
                   1440:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1441:             my %domconfig =
                   1442:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1443:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1444:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1445:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1446:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1447:                     }
                   1448:                 }
                   1449:             } else {
1.1178    raeburn  1450:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1451:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1452:                 if (&hostname($remotebalancer) ne '') {
                   1453:                     $offloadto = [$remotebalancer];
                   1454:                 }
                   1455:             }
                   1456:         } elsif (&hostname($rule_in_effect) ne '') {
                   1457:             $offloadto = [$rule_in_effect];
                   1458:         }
                   1459:     }
                   1460:     return $offloadto;
                   1461: }
                   1462: 
1.1127    raeburn  1463: sub internet_dom_servers {
                   1464:     my ($dom) = @_;
                   1465:     my (%uniqservers,%servers);
                   1466:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1467:     my @machinedoms = &machine_domains($primaryserver);
                   1468:     foreach my $mdom (@machinedoms) {
                   1469:         my %currservers = %servers;
                   1470:         my %server = &get_servers($mdom);
                   1471:         %servers = (%currservers,%server);
                   1472:     }
                   1473:     my %by_hostname;
                   1474:     foreach my $id (keys(%servers)) {
                   1475:         push(@{$by_hostname{$servers{$id}}},$id);
                   1476:     }
                   1477:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1478:         if (@{$by_hostname{$hostname}} > 1) {
                   1479:             my $match = 0;
                   1480:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1481:                 if (&host_domain($id) eq $dom) {
                   1482:                     $uniqservers{$id} = $hostname;
                   1483:                     $match = 1;
                   1484:                 }
                   1485:             }
                   1486:             unless ($match) {
                   1487:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1488:             }
                   1489:         } else {
                   1490:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1491:         }
                   1492:     }
                   1493:     return %uniqservers;
                   1494: }
                   1495: 
1.1       albertel 1496: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1497: 
1.599     albertel 1498: my %homecache;
1.1       albertel 1499: sub homeserver {
1.230     stredwic 1500:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1501:     my $index="$uname:$udom";
1.426     albertel 1502: 
1.599     albertel 1503:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1504: 
                   1505:     my %servers = &get_servers($udom,'library');
                   1506:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1507:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1508: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1509: 
                   1510: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1511: 	if ($answer eq 'found') {
                   1512: 	    delete($badServerCache{$tryserver}); 
                   1513: 	    return $homecache{$index}=$tryserver;
                   1514: 	} elsif ($answer eq 'no_host') {
                   1515: 	    $badServerCache{$tryserver}=1;
                   1516: 	}
1.1       albertel 1517:     }    
                   1518:     return 'no_host';
1.70      www      1519: }
                   1520: 
                   1521: # ------------------------------------- Find the usernames behind a list of IDs
                   1522: 
                   1523: sub idget {
                   1524:     my ($udom,@ids)=@_;
                   1525:     my %returnhash=();
                   1526:     
1.841     albertel 1527:     my %servers = &get_servers($udom,'library');
                   1528:     foreach my $tryserver (keys(%servers)) {
                   1529: 	my $idlist=join('&',@ids);
                   1530: 	$idlist=~tr/A-Z/a-z/; 
                   1531: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1532: 	my @answer=();
                   1533: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1534: 	    @answer=split(/\&/,$reply);
                   1535: 	}                    ;
                   1536: 	my $i;
                   1537: 	for ($i=0;$i<=$#ids;$i++) {
                   1538: 	    if ($answer[$i]) {
                   1539: 		$returnhash{$ids[$i]}=$answer[$i];
                   1540: 	    } 
                   1541: 	}
                   1542:     } 
1.70      www      1543:     return %returnhash;
                   1544: }
                   1545: 
                   1546: # ------------------------------------- Find the IDs behind a list of usernames
                   1547: 
                   1548: sub idrget {
                   1549:     my ($udom,@unames)=@_;
                   1550:     my %returnhash=();
1.800     albertel 1551:     foreach my $uname (@unames) {
                   1552:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1553:     }
1.70      www      1554:     return %returnhash;
                   1555: }
                   1556: 
                   1557: # ------------------------------- Store away a list of names and associated IDs
                   1558: 
                   1559: sub idput {
                   1560:     my ($udom,%ids)=@_;
                   1561:     my %servers=();
1.800     albertel 1562:     foreach my $uname (keys(%ids)) {
                   1563: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1564:         my $uhom=&homeserver($uname,$udom);
1.70      www      1565:         if ($uhom ne 'no_host') {
1.800     albertel 1566:             my $id=&escape($ids{$uname});
1.70      www      1567:             $id=~tr/A-Z/a-z/;
1.800     albertel 1568:             my $esc_unam=&escape($uname);
1.70      www      1569: 	    if ($servers{$uhom}) {
1.800     albertel 1570: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1571:             } else {
1.800     albertel 1572:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1573:             }
                   1574:         }
1.191     harris41 1575:     }
1.800     albertel 1576:     foreach my $server (keys(%servers)) {
                   1577:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1578:     }
1.344     www      1579: }
                   1580: 
1.1023    raeburn  1581: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1582: sub dump_dom {
1.1165    droeschl 1583:     my ($namespace, $udom, $regexp) = @_;
                   1584: 
                   1585:     $udom ||= $env{'user.domain'};
                   1586: 
                   1587:     return () unless $udom;
                   1588: 
                   1589:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1590: }
                   1591: 
1.1023    raeburn  1592: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1593: 
                   1594: sub get_dom {
1.860     raeburn  1595:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1596:     my $items='';
                   1597:     foreach my $item (@$storearr) {
                   1598:         $items.=&escape($item).'&';
                   1599:     }
                   1600:     $items=~s/\&$//;
1.860     raeburn  1601:     if (!$udom) {
                   1602:         $udom=$env{'user.domain'};
                   1603:         if (defined(&domain($udom,'primary'))) {
                   1604:             $uhome=&domain($udom,'primary');
                   1605:         } else {
1.874     albertel 1606:             undef($uhome);
1.860     raeburn  1607:         }
                   1608:     } else {
                   1609:         if (!$uhome) {
                   1610:             if (defined(&domain($udom,'primary'))) {
                   1611:                 $uhome=&domain($udom,'primary');
                   1612:             }
                   1613:         }
                   1614:     }
                   1615:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1616:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1617:         my %returnhash;
1.875     albertel 1618:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1619:             return %returnhash;
                   1620:         }
1.806     raeburn  1621:         my @pairs=split(/\&/,$rep);
                   1622:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1623:             return @pairs;
                   1624:         }
                   1625:         my $i=0;
                   1626:         foreach my $item (@$storearr) {
                   1627:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1628:             $i++;
                   1629:         }
                   1630:         return %returnhash;
                   1631:     } else {
1.880     banghart 1632:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1633:     }
                   1634: }
                   1635: 
                   1636: # -------------------------------------------- put items in domain db files 
                   1637: 
                   1638: sub put_dom {
1.860     raeburn  1639:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1640:     if (!$udom) {
                   1641:         $udom=$env{'user.domain'};
                   1642:         if (defined(&domain($udom,'primary'))) {
                   1643:             $uhome=&domain($udom,'primary');
                   1644:         } else {
1.874     albertel 1645:             undef($uhome);
1.860     raeburn  1646:         }
                   1647:     } else {
                   1648:         if (!$uhome) {
                   1649:             if (defined(&domain($udom,'primary'))) {
                   1650:                 $uhome=&domain($udom,'primary');
                   1651:             }
                   1652:         }
                   1653:     } 
                   1654:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1655:         my $items='';
                   1656:         foreach my $item (keys(%$storehash)) {
                   1657:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1658:         }
                   1659:         $items=~s/\&$//;
                   1660:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1661:     } else {
1.860     raeburn  1662:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1663:     }
                   1664: }
                   1665: 
1.1023    raeburn  1666: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1667: sub newput_dom {
1.1023    raeburn  1668:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1669:     my $result;
                   1670:     if (!$udom) {
                   1671:         $udom=$env{'user.domain'};
                   1672:     }
1.1023    raeburn  1673:     if ($udom) {
                   1674:         my $uname = &get_domainconfiguser($udom);
                   1675:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1676:     }
                   1677:     return $result;
                   1678: }
                   1679: 
1.1023    raeburn  1680: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1681: sub del_dom {
1.1023    raeburn  1682:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1683:     if (ref($storearr) eq 'ARRAY') {
                   1684:         if (!$udom) {
                   1685:             $udom=$env{'user.domain'};
                   1686:         }
1.1023    raeburn  1687:         if ($udom) {
                   1688:             my $uname = &get_domainconfiguser($udom); 
                   1689:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1690:         }
                   1691:     }
                   1692: }
                   1693: 
1.1023    raeburn  1694: # ----------------------------------construct domainconfig user for a domain 
                   1695: sub get_domainconfiguser {
                   1696:     my ($udom) = @_;
                   1697:     return $udom.'-domainconfig';
                   1698: }
                   1699: 
1.837     raeburn  1700: sub retrieve_inst_usertypes {
                   1701:     my ($udom) = @_;
                   1702:     my (%returnhash,@order);
1.989     raeburn  1703:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1704:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1705:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1706:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1707:         @order = @{$domdefs{'inststatusorder'}};
                   1708:     } else {
                   1709:         if (defined(&domain($udom,'primary'))) {
                   1710:             my $uhome=&domain($udom,'primary');
                   1711:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1712:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1713:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1714:                 return (\%returnhash,\@order);
                   1715:             }
                   1716:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1717:             my @pairs=split(/\&/,$hashitems);
                   1718:             foreach my $item (@pairs) {
                   1719:                 my ($key,$value)=split(/=/,$item,2);
                   1720:                 $key = &unescape($key);
                   1721:                 next if ($key =~ /^error: 2 /);
                   1722:                 $returnhash{$key}=&thaw_unescape($value);
                   1723:             }
                   1724:             my @esc_order = split(/\&/,$orderitems);
                   1725:             foreach my $item (@esc_order) {
                   1726:                 push(@order,&unescape($item));
                   1727:             }
                   1728:         } else {
                   1729:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1730:         }
                   1731:     }
                   1732:     return (\%returnhash,\@order);
                   1733: }
                   1734: 
1.868     raeburn  1735: sub is_domainimage {
                   1736:     my ($url) = @_;
                   1737:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1738:         if (&domain($1) ne '') {
                   1739:             return '1';
                   1740:         }
                   1741:     }
                   1742:     return;
                   1743: }
                   1744: 
1.899     raeburn  1745: sub inst_directory_query {
                   1746:     my ($srch) = @_;
                   1747:     my $udom = $srch->{'srchdomain'};
                   1748:     my %results;
                   1749:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1750:     my $outcome;
1.899     raeburn  1751:     if ($homeserver ne '') {
1.904     albertel 1752: 	my $queryid=&reply("querysend:instdirsearch:".
                   1753: 			   &escape($srch->{'srchby'}).':'.
                   1754: 			   &escape($srch->{'srchterm'}).':'.
                   1755: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1756: 	my $host=&hostname($homeserver);
                   1757: 	if ($queryid !~/^\Q$host\E\_/) {
                   1758: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1759: 	    return;
                   1760: 	}
                   1761: 	my $response = &get_query_reply($queryid);
                   1762: 	my $maxtries = 5;
                   1763: 	my $tries = 1;
                   1764: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1765: 	    $response = &get_query_reply($queryid);
                   1766: 	    $tries ++;
                   1767: 	}
                   1768: 
                   1769:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1770:             if ($response eq 'unavailable') {
                   1771:                 $outcome = $response;
                   1772:             } else {
                   1773:                 $outcome = 'ok';
                   1774:                 my @matches = split(/\n/,$response);
                   1775:                 foreach my $match (@matches) {
                   1776:                     my ($key,$value) = split(/=/,$match);
                   1777:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1778:                 }
1.899     raeburn  1779:             }
                   1780:         }
                   1781:     }
1.909     raeburn  1782:     return ($outcome,%results);
1.899     raeburn  1783: }
                   1784: 
                   1785: sub usersearch {
                   1786:     my ($srch) = @_;
                   1787:     my $dom = $srch->{'srchdomain'};
                   1788:     my %results;
                   1789:     my %libserv = &all_library();
                   1790:     my $query = 'usersearch';
                   1791:     foreach my $tryserver (keys(%libserv)) {
                   1792:         if (&host_domain($tryserver) eq $dom) {
                   1793:             my $host=&hostname($tryserver);
                   1794:             my $queryid=
1.911     raeburn  1795:                 &reply("querysend:".&escape($query).':'.
                   1796:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1797:                        &escape($srch->{'srchtype'}).':'.
                   1798:                        &escape($srch->{'srchterm'}),$tryserver);
                   1799:             if ($queryid !~/^\Q$host\E\_/) {
                   1800:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1801:                 next;
1.899     raeburn  1802:             }
                   1803:             my $reply = &get_query_reply($queryid);
                   1804:             my $maxtries = 1;
                   1805:             my $tries = 1;
                   1806:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1807:                 $reply = &get_query_reply($queryid);
                   1808:                 $tries ++;
                   1809:             }
                   1810:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1811:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1812:             } else {
1.911     raeburn  1813:                 my @matches;
                   1814:                 if ($reply =~ /\n/) {
                   1815:                     @matches = split(/\n/,$reply);
                   1816:                 } else {
                   1817:                     @matches = split(/\&/,$reply);
                   1818:                 }
1.899     raeburn  1819:                 foreach my $match (@matches) {
                   1820:                     my ($uname,$udom,%userhash);
1.911     raeburn  1821:                     foreach my $entry (split(/:/,$match)) {
                   1822:                         my ($key,$value) =
                   1823:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1824:                         $userhash{$key} = $value;
                   1825:                         if ($key eq 'username') {
                   1826:                             $uname = $value;
                   1827:                         } elsif ($key eq 'domain') {
                   1828:                             $udom = $value;
1.911     raeburn  1829:                         }
1.899     raeburn  1830:                     }
                   1831:                     $results{$uname.':'.$udom} = \%userhash;
                   1832:                 }
                   1833:             }
                   1834:         }
                   1835:     }
                   1836:     return %results;
                   1837: }
                   1838: 
1.912     raeburn  1839: sub get_instuser {
                   1840:     my ($udom,$uname,$id) = @_;
                   1841:     my $homeserver = &domain($udom,'primary');
                   1842:     my ($outcome,%results);
                   1843:     if ($homeserver ne '') {
                   1844:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1845:                            &escape($id).':'.&escape($udom),$homeserver);
                   1846:         my $host=&hostname($homeserver);
                   1847:         if ($queryid !~/^\Q$host\E\_/) {
                   1848:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1849:             return;
                   1850:         }
                   1851:         my $response = &get_query_reply($queryid);
                   1852:         my $maxtries = 5;
                   1853:         my $tries = 1;
                   1854:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1855:             $response = &get_query_reply($queryid);
                   1856:             $tries ++;
                   1857:         }
                   1858:         if (!&error($response) && $response ne 'refused') {
                   1859:             if ($response eq 'unavailable') {
                   1860:                 $outcome = $response;
                   1861:             } else {
                   1862:                 $outcome = 'ok';
                   1863:                 my @matches = split(/\n/,$response);
                   1864:                 foreach my $match (@matches) {
                   1865:                     my ($key,$value) = split(/=/,$match);
                   1866:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1867:                 }
                   1868:             }
                   1869:         }
                   1870:     }
                   1871:     my %userinfo;
                   1872:     if (ref($results{$uname}) eq 'HASH') {
                   1873:         %userinfo = %{$results{$uname}};
                   1874:     } 
                   1875:     return ($outcome,%userinfo);
                   1876: }
                   1877: 
                   1878: sub inst_rulecheck {
1.923     raeburn  1879:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1880:     my %returnhash;
                   1881:     if ($udom ne '') {
                   1882:         if (ref($rules) eq 'ARRAY') {
                   1883:             @{$rules} = map {&escape($_);} (@{$rules});
                   1884:             my $rulestr = join(':',@{$rules});
                   1885:             my $homeserver=&domain($udom,'primary');
                   1886:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1887:                 my $response;
                   1888:                 if ($item eq 'username') {                
                   1889:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1890:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1891:                                               $homeserver));
1.923     raeburn  1892:                 } elsif ($item eq 'id') {
                   1893:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1894:                                               ':'.&escape($id).':'.$rulestr,
                   1895:                                               $homeserver));
1.945     raeburn  1896:                 } elsif ($item eq 'selfcreate') {
                   1897:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1898:                                                &escape($udom).':'.&escape($uname).
                   1899:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1900:                 }
1.912     raeburn  1901:                 if ($response ne 'refused') {
                   1902:                     my @pairs=split(/\&/,$response);
                   1903:                     foreach my $item (@pairs) {
                   1904:                         my ($key,$value)=split(/=/,$item,2);
                   1905:                         $key = &unescape($key);
                   1906:                         next if ($key =~ /^error: 2 /);
                   1907:                         $returnhash{$key}=&thaw_unescape($value);
                   1908:                     }
                   1909:                 }
                   1910:             }
                   1911:         }
                   1912:     }
                   1913:     return %returnhash;
                   1914: }
                   1915: 
                   1916: sub inst_userrules {
1.923     raeburn  1917:     my ($udom,$check) = @_;
1.912     raeburn  1918:     my (%ruleshash,@ruleorder);
                   1919:     if ($udom ne '') {
                   1920:         my $homeserver=&domain($udom,'primary');
                   1921:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1922:             my $response;
                   1923:             if ($check eq 'id') {
                   1924:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1925:                                  $homeserver);
1.943     raeburn  1926:             } elsif ($check eq 'email') {
                   1927:                 $response=&reply('instemailrules:'.&escape($udom),
                   1928:                                  $homeserver);
1.923     raeburn  1929:             } else {
                   1930:                 $response=&reply('instuserrules:'.&escape($udom),
                   1931:                                  $homeserver);
                   1932:             }
1.912     raeburn  1933:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1934:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1935:                 ($response ne 'no_such_host')) {
                   1936:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1937:                 my @pairs=split(/\&/,$hashitems);
                   1938:                 foreach my $item (@pairs) {
                   1939:                     my ($key,$value)=split(/=/,$item,2);
                   1940:                     $key = &unescape($key);
                   1941:                     next if ($key =~ /^error: 2 /);
                   1942:                     $ruleshash{$key}=&thaw_unescape($value);
                   1943:                 }
                   1944:                 my @esc_order = split(/\&/,$orderitems);
                   1945:                 foreach my $item (@esc_order) {
                   1946:                     push(@ruleorder,&unescape($item));
                   1947:                 }
                   1948:             }
                   1949:         }
                   1950:     }
                   1951:     return (\%ruleshash,\@ruleorder);
                   1952: }
                   1953: 
1.976     raeburn  1954: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1955: 
                   1956: sub get_domain_defaults {
                   1957:     my ($domain) = @_;
                   1958:     my $cachetime = 60*60*24;
                   1959:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1960:     if (defined($cached)) {
                   1961:         if (ref($result) eq 'HASH') {
                   1962:             return %{$result};
                   1963:         }
                   1964:     }
                   1965:     my %domdefaults;
                   1966:     my %domconfig =
1.989     raeburn  1967:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1968:                                   'requestcourses','inststatus',
1.1183    raeburn  1969:                                   'coursedefaults','usersessions',
                   1970:                                   'requestauthor'],$domain);
1.943     raeburn  1971:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1972:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1973:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1974:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1975:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1976:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1977:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1978:     } else {
                   1979:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1980:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1981:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1982:     }
1.976     raeburn  1983:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1984:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1985:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1986:         } else {
                   1987:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1988:         } 
1.1177    raeburn  1989:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1990:         foreach my $item (@usertools) {
                   1991:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1992:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1993:             }
                   1994:         }
                   1995:     }
1.985     raeburn  1996:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1997:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1998:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1999:         }
                   2000:     }
1.1183    raeburn  2001:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2002:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2003:     }
1.989     raeburn  2004:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2005:         foreach my $item ('inststatustypes','inststatusorder') {
                   2006:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2007:         }
                   2008:     }
1.1047    raeburn  2009:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   2010:         foreach my $item ('canuse_pdfforms') {
                   2011:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   2012:         }
1.1216    raeburn  2013:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2014:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2015:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
                   2016:         }
1.1047    raeburn  2017:     }
1.1073    raeburn  2018:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2019:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2020:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2021:         }
                   2022:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2023:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2024:         }
                   2025:     }
1.1219    raeburn  2026:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2027:     return %domdefaults;
                   2028: }
                   2029: 
1.344     www      2030: # --------------------------------------------------- Assign a key to a student
                   2031: 
                   2032: sub assign_access_key {
1.364     www      2033: #
                   2034: # a valid key looks like uname:udom#comments
                   2035: # comments are being appended
                   2036: #
1.498     www      2037:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2038:     $kdom=
1.620     albertel 2039:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2040:     $knum=
1.620     albertel 2041:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2042:     $cdom=
1.620     albertel 2043:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2044:     $cnum=
1.620     albertel 2045:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2046:     $udom=$env{'user.name'} unless (defined($udom));
                   2047:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2048:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2049:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2050:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2051:                                                   # assigned to this person
                   2052:                                                   # - this should not happen,
1.345     www      2053:                                                   # unless something went wrong
                   2054:                                                   # the first time around
                   2055: # ready to assign
1.364     www      2056:         $logentry=$1.'; '.$logentry;
1.496     www      2057:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2058:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2059: # key now belongs to user
1.346     www      2060: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2061:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2062:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2063:                 return 'ok';
                   2064:             } else {
                   2065:                 return 
                   2066:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2067: 	    }
                   2068:         } else {
                   2069:             return 'error: Could not assign key, try again later.';
                   2070:         }
1.364     www      2071:     } elsif (!$existing{$ckey}) {
1.345     www      2072: # the key does not exist
                   2073: 	return 'error: The key does not exist';
                   2074:     } else {
                   2075: # the key is somebody else's
                   2076: 	return 'error: The key is already in use';
                   2077:     }
1.344     www      2078: }
                   2079: 
1.364     www      2080: # ------------------------------------------ put an additional comment on a key
                   2081: 
                   2082: sub comment_access_key {
                   2083: #
                   2084: # a valid key looks like uname:udom#comments
                   2085: # comments are being appended
                   2086: #
                   2087:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2088:     $cdom=
1.620     albertel 2089:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2090:     $cnum=
1.620     albertel 2091:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2092:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2093:     if ($existing{$ckey}) {
                   2094:         $existing{$ckey}.='; '.$logentry;
                   2095: # ready to assign
1.367     www      2096:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2097:                                                  $cdom,$cnum) eq 'ok') {
                   2098: 	    return 'ok';
                   2099:         } else {
                   2100: 	    return 'error: Count not store comment.';
                   2101:         }
                   2102:     } else {
                   2103: # the key does not exist
                   2104: 	return 'error: The key does not exist';
                   2105:     }
                   2106: }
                   2107: 
1.344     www      2108: # ------------------------------------------------------ Generate a set of keys
                   2109: 
                   2110: sub generate_access_keys {
1.364     www      2111:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2112:     $cdom=
1.620     albertel 2113:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2114:     $cnum=
1.620     albertel 2115:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2116:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2117:     unless (($cdom) && ($cnum)) { return 0; }
                   2118:     if ($number>10000) { return 0; }
                   2119:     sleep(2); # make sure don't get same seed twice
                   2120:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2121:     my $total=0;
                   2122:     for (my $i=1;$i<=$number;$i++) {
                   2123:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2124:                   sprintf("%lx",int(100000*rand)).'-'.
                   2125:                   sprintf("%lx",int(100000*rand));
                   2126:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2127:        $newkey=~s/0/h/g; # and also 0 and O
                   2128:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2129:        if ($existing{$newkey}) {
                   2130:            $i--;
                   2131:        } else {
1.364     www      2132: 	  if (&put('accesskeys',
                   2133:               { $newkey => '# generated '.localtime().
1.620     albertel 2134:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2135:                            '; '.$logentry },
                   2136: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2137:               $total++;
                   2138: 	  }
                   2139:        }
                   2140:     }
1.620     albertel 2141:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2142:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2143:     return $total;
                   2144: }
                   2145: 
                   2146: # ------------------------------------------------------- Validate an accesskey
                   2147: 
                   2148: sub validate_access_key {
                   2149:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2150:     $cdom=
1.620     albertel 2151:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2152:     $cnum=
1.620     albertel 2153:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2154:     $udom=$env{'user.domain'} unless (defined($udom));
                   2155:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2156:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2157:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2158: }
                   2159: 
                   2160: # ------------------------------------- Find the section of student in a course
1.652     albertel 2161: sub devalidate_getsection_cache {
                   2162:     my ($udom,$unam,$courseid)=@_;
                   2163:     my $hashid="$udom:$unam:$courseid";
                   2164:     &devalidate_cache_new('getsection',$hashid);
                   2165: }
1.298     matthew  2166: 
1.815     albertel 2167: sub courseid_to_courseurl {
                   2168:     my ($courseid) = @_;
                   2169:     #already url style courseid
                   2170:     return $courseid if ($courseid =~ m{^/});
                   2171: 
                   2172:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2173: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2174: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2175: 	return "/$cdom/$cnum";
                   2176:     }
                   2177: 
                   2178:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2179:     if (exists($courseinfo{'num'})) {
                   2180: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2181:     }
                   2182: 
                   2183:     return undef;
                   2184: }
                   2185: 
1.298     matthew  2186: sub getsection {
                   2187:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2188:     my $cachetime=1800;
1.551     albertel 2189: 
                   2190:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2191:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2192:     if (defined($cached)) { return $result; }
                   2193: 
1.298     matthew  2194:     my %Pending; 
                   2195:     my %Expired;
                   2196:     #
                   2197:     # Each role can either have not started yet (pending), be active, 
                   2198:     #    or have expired.
                   2199:     #
                   2200:     # If there is an active role, we are done.
                   2201:     #
                   2202:     # If there is more than one role which has not started yet, 
                   2203:     #     choose the one which will start sooner
                   2204:     # If there is one role which has not started yet, return it.
                   2205:     #
                   2206:     # If there is more than one expired role, choose the one which ended last.
                   2207:     # If there is a role which has expired, return it.
                   2208:     #
1.815     albertel 2209:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2210:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2211:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2212:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2213:         my $section=$1;
                   2214:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2215:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2216:         my $now=time;
1.548     albertel 2217:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2218:             $Expired{$end}=$section;
                   2219:             next;
                   2220:         }
1.548     albertel 2221:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2222:             $Pending{$start}=$section;
                   2223:             next;
                   2224:         }
1.599     albertel 2225:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2226:     }
                   2227:     #
                   2228:     # Presumedly there will be few matching roles from the above
                   2229:     # loop and the sorting time will be negligible.
                   2230:     if (scalar(keys(%Pending))) {
                   2231:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2232:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2233:     } 
                   2234:     if (scalar(keys(%Expired))) {
                   2235:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2236:         my $time = pop(@sorted);
1.599     albertel 2237:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2238:     }
1.599     albertel 2239:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2240: }
1.70      www      2241: 
1.599     albertel 2242: sub save_cache {
                   2243:     &purge_remembered();
1.722     albertel 2244:     #&Apache::loncommon::validate_page();
1.620     albertel 2245:     undef(%env);
1.780     albertel 2246:     undef($env_loaded);
1.599     albertel 2247: }
1.452     albertel 2248: 
1.599     albertel 2249: my $to_remember=-1;
                   2250: my %remembered;
                   2251: my %accessed;
                   2252: my $kicks=0;
                   2253: my $hits=0;
1.849     albertel 2254: sub make_key {
                   2255:     my ($name,$id) = @_;
1.872     albertel 2256:     if (length($id) > 65 
                   2257: 	&& length(&escape($id)) > 200) {
                   2258: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2259:     }
1.849     albertel 2260:     return &escape($name.':'.$id);
                   2261: }
                   2262: 
1.599     albertel 2263: sub devalidate_cache_new {
                   2264:     my ($name,$id,$debug) = @_;
                   2265:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2266:     $id=&make_key($name,$id);
1.599     albertel 2267:     $memcache->delete($id);
                   2268:     delete($remembered{$id});
                   2269:     delete($accessed{$id});
                   2270: }
                   2271: 
                   2272: sub is_cached_new {
                   2273:     my ($name,$id,$debug) = @_;
1.849     albertel 2274:     $id=&make_key($name,$id);
1.599     albertel 2275:     if (exists($remembered{$id})) {
1.1133    foxr     2276: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2277: 	$accessed{$id}=[&gettimeofday()];
                   2278: 	$hits++;
                   2279: 	return ($remembered{$id},1);
                   2280:     }
                   2281:     my $value = $memcache->get($id);
                   2282:     if (!(defined($value))) {
                   2283: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2284: 	return (undef,undef);
1.416     albertel 2285:     }
1.599     albertel 2286:     if ($value eq '__undef__') {
                   2287: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2288: 	$value=undef;
                   2289:     }
                   2290:     &make_room($id,$value,$debug);
                   2291:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2292:     return ($value,1);
                   2293: }
                   2294: 
                   2295: sub do_cache_new {
                   2296:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2297:     $id=&make_key($name,$id);
1.599     albertel 2298:     my $setvalue=$value;
                   2299:     if (!defined($setvalue)) {
                   2300: 	$setvalue='__undef__';
                   2301:     }
1.623     albertel 2302:     if (!defined($time) ) {
                   2303: 	$time=600;
                   2304:     }
1.599     albertel 2305:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2306:     my $result = $memcache->set($id,$setvalue,$time);
                   2307:     if (! $result) {
1.872     albertel 2308: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2309: 	$memcache->disconnect_all();
1.872     albertel 2310:     }
1.600     albertel 2311:     # need to make a copy of $value
1.919     albertel 2312:     &make_room($id,$value,$debug);
1.599     albertel 2313:     return $value;
                   2314: }
                   2315: 
                   2316: sub make_room {
                   2317:     my ($id,$value,$debug)=@_;
1.919     albertel 2318: 
                   2319:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2320:                                     : $value;
1.599     albertel 2321:     if ($to_remember<0) { return; }
                   2322:     $accessed{$id}=[&gettimeofday()];
                   2323:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2324:     my $to_kick;
                   2325:     my $max_time=0;
                   2326:     foreach my $other (keys(%accessed)) {
                   2327: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2328: 	    $to_kick=$other;
                   2329: 	    $max_time=&tv_interval($accessed{$other});
                   2330: 	}
                   2331:     }
                   2332:     delete($remembered{$to_kick});
                   2333:     delete($accessed{$to_kick});
                   2334:     $kicks++;
                   2335:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2336:     return;
                   2337: }
                   2338: 
1.599     albertel 2339: sub purge_remembered {
1.604     albertel 2340:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2341:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2342:     undef(%remembered);
                   2343:     undef(%accessed);
1.428     albertel 2344: }
1.70      www      2345: # ------------------------------------- Read an entry from a user's environment
                   2346: 
                   2347: sub userenvironment {
                   2348:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2349:     my $items;
                   2350:     foreach my $item (@what) {
                   2351:         $items.=&escape($item).'&';
                   2352:     }
                   2353:     $items=~s/\&$//;
1.70      www      2354:     my %returnhash=();
1.1009    raeburn  2355:     my $uhome = &homeserver($unam,$udom);
                   2356:     unless ($uhome eq 'no_host') {
                   2357:         my @answer=split(/\&/, 
                   2358:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2359:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2360:             return %returnhash;
                   2361:         }
1.1009    raeburn  2362:         my $i;
                   2363:         for ($i=0;$i<=$#what;$i++) {
                   2364: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2365:         }
1.70      www      2366:     }
                   2367:     return %returnhash;
1.1       albertel 2368: }
                   2369: 
1.617     albertel 2370: # ---------------------------------------------------------- Get a studentphoto
                   2371: sub studentphoto {
                   2372:     my ($udom,$unam,$ext) = @_;
                   2373:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2374:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2375:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2376:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2377:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   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:         }
                   2388:     } else {
                   2389:         my ($result,$perm_reqd) = 
1.707     albertel 2390: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2391:         if ($result eq 'ok') {
                   2392:             if (!($perm_reqd eq 'yes')) {
                   2393:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2394:             }
                   2395:         }
                   2396:     }
                   2397:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2398: }
                   2399: 
                   2400: sub retrievestudentphoto {
                   2401:     my ($udom,$unam,$ext,$type) = @_;
                   2402:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2403:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2404:     if ($ret eq 'ok') {
                   2405:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2406:         if ($type eq 'thumbnail') {
                   2407:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2408:         }
                   2409:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2410:         return $tokenurl;
                   2411:     } else {
                   2412:         if ($type eq 'thumbnail') {
                   2413:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2414:         } else { 
                   2415:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2416:         }
1.617     albertel 2417:     }
                   2418: }
                   2419: 
1.263     www      2420: # -------------------------------------------------------------------- New chat
                   2421: 
                   2422: sub chatsend {
1.724     raeburn  2423:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2424:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2425:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2426:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2427:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2428: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2429: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2430: }
                   2431: 
                   2432: # ------------------------------------------ Find current version of a resource
                   2433: 
                   2434: sub getversion {
                   2435:     my $fname=&clutter(shift);
1.1189    raeburn  2436:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2437:     return &currentversion(&filelocation('',$fname));
                   2438: }
                   2439: 
                   2440: sub currentversion {
                   2441:     my $fname=shift;
                   2442:     my $author=$fname;
                   2443:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2444:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2445:     my $home=&homeserver($uname,$udom);
1.292     www      2446:     if ($home eq 'no_host') { 
                   2447:         return -1; 
                   2448:     }
1.1112    www      2449:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2450:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2451: 	return -1;
                   2452:     }
1.1112    www      2453:     return $answer;
1.263     www      2454: }
                   2455: 
1.1111    www      2456: #
                   2457: # Return special version number of resource if set by override, empty otherwise
                   2458: #
                   2459: sub usedversion {
                   2460:     my $fname=shift;
                   2461:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2462:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2463:     if ($urlversion) { return $urlversion; }
                   2464:     return '';
                   2465: }
                   2466: 
1.1       albertel 2467: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2468: 
1.1       albertel 2469: sub subscribe {
                   2470:     my $fname=shift;
1.761     raeburn  2471:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2472:     $fname=~s/[\n\r]//g;
1.1       albertel 2473:     my $author=$fname;
                   2474:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2475:     my ($udom,$uname)=split(/\//,$author);
                   2476:     my $home=homeserver($uname,$udom);
1.335     albertel 2477:     if ($home eq 'no_host') {
                   2478:         return 'not_found';
1.1       albertel 2479:     }
                   2480:     my $answer=reply("sub:$fname",$home);
1.64      www      2481:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2482: 	$answer.=' by '.$home;
                   2483:     }
1.1       albertel 2484:     return $answer;
                   2485: }
                   2486:     
1.8       www      2487: # -------------------------------------------------------------- Replicate file
                   2488: 
                   2489: sub repcopy {
                   2490:     my $filename=shift;
1.23      www      2491:     $filename=~s/\/+/\//g;
1.1142    raeburn  2492:     my $londocroot = $perlvar{'lonDocRoot'};
                   2493:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2494:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2495:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2496: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2497: 	return &repcopy_userfile($filename);
                   2498:     }
1.532     albertel 2499:     $filename=~s/[\n\r]//g;
1.8       www      2500:     my $transname="$filename.in.transfer";
1.828     www      2501: # FIXME: this should flock
1.607     raeburn  2502:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2503:     my $remoteurl=subscribe($filename);
1.64      www      2504:     if ($remoteurl =~ /^con_lost by/) {
                   2505: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2506:            return 'unavailable';
1.8       www      2507:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2508: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2509: 	   return 'not_found';
1.64      www      2510:     } elsif ($remoteurl =~ /^rejected by/) {
                   2511: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2512:            return 'forbidden';
1.20      www      2513:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2514:            return 'ok';
1.8       www      2515:     } else {
1.290     www      2516:         my $author=$filename;
                   2517:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2518:         my ($udom,$uname)=split(/\//,$author);
                   2519:         my $home=homeserver($uname,$udom);
                   2520:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2521:            my @parts=split(/\//,$filename);
                   2522:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2523:            if ($path ne "$londocroot/res") {
1.8       www      2524:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2525: 	       return 'bad_request';
1.8       www      2526:            }
                   2527:            my $count;
                   2528:            for ($count=5;$count<$#parts;$count++) {
                   2529:                $path.="/$parts[$count]";
                   2530:                if ((-e $path)!=1) {
                   2531: 		   mkdir($path,0777);
                   2532:                }
                   2533:            }
                   2534:            my $ua=new LWP::UserAgent;
                   2535:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2536:            my $response=$ua->request($request,$transname);
                   2537:            if ($response->is_error()) {
                   2538: 	       unlink($transname);
                   2539:                my $message=$response->status_line;
1.672     albertel 2540:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2541:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2542:                return 'unavailable';
1.8       www      2543:            } else {
1.16      www      2544: 	       if ($remoteurl!~/\.meta$/) {
                   2545:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2546:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2547:                   if ($mresponse->is_error()) {
                   2548: 		      unlink($filename.'.meta');
                   2549:                       &logthis(
1.672     albertel 2550:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2551:                   }
                   2552: 	       }
1.8       www      2553:                rename($transname,$filename);
1.607     raeburn  2554:                return 'ok';
1.8       www      2555:            }
1.290     www      2556:        }
1.8       www      2557:     }
1.330     www      2558: }
                   2559: 
                   2560: # ------------------------------------------------ Get server side include body
                   2561: sub ssi_body {
1.381     albertel 2562:     my ($filelink,%form)=@_;
1.606     matthew  2563:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2564:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2565:     }
1.953     www      2566:     my $output='';
                   2567:     my $response;
1.980     raeburn  2568:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2569:        ($output,$response)=&externalssi($filelink);
1.953     www      2570:     } else {
1.1004    droeschl 2571:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2572:        $filelink .= 'inhibitmenu=yes';
1.953     www      2573:        ($output,$response)=&ssi($filelink,%form);
                   2574:     }
1.778     albertel 2575:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2576:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2577:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2578:     if (wantarray) {
                   2579:         return ($output, $response);
                   2580:     } else {
                   2581:         return $output;
                   2582:     }
1.8       www      2583: }
                   2584: 
1.15      www      2585: # --------------------------------------------------------- Server Side Include
                   2586: 
1.782     albertel 2587: sub absolute_url {
                   2588:     my ($host_name) = @_;
                   2589:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2590:     if ($host_name eq '') {
                   2591: 	$host_name = $ENV{'SERVER_NAME'};
                   2592:     }
                   2593:     return $protocol.$host_name;
                   2594: }
                   2595: 
1.942     foxr     2596: #
                   2597: #   Server side include.
                   2598: # Parameters:
                   2599: #  fn     Possibly encrypted resource name/id.
                   2600: #  form   Hash that describes how the rendering should be done
                   2601: #         and other things.
1.944     foxr     2602: # Returns:
1.950     raeburn  2603: #   Scalar context: The content of the response.
                   2604: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2605: #     
1.15      www      2606: sub ssi {
                   2607: 
1.944     foxr     2608:     my ($fn,%form)=@_;
1.15      www      2609:     my $ua=new LWP::UserAgent;
1.23      www      2610:     my $request;
1.711     albertel 2611: 
                   2612:     $form{'no_update_last_known'}=1;
1.895     albertel 2613:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2614:     if (%form) {
1.782     albertel 2615:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2616:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2617:     } else {
1.782     albertel 2618:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2619:     }
                   2620: 
1.15      www      2621:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2622:     my $response= $ua->request($request);
1.1182    foxr     2623:     my $content = $response->content;
                   2624: 
                   2625: 
1.944     foxr     2626:     if (wantarray) {
1.1173    foxr     2627: 	return ($content, $response);
1.944     foxr     2628:     } else {
1.1173    foxr     2629: 	return $content;
1.942     foxr     2630:     }
1.324     www      2631: }
                   2632: 
                   2633: sub externalssi {
                   2634:     my ($url)=@_;
                   2635:     my $ua=new LWP::UserAgent;
                   2636:     my $request=new HTTP::Request('GET',$url);
                   2637:     my $response=$ua->request($request);
1.954     raeburn  2638:     if (wantarray) {
                   2639:         return ($response->content, $response);
                   2640:     } else {
                   2641:         return $response->content;
                   2642:     }
1.15      www      2643: }
1.254     www      2644: 
1.492     albertel 2645: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2646: 
                   2647: sub allowuploaded {
                   2648:     my ($srcurl,$url)=@_;
                   2649:     $url=&clutter(&declutter($url));
                   2650:     my $dir=$url;
                   2651:     $dir=~s/\/[^\/]+$//;
                   2652:     my %httpref=();
                   2653:     my $httpurl=&hreflocation('',$url);
                   2654:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2655:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2656: }
1.477     raeburn  2657: 
1.1193    raeburn  2658: #
                   2659: # Determine if the current user should be able to edit a particular resource,
                   2660: # when viewing in course context.
                   2661: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2662: #     Functions.
                   2663: # (b) When displaying folder contents in course editor, used to determine if
                   2664: #     "Edit" link will be displayed alongside resource.
                   2665: #
1.1196    raeburn  2666: #  input: six args -- filename (decluttered), course number, course domain,
                   2667: #                   url, symb (if registered) and group (if this is a group
                   2668: #                   item -- e.g., bulletin board, group page etc.).
                   2669: #  output: array of five scalars -- 
1.1193    raeburn  2670: #          $cfile -- url for file editing if editable on current server
                   2671: #          $home -- homeserver of resource (i.e., for author if published,
                   2672: #                                           or course if uploaded.).
                   2673: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2674: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2675: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2676: #
                   2677: 
                   2678: sub can_edit_resource {
1.1194    raeburn  2679:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2680:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2681: #
                   2682: # For aboutme pages user can only edit his/her own.
                   2683: #
1.1199    raeburn  2684:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2685:         my ($sdom,$sname) = ($1,$2);
                   2686:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2687:             $home = $env{'user.home'};
                   2688:             $cfile = $resurl;
                   2689:             if ($env{'form.forceedit'}) {
                   2690:                 $forceview = 1;
                   2691:             } else {
                   2692:                 $forceedit = 1;
                   2693:             }
                   2694:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2695:         } else {
                   2696:             return;
                   2697:         }
                   2698:     }
                   2699: 
                   2700:     if ($env{'request.course.id'}) {
                   2701:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2702:         if ($group ne '') {
                   2703: # if this is a group homepage or group bulletin board, check group privs
                   2704:             my $allowed = 0;
1.1197    raeburn  2705:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2706:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2707:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2708:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2709:                     $allowed = 1;
                   2710:                 }
1.1197    raeburn  2711:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2712:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2713:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2714:                     $allowed = 1;
                   2715:                 }
                   2716:             }
                   2717:             if ($allowed) {
                   2718:                 $home=&homeserver($cnum,$cdom);
                   2719:                 if ($env{'form.forceedit'}) {
                   2720:                     $forceview = 1;
                   2721:                 } else {
                   2722:                     $forceedit = 1;
                   2723:                 }
                   2724:                 $cfile = $resurl;
                   2725:             } else {
                   2726:                 return;
                   2727:             }
                   2728:         } else {
1.1208    raeburn  2729:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2730:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2731:                     return;
                   2732:                 }
                   2733:             } elsif (!$crsedit) {
1.1194    raeburn  2734: #
                   2735: # No edit allowed where CC has switched to student role.
                   2736: #
                   2737:                 return;
                   2738:             }
                   2739:         }
                   2740:     }
                   2741: 
1.1193    raeburn  2742:     if ($file ne '') {
                   2743:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2744:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2745:                 $uploaded = 1;
                   2746:                 $incourse = 1;
1.1193    raeburn  2747:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2748:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2749:                     if ($env{'form.forceedit'}) {
                   2750:                         $forceview = 1;
                   2751:                     } else {
                   2752:                         $forceedit = 1;
                   2753:                     }
1.1194    raeburn  2754:                 }
                   2755:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2756:                 $incourse = 1;
                   2757:                 if ($env{'form.forceedit'}) {
                   2758:                     $forceview = 1;
                   2759:                 } else {
                   2760:                     $forceedit = 1;
                   2761:                 }
                   2762:                 $cfile = $resurl;
                   2763:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2764:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2765:                     $incourse = 1;
                   2766:                     if ($env{'form.forceedit'}) {
                   2767:                         $forceview = 1;
                   2768:                     } else {
                   2769:                         $forceedit = 1;
                   2770:                     }
                   2771:                     $cfile = $resurl;
1.1199    raeburn  2772:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2773:                     $incourse = 1;
                   2774:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2775:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2776:                     $incourse = 1;
1.1199    raeburn  2777:                     if ($env{'form.forceedit'}) {
                   2778:                         $forceview = 1;
                   2779:                     } else {
                   2780:                         $forceedit = 1;
                   2781:                     }
                   2782:                     $cfile = $resurl;
1.1208    raeburn  2783:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2784:                     $incourse = 1;
                   2785:                     if ($env{'form.forceedit'}) {
                   2786:                         $forceview = 1;
                   2787:                     } else {
                   2788:                         $forceedit = 1;
                   2789:                     }
                   2790:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2791:                 }
                   2792:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2793:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2794:                 if (&is_on_map($template)) { 
                   2795:                     $incourse = 1;
                   2796:                     $forceview = 1;
                   2797:                     $cfile = $template;
1.1193    raeburn  2798:                 }
1.1199    raeburn  2799:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2800:                     $incourse = 1;
                   2801:                     if ($env{'form.forceedit'}) {
                   2802:                         $forceview = 1;
                   2803:                     } else {
                   2804:                         $forceedit = 1;
                   2805:                     }
                   2806:                     $cfile = $resurl;
                   2807:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2808:                 $incourse = 1;
                   2809:                 $forceview = 1;
                   2810:                 if ($symb) {
                   2811:                     my ($map,$id,$res)=&decode_symb($symb);
                   2812:                     $env{'request.symb'} = $symb;
                   2813:                     $cfile = &clutter($res);
                   2814:                 } else {
                   2815:                     $cfile = $env{'form.suppurl'};
                   2816:                     $cfile =~ s{^http://}{};
                   2817:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2818:                 }
1.1193    raeburn  2819:             }
                   2820:         }
1.1194    raeburn  2821:         if ($uploaded || $incourse) {
                   2822:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2823:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2824:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2825:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2826:             # Check that the user has permission to edit this resource
                   2827:             my $setpriv = 1;
                   2828:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2829:             if (defined($cfudom)) {
                   2830:                 $home=&homeserver($cfuname,$cfudom);
                   2831:                 $cfile=$file;
                   2832:             }
                   2833:         }
1.1194    raeburn  2834:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2835:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2836:             my @ids=&current_machine_ids();
                   2837:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2838:                 $switchserver=1;
                   2839:             }
                   2840:         }
                   2841:     }
1.1194    raeburn  2842:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2843: }
                   2844: 
                   2845: sub is_course_upload {
                   2846:     my ($file,$cnum,$cdom) = @_;
                   2847:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2848:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2849:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2850:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2851:         return 1;
                   2852:     }
                   2853:     return;
                   2854: }
                   2855: 
1.1194    raeburn  2856: sub in_course {
1.1195    raeburn  2857:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2858:     if ($hideprivileged) {
                   2859:         my $skipuser;
1.1219    raeburn  2860:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2861:         my @possdoms = ($cdom);  
                   2862:         if ($coursehash{'checkforpriv'}) { 
                   2863:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   2864:         }
                   2865:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  2866:             $skipuser = 1;
                   2867:             if ($coursehash{'nothideprivileged'}) {
                   2868:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2869:                     my $user;
                   2870:                     if ($item =~ /:/) {
                   2871:                         $user = $item;
                   2872:                     } else {
                   2873:                         $user = join(':',split(/[\@]/,$item));
                   2874:                     }
                   2875:                     if ($user eq $uname.':'.$udom) {
                   2876:                         undef($skipuser);
                   2877:                         last;
                   2878:                     }
                   2879:                 }
                   2880:             }
                   2881:             if ($skipuser) {
                   2882:                 return 0;
                   2883:             }
                   2884:         }
                   2885:     }
1.1194    raeburn  2886:     $type ||= 'any';
                   2887:     if (!defined($cdom) || !defined($cnum)) {
                   2888:         my $cid  = $env{'request.course.id'};
                   2889:         $cdom = $env{'course.'.$cid.'.domain'};
                   2890:         $cnum = $env{'course.'.$cid.'.num'};
                   2891:     }
                   2892:     my $typesref;
1.1195    raeburn  2893:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  2894:         $typesref = ['active','previous','future'];
                   2895:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2896:         $typesref = [$type];
                   2897:     }
                   2898:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2899:                               $typesref,undef,[$cdom]);
                   2900:     my ($tmp) = keys(%roles);
                   2901:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2902:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2903:     if (@course_roles > 0) {
                   2904:         return 1;
                   2905:     }
                   2906:     return 0;
                   2907: }
                   2908: 
1.478     albertel 2909: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2910: # input: action, courseID, current domain, intended
1.637     raeburn  2911: #        path to file, source of file, instruction to parse file for objects,
                   2912: #        ref to hash for embedded objects,
                   2913: #        ref to hash for codebase of java objects.
1.1095    raeburn  2914: #        reference to scalar to accommodate mime type determined
                   2915: #          from File::MMagic if $parser = parse.
1.637     raeburn  2916: #
1.485     raeburn  2917: # output: url to file (if action was uploaddoc), 
                   2918: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2919: #
1.478     albertel 2920: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2921: # course.
1.477     raeburn  2922: #
1.478     albertel 2923: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2924: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2925: #          course's home server.
1.477     raeburn  2926: #
1.478     albertel 2927: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2928: #          be copied from $source (current location) to 
                   2929: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2930: #         and will then be copied to
                   2931: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2932: #         course's home server.
1.485     raeburn  2933: #
1.481     raeburn  2934: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2935: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2936: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2937: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2938: #         in course's home server.
1.637     raeburn  2939: #
1.477     raeburn  2940: 
                   2941: sub process_coursefile {
1.1095    raeburn  2942:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2943:         $mimetype)=@_;
1.477     raeburn  2944:     my $fetchresult;
1.638     albertel 2945:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2946:     if ($action eq 'propagate') {
1.638     albertel 2947:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2948: 			     $home);
1.481     raeburn  2949:     } else {
1.477     raeburn  2950:         my $fpath = '';
                   2951:         my $fname = $file;
1.478     albertel 2952:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2953:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2954:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2955:         if ($action eq 'copy') {
                   2956:             if ($source eq '') {
                   2957:                 $fetchresult = 'no source file';
                   2958:                 return $fetchresult;
                   2959:             } else {
                   2960:                 my $destination = $filepath.'/'.$fname;
                   2961:                 rename($source,$destination);
                   2962:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2963:                                  $home);
1.481     raeburn  2964:             }
                   2965:         } elsif ($action eq 'uploaddoc') {
                   2966:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2967:             print $fh $env{'form.'.$source};
1.481     raeburn  2968:             close($fh);
1.637     raeburn  2969:             if ($parser eq 'parse') {
1.1024    raeburn  2970:                 my $mm = new File::MMagic;
1.1095    raeburn  2971:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2972:                 if ($type eq 'text/html') {
1.1024    raeburn  2973:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2974:                     unless ($parse_result eq 'ok') {
                   2975:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2976:                     }
1.637     raeburn  2977:                 }
1.1095    raeburn  2978:                 if (ref($mimetype)) {
                   2979:                     $$mimetype = $type;
                   2980:                 } 
1.637     raeburn  2981:             }
1.477     raeburn  2982:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2983:                                  $home);
1.481     raeburn  2984:             if ($fetchresult eq 'ok') {
                   2985:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2986:             } else {
                   2987:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2988:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2989:                 return '/adm/notfound.html';
                   2990:             }
1.477     raeburn  2991:         }
                   2992:     }
1.485     raeburn  2993:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2994:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2995:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2996:     }
                   2997:     return $fetchresult;
                   2998: }
                   2999: 
1.637     raeburn  3000: sub build_filepath {
                   3001:     my ($fpath) = @_;
                   3002:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3003:     unless ($fpath eq '') {
                   3004:         my @parts=split('/',$fpath);
                   3005:         foreach my $part (@parts) {
                   3006:             $filepath.= '/'.$part;
                   3007:             if ((-e $filepath)!=1) {
                   3008:                 mkdir($filepath,0777);
                   3009:             }
                   3010:         }
                   3011:     }
                   3012:     return $filepath;
                   3013: }
                   3014: 
                   3015: sub store_edited_file {
1.638     albertel 3016:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3017:     my $file = $primary_url;
                   3018:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3019:     my $fpath = '';
                   3020:     my $fname = $file;
                   3021:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3022:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3023:     my $filepath = &build_filepath($fpath);
                   3024:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3025:     print $fh $content;
                   3026:     close($fh);
1.638     albertel 3027:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3028:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3029: 			  $home);
1.637     raeburn  3030:     if ($$fetchresult eq 'ok') {
                   3031:         return '/uploaded/'.$fpath.'/'.$fname;
                   3032:     } else {
1.638     albertel 3033:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3034: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3035:         return '/adm/notfound.html';
                   3036:     }
                   3037: }
                   3038: 
1.531     albertel 3039: sub clean_filename {
1.831     albertel 3040:     my ($fname,$args)=@_;
1.315     www      3041: # Replace Windows backslashes by forward slashes
1.257     www      3042:     $fname=~s/\\/\//g;
1.831     albertel 3043:     if (!$args->{'keep_path'}) {
                   3044:         # Get rid of everything but the actual filename
                   3045: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3046:     }
1.315     www      3047: # Replace spaces by underscores
                   3048:     $fname=~s/\s+/\_/g;
                   3049: # Replace all other weird characters by nothing
1.831     albertel 3050:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3051: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3052: # numbers
                   3053:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3054:     return $fname;
                   3055: }
1.1051    raeburn  3056: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3057: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3058: # image with the same aspect ratio as the original, but with dimensions which do 
                   3059: # not exceed $resizewidth and $resizeheight.
                   3060:  
1.984     neumanie 3061: sub resizeImage {
1.1051    raeburn  3062:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3063:     my $ima = Image::Magick->new;
                   3064:     my $resized;
                   3065:     if (-e $img_path) {
                   3066:         $ima->Read($img_path);
                   3067:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3068:             my $width = $ima->Get('width');
                   3069:             my $height = $ima->Get('height');
                   3070:             if ($width > $resizewidth) {
                   3071: 	        my $factor = $width/$resizewidth;
                   3072:                 my $newheight = $height/$factor;
                   3073:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3074:                 $resized = 1;
                   3075:             }
                   3076:         }
                   3077:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3078:             my $width = $ima->Get('width');
                   3079:             my $height = $ima->Get('height');
                   3080:             if ($height > $resizeheight) {
                   3081:                 my $factor = $height/$resizeheight;
                   3082:                 my $newwidth = $width/$factor;
                   3083:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3084:                 $resized = 1;
                   3085:             }
                   3086:         }
                   3087:         if ($resized) {
                   3088:             $ima->Write($img_path);
                   3089:         }
                   3090:     }
                   3091:     return;
1.977     amueller 3092: }
                   3093: 
1.608     albertel 3094: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3095: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3096: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3097: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3098: #                                    canceloverwrite, or ''. 
                   3099: #                   if 'coursedoc': upload to the current course
                   3100: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3101: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3102: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3103: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3104: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3105: #        $allfiles - reference to hash for embedded objects
                   3106: #        $codebase - reference to hash for codebase of java objects
                   3107: #        $desuname - username for permanent storage of uploaded file
                   3108: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3109: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3110: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3111: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3112: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3113: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3114: #                    from File::MMagic.
1.858     raeburn  3115: # 
1.686     albertel 3116: # output: url of file in userspace, or error: <message> 
                   3117: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3118: 
1.531     albertel 3119: sub userfileupload {
1.1090    raeburn  3120:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3121:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3122:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3123:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3124:     $fname=&clean_filename($fname);
1.1090    raeburn  3125:     # See if there is anything left
1.257     www      3126:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3127:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3128:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3129:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3130:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3131:         my $now = time;
1.1090    raeburn  3132:         my $filepath;
1.1095    raeburn  3133:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3134:              $filepath = 'tmp/helprequests/'.$now;
                   3135:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3136:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3137:                          '_'.$env{'user.domain'}.'/pending';
                   3138:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3139:             my ($docuname,$docudom);
                   3140:             if ($destudom) {
                   3141:                 $docudom = $destudom;
                   3142:             } else {
                   3143:                 $docudom = $env{'user.domain'};
                   3144:             }
                   3145:             if ($destuname) {
                   3146:                 $docuname = $destuname;
                   3147:             } else {
                   3148:                 $docuname = $env{'user.name'};
                   3149:             }
                   3150:             if (exists($env{'form.group'})) {
                   3151:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3152:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3153:             }
                   3154:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3155:             if ($context eq 'canceloverwrite') {
                   3156:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3157:                 if (-e  $tempfile) {
                   3158:                     my @info = stat($tempfile);
                   3159:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3160:                         unlink($tempfile);
                   3161:                     }
                   3162:                 }
                   3163:                 return;
1.523     raeburn  3164:             }
                   3165:         }
1.1090    raeburn  3166:         # Create the directory if not present
1.741     raeburn  3167:         my @parts=split(/\//,$filepath);
                   3168:         my $fullpath = $perlvar{'lonDaemons'};
                   3169:         for (my $i=0;$i<@parts;$i++) {
                   3170:             $fullpath .= '/'.$parts[$i];
                   3171:             if ((-e $fullpath)!=1) {
                   3172:                 mkdir($fullpath,0777);
                   3173:             }
                   3174:         }
                   3175:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3176:         print $fh $env{'form.'.$formname};
                   3177:         close($fh);
1.1090    raeburn  3178:         if ($context eq 'existingfile') {
                   3179:             my @info = stat($fullpath.'/'.$fname);
                   3180:             return ($fullpath.'/'.$fname,$info[9]);
                   3181:         } else {
                   3182:             return $fullpath.'/'.$fname;
                   3183:         }
1.523     raeburn  3184:     }
1.995     raeburn  3185:     if ($subdir eq 'scantron') {
                   3186:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3187:     } else {
1.995     raeburn  3188:         $fname="$subdir/$fname";
                   3189:     }
1.1090    raeburn  3190:     if ($context eq 'coursedoc') {
1.638     albertel 3191: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3192: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3193:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3194:             return &finishuserfileupload($docuname,$docudom,
                   3195: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3196: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3197:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3198:         } else {
1.1218    raeburn  3199:             if ($env{'form.folder'}) {
                   3200:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3201:             }
1.638     albertel 3202:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3203: 				       $fname,$formname,$parser,
1.1095    raeburn  3204: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3205:         }
1.719     banghart 3206:     } elsif (defined($destuname)) {
                   3207:         my $docuname=$destuname;
                   3208:         my $docudom=$destudom;
1.860     raeburn  3209: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3210: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3211:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3212:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3213:     } else {
1.638     albertel 3214:         my $docuname=$env{'user.name'};
                   3215:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3216:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3217:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3218:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3219:         }
1.860     raeburn  3220: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3221: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3222:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3223:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3224:     }
1.271     www      3225: }
                   3226: 
                   3227: sub finishuserfileupload {
1.860     raeburn  3228:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3229:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3230:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3231:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3232:   
1.860     raeburn  3233:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3234:     $file=$fname;
                   3235:     if ($fname=~m|/|) {
                   3236:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3237: 	$path.=$fnamepath.'/';
                   3238:     }
1.259     www      3239:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3240:     my $count;
                   3241:     for ($count=4;$count<=$#parts;$count++) {
                   3242:         $filepath.="/$parts[$count]";
                   3243:         if ((-e $filepath)!=1) {
                   3244: 	    mkdir($filepath,0777);
                   3245:         }
                   3246:     }
1.984     neumanie 3247: 
1.258     www      3248: # Save the file
                   3249:     {
1.701     albertel 3250: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3251: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3252: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3253: 	    return '/adm/notfound.html';
                   3254: 	}
1.1090    raeburn  3255:         if ($context eq 'overwrite') {
1.1117    foxr     3256:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3257:             my $target = $filepath.'/'.$file;
                   3258:             if (-e $source) {
                   3259:                 my @info = stat($source);
                   3260:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3261:                     unless (&File::Copy::move($source,$target)) {
                   3262:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3263:                         return "Moving from $source failed";
                   3264:                     }
                   3265:                 } else {
                   3266:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3267:                 }
                   3268:             } else {
                   3269:                 return "Temporary file: $source missing";
                   3270:             }
                   3271:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3272: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3273: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3274: 	    return '/adm/notfound.html';
                   3275: 	}
1.570     albertel 3276: 	close(FH);
1.1051    raeburn  3277:         if ($resizewidth && $resizeheight) {
                   3278:             my $mm = new File::MMagic;
                   3279:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3280:             if ($mime_type =~ m{^image/}) {
                   3281: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3282:             }  
1.977     amueller 3283: 	}
1.258     www      3284:     }
1.1152    raeburn  3285:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3286:         if (ref($mimetype)) {
                   3287:             if ($$mimetype eq '') {
                   3288:                 my $mm = new File::MMagic;
                   3289:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3290:                 $$mimetype = $type;
                   3291:             }
                   3292:         }
                   3293:     }
1.637     raeburn  3294:     if ($parser eq 'parse') {
1.1152    raeburn  3295:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3296:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3297:                                                        $allfiles,$codebase);
                   3298:             unless ($parse_result eq 'ok') {
                   3299:                 &logthis('Failed to parse '.$filepath.$file.
                   3300: 	   	         ' for embedded media: '.$parse_result); 
                   3301:             }
1.637     raeburn  3302:         }
                   3303:     }
1.860     raeburn  3304:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3305:         my $input = $filepath.'/'.$file;
                   3306:         my $output = $filepath.'/'.'tn-'.$file;
                   3307:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3308:         system("convert -sample $thumbsize $input $output");
                   3309:         if (-e $filepath.'/'.'tn-'.$file) {
                   3310:             $fetchthumb  = 1; 
                   3311:         }
                   3312:     }
1.858     raeburn  3313:  
1.259     www      3314: # Notify homeserver to grep it
                   3315: #
1.984     neumanie 3316:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3317:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3318:     if ($fetchresult eq 'ok') {
1.860     raeburn  3319:         if ($fetchthumb) {
                   3320:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3321:             if ($thumbresult ne 'ok') {
                   3322:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3323:                          $docuhome.': '.$thumbresult);
                   3324:             }
                   3325:         }
1.259     www      3326: #
1.258     www      3327: # Return the URL to it
1.494     albertel 3328:         return '/uploaded/'.$path.$file;
1.263     www      3329:     } else {
1.494     albertel 3330:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3331: 		 ': '.$fetchresult);
1.263     www      3332:         return '/adm/notfound.html';
1.858     raeburn  3333:     }
1.493     albertel 3334: }
                   3335: 
1.637     raeburn  3336: sub extract_embedded_items {
1.961     raeburn  3337:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3338:     my @state = ();
1.1164    raeburn  3339:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3340:     my %javafiles = (
                   3341:                       codebase => '',
                   3342:                       code => '',
                   3343:                       archive => ''
                   3344:                     );
                   3345:     my %mediafiles = (
                   3346:                       src => '',
                   3347:                       movie => '',
                   3348:                      );
1.648     raeburn  3349:     my $p;
                   3350:     if ($content) {
                   3351:         $p = HTML::LCParser->new($content);
                   3352:     } else {
1.961     raeburn  3353:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3354:     }
1.641     albertel 3355:     while (my $t=$p->get_token()) {
1.640     albertel 3356: 	if ($t->[0] eq 'S') {
                   3357: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3358: 	    push(@state, $tagname);
1.648     raeburn  3359:             if (lc($tagname) eq 'allow') {
                   3360:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3361:             }
1.640     albertel 3362: 	    if (lc($tagname) eq 'img') {
                   3363: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3364: 	    }
1.886     albertel 3365: 	    if (lc($tagname) eq 'a') {
1.1221  ! raeburn  3366:                 unless ($attr->{'href'} =~ /^#/) {
        !          3367:                     &add_filetype($allfiles,$attr->{'href'},'href');
        !          3368:                 }
1.886     albertel 3369: 	    }
1.645     raeburn  3370:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3371:                 my $src;
1.645     raeburn  3372:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3373:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3374:                 } else {
1.1164    raeburn  3375:                     if ($attr->{'src'} ne '') {
                   3376:                         $src = $attr->{'src'};
                   3377:                         &add_filetype($allfiles,$src,'src');
                   3378:                     }
                   3379:                 }
                   3380:                 my $text = $p->get_trimmed_text();
                   3381:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3382:                     my @swfargs = split(/,/,$1);
                   3383:                     foreach my $item (@swfargs) {
                   3384:                         $item =~ s/["']//g;
                   3385:                         $item =~ s/^\s+//;
                   3386:                         $item =~ s/\s+$//;
                   3387:                     }
                   3388:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3389:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3390:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3391:                         } else {
                   3392:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3393:                         }
                   3394:                     }
1.645     raeburn  3395:                 }
                   3396:             }
                   3397:             if (lc($tagname) eq 'link') {
                   3398:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3399:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3400:                 }
                   3401:             }
1.640     albertel 3402: 	    if (lc($tagname) eq 'object' ||
                   3403: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3404: 		foreach my $item (keys(%javafiles)) {
                   3405: 		    $javafiles{$item} = '';
                   3406: 		}
1.1164    raeburn  3407:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3408:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3409:                 }
1.640     albertel 3410: 	    }
                   3411: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3412: 		my $name = lc($attr->{'name'});
                   3413: 		foreach my $item (keys(%javafiles)) {
                   3414: 		    if ($name eq $item) {
                   3415: 			$javafiles{$item} = $attr->{'value'};
                   3416: 			last;
                   3417: 		    }
                   3418: 		}
1.1164    raeburn  3419:                 my $pathfrom;
1.640     albertel 3420: 		foreach my $item (keys(%mediafiles)) {
                   3421: 		    if ($name eq $item) {
1.1164    raeburn  3422:                         $pathfrom = $attr->{'value'};
                   3423:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3424: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3425: 			last;
                   3426: 		    }
                   3427: 		}
1.1164    raeburn  3428:                 if ($name eq 'flashvars') {
                   3429:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3430:                 }
                   3431:                 if ($pathfrom ne '') {
                   3432:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3433:                                          $pathfrom);
                   3434:                 }
1.640     albertel 3435: 	    }
                   3436: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3437: 		foreach my $item (keys(%javafiles)) {
                   3438: 		    if ($attr->{$item}) {
                   3439: 			$javafiles{$item} = $attr->{$item};
                   3440: 			last;
                   3441: 		    }
                   3442: 		}
                   3443: 		foreach my $item (keys(%mediafiles)) {
                   3444: 		    if ($attr->{$item}) {
                   3445: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3446: 			last;
                   3447: 		    }
                   3448: 		}
1.1164    raeburn  3449:                 if (lc($tagname) eq 'embed') {
                   3450:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3451:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3452:                                              $attr->{'src'});
                   3453:                     }
                   3454:                 }
1.640     albertel 3455: 	    }
1.1164    raeburn  3456:             if ($t->[4] =~ m{/>$}) {
                   3457:                 pop(@state);  
                   3458:             }
1.640     albertel 3459: 	} elsif ($t->[0] eq 'E') {
                   3460: 	    my ($tagname) = ($t->[1]);
                   3461: 	    if ($javafiles{'codebase'} ne '') {
                   3462: 		$javafiles{'codebase'} .= '/';
                   3463: 	    }  
                   3464: 	    if (lc($tagname) eq 'applet' ||
                   3465: 		lc($tagname) eq 'object' ||
                   3466: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3467: 		) {
                   3468: 		foreach my $item (keys(%javafiles)) {
                   3469: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3470: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3471: 			&add_filetype($allfiles,$file,$item);
                   3472: 		    }
                   3473: 		}
                   3474: 	    } 
                   3475: 	    pop @state;
                   3476: 	}
                   3477:     }
1.1164    raeburn  3478:     foreach my $id (sort(keys(%flashvars))) {
                   3479:         if ($shockwave{$id} ne '') {
                   3480:             my @pairs = split(/\&/,$flashvars{$id});
                   3481:             foreach my $pair (@pairs) {
                   3482:                 my ($key,$value) = split(/\=/,$pair);
                   3483:                 if ($key eq 'thumb') {
                   3484:                     &add_filetype($allfiles,$value,$key);
                   3485:                 } elsif ($key eq 'content') {
                   3486:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3487:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3488:                     if ($ext ne '') {
                   3489:                         &add_filetype($allfiles,$path.$value,$ext);
                   3490:                     }
                   3491:                 }
                   3492:             }
                   3493:         }
                   3494:     }
1.637     raeburn  3495:     return 'ok';
                   3496: }
                   3497: 
1.639     albertel 3498: sub add_filetype {
                   3499:     my ($allfiles,$file,$type)=@_;
                   3500:     if (exists($allfiles->{$file})) {
                   3501: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3502: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3503: 	}
                   3504:     } else {
                   3505: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3506:     }
                   3507: }
                   3508: 
1.1164    raeburn  3509: sub embedded_dependency {
                   3510:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3511:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3512:         if (($identifier ne '') &&
                   3513:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3514:             ($pathfrom ne '')) {
                   3515:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3516:             foreach my $dep (@{$related->{$identifier}}) {
                   3517:                 &add_filetype($allfiles,$path.$dep,'object');
                   3518:             }
                   3519:         }
                   3520:     }
                   3521:     return;
                   3522: }
                   3523: 
1.493     albertel 3524: sub removeuploadedurl {
1.984     neumanie 3525:     my ($url)=@_;	
                   3526:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3527:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3528: }
                   3529: 
                   3530: sub removeuserfile {
                   3531:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3532:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3533:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3534:     if ($result eq 'ok') {	
1.798     raeburn  3535:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3536:             my $metafile = $fname.'.meta';
                   3537:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3538: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3539:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3540:             my $sqlresult = 
1.823     albertel 3541:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3542:                                         'portfolio_metadata',$group,
                   3543:                                         'delete');
1.798     raeburn  3544:         }
                   3545:     }
                   3546:     return $result;
1.257     www      3547: }
1.15      www      3548: 
1.530     albertel 3549: sub mkdiruserfile {
                   3550:     my ($docuname,$docudom,$dir)=@_;
                   3551:     my $home=&homeserver($docuname,$docudom);
                   3552:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3553: }
                   3554: 
1.531     albertel 3555: sub renameuserfile {
                   3556:     my ($docuname,$docudom,$old,$new)=@_;
                   3557:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3558:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3559:                         &escape("$old").':'.&escape("$new"),$home);
                   3560:     if ($result eq 'ok') {
                   3561:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3562:             my $oldmeta = $old.'.meta';
                   3563:             my $newmeta = $new.'.meta';
                   3564:             my $metaresult = 
                   3565:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3566: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3567:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3568:             my $sqlresult = 
1.823     albertel 3569:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3570:                                         'portfolio_metadata',$group,
                   3571:                                         'delete');
1.798     raeburn  3572:         }
                   3573:     }
                   3574:     return $result;
1.531     albertel 3575: }
                   3576: 
1.14      www      3577: # ------------------------------------------------------------------------- Log
                   3578: 
                   3579: sub log {
                   3580:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3581:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3582: }
                   3583: 
                   3584: # ------------------------------------------------------------------ Course Log
1.352     www      3585: #
                   3586: # This routine flushes several buffers of non-mission-critical nature
                   3587: #
1.157     www      3588: 
                   3589: sub flushcourselogs {
1.352     www      3590:     &logthis('Flushing log buffers');
                   3591: #
                   3592: # course logs
                   3593: # This is a log of all transactions in a course, which can be used
                   3594: # for data mining purposes
                   3595: #
                   3596: # It also collects the courseid database, which lists last transaction
                   3597: # times and course titles for all courseids
                   3598: #
                   3599:     my %courseidbuffer=();
1.921     raeburn  3600:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3601:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3602: 		          &escape($courselogs{$crsid}),
                   3603: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3604: 	    delete $courselogs{$crsid};
                   3605:         } else {
                   3606:             &logthis('Failed to flush log buffer for '.$crsid);
                   3607:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3608:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3609:                         " exceeded maximum size, deleting.</font>");
                   3610:                delete $courselogs{$crsid};
                   3611:             }
1.352     www      3612:         }
1.920     raeburn  3613:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3614:             'description' => $coursedescrbuf{$crsid},
                   3615:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3616:             'type'        => $coursetypebuf{$crsid},
                   3617:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3618:         };
1.191     harris41 3619:     }
1.352     www      3620: #
                   3621: # Write course id database (reverse lookup) to homeserver of courses 
                   3622: # Is used in pickcourse
                   3623: #
1.840     albertel 3624:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3625:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3626:                                     $courseidbuffer{$crs_home},
                   3627:                                     $crs_home,'timeonly');
1.352     www      3628:     }
                   3629: #
                   3630: # File accesses
                   3631: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3632: #
1.449     matthew  3633:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3634:         if ($entry =~ /___count$/) {
                   3635:             my ($dom,$name);
1.807     albertel 3636:             ($dom,$name,undef)=
1.811     albertel 3637: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3638:             if (! defined($dom) || $dom eq '' || 
                   3639:                 ! defined($name) || $name eq '') {
1.620     albertel 3640:                 my $cid = $env{'request.course.id'};
                   3641:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3642:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3643:             }
1.450     matthew  3644:             my $value = $accesshash{$entry};
                   3645:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3646:             my %temphash=($url => $value);
1.449     matthew  3647:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3648:             if ($result eq 'ok') {
                   3649:                 delete $accesshash{$entry};
                   3650:             }
                   3651:         } else {
1.811     albertel 3652:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3653:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3654:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3655:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3656:                 delete $accesshash{$entry};
                   3657:             }
1.185     www      3658:         }
1.191     harris41 3659:     }
1.352     www      3660: #
                   3661: # Roles
                   3662: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3663: #
1.800     albertel 3664:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3665:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3666: 	    split(/\:/,$entry);
                   3667:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3668:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3669:                 $rudom,$runame) eq 'ok') {
                   3670: 	    delete $userrolehash{$entry};
                   3671:         }
                   3672:     }
1.662     raeburn  3673: #
                   3674: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3675: #
                   3676:     my %domrolebuffer = ();
1.1000    raeburn  3677:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3678:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3679:         if ($domrolebuffer{$rudom}) {
                   3680:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3681:                       '='.&escape($domainrolehash{$entry});
                   3682:         } else {
                   3683:             $domrolebuffer{$rudom}.=&escape($entry).
                   3684:                       '='.&escape($domainrolehash{$entry});
                   3685:         }
                   3686:         delete $domainrolehash{$entry};
                   3687:     }
                   3688:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3689: 	my %servers = &get_servers($dom,'library');
                   3690: 	foreach my $tryserver (keys(%servers)) {
                   3691: 	    unless (&reply('domroleput:'.$dom.':'.
                   3692: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3693: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3694: 	    }
1.662     raeburn  3695:         }
                   3696:     }
1.186     www      3697:     $dumpcount++;
1.157     www      3698: }
                   3699: 
                   3700: sub courselog {
                   3701:     my $what=shift;
1.158     www      3702:     $what=time.':'.$what;
1.620     albertel 3703:     unless ($env{'request.course.id'}) { return ''; }
                   3704:     $coursedombuf{$env{'request.course.id'}}=
                   3705:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3706:     $coursenumbuf{$env{'request.course.id'}}=
                   3707:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3708:     $coursehombuf{$env{'request.course.id'}}=
                   3709:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3710:     $coursedescrbuf{$env{'request.course.id'}}=
                   3711:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3712:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3713:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3714:     $courseownerbuf{$env{'request.course.id'}}=
                   3715:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3716:     $coursetypebuf{$env{'request.course.id'}}=
                   3717:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3718:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3719: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3720:     } else {
1.620     albertel 3721: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3722:     }
1.620     albertel 3723:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3724: 	&flushcourselogs();
                   3725:     }
1.158     www      3726: }
                   3727: 
                   3728: sub courseacclog {
                   3729:     my $fnsymb=shift;
1.620     albertel 3730:     unless ($env{'request.course.id'}) { return ''; }
                   3731:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3732:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3733:         $what.=':POST';
1.583     matthew  3734:         # FIXME: Probably ought to escape things....
1.800     albertel 3735: 	foreach my $key (keys(%env)) {
                   3736:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3737:                 my $formitem = $1;
                   3738:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3739:                     $what.=':'.$formitem.'='.$env{$key};
                   3740:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3741:                     $what.=':'.$formitem.'='.$env{$key};
                   3742:                 }
1.158     www      3743:             }
1.191     harris41 3744:         }
1.583     matthew  3745:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3746:         # FIXME: We should not be depending on a form parameter that someone
                   3747:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3748:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3749:             $what.= ':POST';
                   3750:             # FIXME: Probably ought to escape things....
                   3751:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3752:                                  'crsdiscuss') {
1.620     albertel 3753:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3754:             }
                   3755:         }
1.158     www      3756:     }
                   3757:     &courselog($what);
1.149     www      3758: }
                   3759: 
1.185     www      3760: sub countacc {
                   3761:     my $url=&declutter(shift);
1.458     matthew  3762:     return if (! defined($url) || $url eq '');
1.620     albertel 3763:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3764: #
                   3765: # Mark that this url was used in this course
                   3766: #
1.620     albertel 3767:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3768: #
                   3769: # Increase the access count for this resource in this child process
                   3770: #
1.281     www      3771:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3772:     $accesshash{$key}++;
1.185     www      3773: }
1.349     www      3774: 
1.361     www      3775: sub linklog {
                   3776:     my ($from,$to)=@_;
                   3777:     $from=&declutter($from);
                   3778:     $to=&declutter($to);
                   3779:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3780:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3781: }
1.1160    www      3782: 
                   3783: sub statslog {
                   3784:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3785:     if ($users<2) { return; }
                   3786:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3787:             'course'       => $env{'request.course.id'},
                   3788:             'sections'     => '"all"',
                   3789:             'num_students' => $users,
                   3790:             'part'         => $part,
                   3791:             'symb'         => $symb,
                   3792:             'mean_tries'   => $av_attempts,
                   3793:             'deg_of_diff'  => $degdiff});
                   3794:     foreach my $key (keys(%dynstore)) {
                   3795:         $accesshash{$key}=$dynstore{$key};
                   3796:     }
                   3797: }
1.361     www      3798:   
1.349     www      3799: sub userrolelog {
                   3800:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3801:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3802:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3803:        $userrolehash
                   3804:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3805:                     =$tend.':'.$tstart;
1.662     raeburn  3806:     }
1.1169    droeschl 3807:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3808:        $userrolehash
                   3809:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3810:                     =$tend.':'.$tstart;
                   3811:     }
1.1169    droeschl 3812:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3813:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3814:        $domainrolehash
                   3815:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3816:                     = $tend.':'.$tstart;
                   3817:     }
1.351     www      3818: }
                   3819: 
1.957     raeburn  3820: sub courserolelog {
                   3821:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3822:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3823:         my $cdom = $1;
                   3824:         my $cnum = $2;
                   3825:         my $sec = $3;
                   3826:         my $namespace = 'rolelog';
                   3827:         my %storehash = (
                   3828:                            role    => $trole,
                   3829:                            start   => $tstart,
                   3830:                            end     => $tend,
                   3831:                            selfenroll => $selfenroll,
                   3832:                            context    => $context,
                   3833:                         );
                   3834:         if ($trole eq 'gr') {
                   3835:             $namespace = 'groupslog';
                   3836:             $storehash{'group'} = $sec;
                   3837:         } else {
                   3838:             $storehash{'section'} = $sec;
                   3839:         }
1.1188    raeburn  3840:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3841:                    $domain,$cnum,$cdom);
1.1184    raeburn  3842:         if (($trole ne 'st') || ($sec ne '')) {
                   3843:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3844:         }
                   3845:     }
                   3846:     return;
                   3847: }
                   3848: 
1.1184    raeburn  3849: sub domainrolelog {
                   3850:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3851:     if ($area =~ m{^/($match_domain)/$}) {
                   3852:         my $cdom = $1;
                   3853:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3854:         my $namespace = 'rolelog';
                   3855:         my %storehash = (
                   3856:                            role    => $trole,
                   3857:                            start   => $tstart,
                   3858:                            end     => $tend,
                   3859:                            context => $context,
                   3860:                         );
1.1188    raeburn  3861:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3862:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3863:     }
                   3864:     return;
                   3865: 
                   3866: }
                   3867: 
                   3868: sub coauthorrolelog {
                   3869:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3870:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3871:         my $audom = $1;
                   3872:         my $auname = $2;
                   3873:         my $namespace = 'rolelog';
                   3874:         my %storehash = (
                   3875:                            role    => $trole,
                   3876:                            start   => $tstart,
                   3877:                            end     => $tend,
                   3878:                            context => $context,
                   3879:                         );
1.1188    raeburn  3880:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3881:                    $domain,$auname,$audom);
1.1184    raeburn  3882:     }
                   3883:     return;
                   3884: }
                   3885: 
1.351     www      3886: sub get_course_adv_roles {
1.948     raeburn  3887:     my ($cid,$codes) = @_;
1.620     albertel 3888:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3889:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3890:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3891:     my %nothide=();
1.800     albertel 3892:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3893:         if ($user !~ /:/) {
                   3894: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3895:         } else {
                   3896:             $nothide{$user}=1;
                   3897:         }
1.470     www      3898:     }
1.1219    raeburn  3899:     my @possdoms = ($coursehash{'domain'});
                   3900:     if ($coursehash{'checkforpriv'}) {
                   3901:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3902:     }
1.351     www      3903:     my %returnhash=();
                   3904:     my %dumphash=
                   3905:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3906:     my $now=time;
1.997     raeburn  3907:     my %privileged;
1.1000    raeburn  3908:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3909: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3910:         if (($tstart) && ($tstart<0)) { next; }
                   3911:         if (($tend) && ($tend<$now)) { next; }
                   3912:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3913:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3914: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  3915:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3916:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3917: 	if ($role eq 'cr') { next; }
1.948     raeburn  3918:         if ($codes) {
                   3919:             if ($section) { $role .= ':'.$section; }
                   3920:             if ($returnhash{$role}) {
                   3921:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3922:             } else {
                   3923:                 $returnhash{$role}=$username.':'.$domain;
                   3924:             }
1.351     www      3925:         } else {
1.988     raeburn  3926:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3927:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3928:             if ($returnhash{$key}) {
                   3929: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3930:             } else {
                   3931:                 $returnhash{$key}=$username.':'.$domain;
                   3932:             }
1.351     www      3933:         }
1.948     raeburn  3934:     }
1.400     www      3935:     return %returnhash;
                   3936: }
                   3937: 
                   3938: sub get_my_roles {
1.937     raeburn  3939:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3940:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3941:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3942:     my (%dumphash,%nothide);
1.1086    raeburn  3943:     if ($context eq 'userroles') {
1.1166    raeburn  3944:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3945:     } else {
1.1219    raeburn  3946:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3947:         if ($hidepriv) {
                   3948:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3949:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3950:                 if ($user !~ /:/) {
                   3951:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3952:                 } else {
                   3953:                     $nothide{$user} = 1;
                   3954:                 }
                   3955:             }
                   3956:         }
1.858     raeburn  3957:     }
1.400     www      3958:     my %returnhash=();
                   3959:     my $now=time;
1.999     raeburn  3960:     my %privileged;
1.800     albertel 3961:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3962:         my ($role,$tend,$tstart);
                   3963:         if ($context eq 'userroles') {
1.1149    raeburn  3964:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3965: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3966:         } else {
                   3967:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3968:         }
1.400     www      3969:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3970:         my $status = 'active';
1.939     raeburn  3971:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3972:             $status = 'previous';
                   3973:         } 
                   3974:         if (($tstart) && ($now<$tstart)) {
                   3975:             $status = 'future';
                   3976:         }
                   3977:         if (ref($types) eq 'ARRAY') {
                   3978:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3979:                 next;
                   3980:             } 
                   3981:         } else {
                   3982:             if ($status ne 'active') {
                   3983:                 next;
                   3984:             }
                   3985:         }
1.867     raeburn  3986:         my ($rolecode,$username,$domain,$section,$area);
                   3987:         if ($context eq 'userroles') {
1.1186    raeburn  3988:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3989:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3990:         } else {
                   3991:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3992:         }
1.832     raeburn  3993:         if (ref($roledoms) eq 'ARRAY') {
                   3994:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3995:                 next;
                   3996:             }
                   3997:         }
                   3998:         if (ref($roles) eq 'ARRAY') {
                   3999:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4000:                 if ($role =~ /^cr\//) {
                   4001:                     if (!grep(/^cr$/,@{$roles})) {
                   4002:                         next;
                   4003:                     }
1.1104    raeburn  4004:                 } elsif ($role =~ /^gr\//) {
                   4005:                     if (!grep(/^gr$/,@{$roles})) {
                   4006:                         next;
                   4007:                     }
1.922     raeburn  4008:                 } else {
                   4009:                     next;
                   4010:                 }
1.832     raeburn  4011:             }
1.867     raeburn  4012:         }
1.937     raeburn  4013:         if ($hidepriv) {
1.1219    raeburn  4014:             my @privroles = ('dc','su');
1.999     raeburn  4015:             if ($context eq 'userroles') {
1.1219    raeburn  4016:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4017:             } else {
1.1219    raeburn  4018:                 my $possdoms = [$domain];
                   4019:                 if (ref($roledoms) eq 'ARRAY') {
                   4020:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4021:                 }
1.1219    raeburn  4022:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4023:                     if (!$nothide{$username.':'.$domain}) {
                   4024:                         next;
                   4025:                     }
                   4026:                 }
1.937     raeburn  4027:             }
                   4028:         }
1.933     raeburn  4029:         if ($withsec) {
                   4030:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4031:                 $tstart.':'.$tend;
                   4032:         } else {
                   4033:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4034:         }
1.832     raeburn  4035:     }
1.373     www      4036:     return %returnhash;
1.399     www      4037: }
                   4038: 
                   4039: # ----------------------------------------------------- Frontpage Announcements
                   4040: #
                   4041: #
                   4042: 
                   4043: sub postannounce {
                   4044:     my ($server,$text)=@_;
1.844     albertel 4045:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4046:     unless ($text=~/\w/) { $text=''; }
                   4047:     return &reply('setannounce:'.&escape($text),$server);
                   4048: }
                   4049: 
                   4050: sub getannounce {
1.448     albertel 4051: 
                   4052:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4053: 	my $announcement='';
1.800     albertel 4054: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4055: 	close($fh);
1.399     www      4056: 	if ($announcement=~/\w/) { 
                   4057: 	    return 
                   4058:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4059:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4060: 	} else {
                   4061: 	    return '';
                   4062: 	}
                   4063:     } else {
                   4064: 	return '';
                   4065:     }
1.351     www      4066: }
1.353     www      4067: 
                   4068: # ---------------------------------------------------------- Course ID routines
                   4069: # Deal with domain's nohist_courseid.db files
                   4070: #
                   4071: 
                   4072: sub courseidput {
1.921     raeburn  4073:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4074:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4075:     my $outcome;
                   4076:     if ($caller eq 'timeonly') {
                   4077:         my $cids = '';
                   4078:         foreach my $item (keys(%$storehash)) {
                   4079:             $cids.=&escape($item).'&';
                   4080:         }
                   4081:         $cids=~s/\&$//;
                   4082:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4083:                           $coursehome);       
                   4084:     } else {
                   4085:         my $items = '';
                   4086:         foreach my $item (keys(%$storehash)) {
                   4087:             $items.= &escape($item).'='.
                   4088:                      &freeze_escape($$storehash{$item}).'&';
                   4089:         }
                   4090:         $items=~s/\&$//;
                   4091:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4092:                           $coursehome);
1.918     raeburn  4093:     }
                   4094:     if ($outcome eq 'unknown_cmd') {
                   4095:         my $what;
                   4096:         foreach my $cid (keys(%$storehash)) {
                   4097:             $what .= &escape($cid).'=';
1.921     raeburn  4098:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4099:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4100:             }
                   4101:             $what =~ s/\:$/&/;
                   4102:         }
                   4103:         $what =~ s/\&$//;  
                   4104:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4105:     } else {
                   4106:         return $outcome;
                   4107:     }
1.353     www      4108: }
                   4109: 
                   4110: sub courseiddump {
1.921     raeburn  4111:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4112:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4113:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4114:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4115:     my $as_hash = 1;
                   4116:     my %returnhash;
                   4117:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4118:     my %libserv = &all_library();
                   4119:     foreach my $tryserver (keys(%libserv)) {
                   4120:         if ( (  $hostidflag == 1 
                   4121: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4122: 	     || (!defined($hostidflag)) ) {
                   4123: 
1.918     raeburn  4124: 	    if (($domfilter eq '') ||
                   4125: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4126:                 my $rep;
                   4127:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4128:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4129:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4130:                                 &escape($descfilter), &escape($instcodefilter), 
                   4131:                                 &escape($ownerfilter), &escape($coursefilter),
                   4132:                                 &escape($typefilter), &escape($regexp_ok), 
                   4133:                                 $as_hash, &escape($selfenrollonly), 
                   4134:                                 &escape($catfilter), $showhidden, $caller, 
                   4135:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4136:                                 &escape($createdbefore), &escape($createdafter), 
                   4137:                                 &escape($creationcontext), $domcloner)));
                   4138:                 } else {
                   4139:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4140:                              $sincefilter.':'.&escape($descfilter).':'.
                   4141:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4142:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4143:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4144:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4145:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4146:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4147:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4148:                              &escape($creationcontext).':'.$domcloner,
                   4149:                              $tryserver);
                   4150:                 }
                   4151:                      
1.918     raeburn  4152:                 my @pairs=split(/\&/,$rep);
                   4153:                 foreach my $item (@pairs) {
                   4154:                     my ($key,$value)=split(/\=/,$item,2);
                   4155:                     $key = &unescape($key);
                   4156:                     next if ($key =~ /^error: 2 /);
                   4157:                     my $result = &thaw_unescape($value);
                   4158:                     if (ref($result) eq 'HASH') {
                   4159:                         $returnhash{$key}=$result;
                   4160:                     } else {
1.921     raeburn  4161:                         my @responses = split(/:/,$value);
                   4162:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4163:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4164:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4165:                         }
1.1008    raeburn  4166:                     }
1.353     www      4167:                 }
                   4168:             }
                   4169:         }
                   4170:     }
                   4171:     return %returnhash;
                   4172: }
                   4173: 
1.1055    raeburn  4174: sub courselastaccess {
                   4175:     my ($cdom,$cnum,$hostidref) = @_;
                   4176:     my %returnhash;
                   4177:     if ($cdom && $cnum) {
                   4178:         my $chome = &homeserver($cnum,$cdom);
                   4179:         if ($chome ne 'no_host') {
                   4180:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4181:             &extract_lastaccess(\%returnhash,$rep);
                   4182:         }
                   4183:     } else {
                   4184:         if (!$cdom) { $cdom=''; }
                   4185:         my %libserv = &all_library();
                   4186:         foreach my $tryserver (keys(%libserv)) {
                   4187:             if (ref($hostidref) eq 'ARRAY') {
                   4188:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4189:             } 
                   4190:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4191:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4192:                 &extract_lastaccess(\%returnhash,$rep);
                   4193:             }
                   4194:         }
                   4195:     }
                   4196:     return %returnhash;
                   4197: }
                   4198: 
                   4199: sub extract_lastaccess {
                   4200:     my ($returnhash,$rep) = @_;
                   4201:     if (ref($returnhash) eq 'HASH') {
                   4202:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4203:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4204:                  $rep eq '') {
                   4205:             my @pairs=split(/\&/,$rep);
                   4206:             foreach my $item (@pairs) {
                   4207:                 my ($key,$value)=split(/\=/,$item,2);
                   4208:                 $key = &unescape($key);
                   4209:                 next if ($key =~ /^error: 2 /);
                   4210:                 $returnhash->{$key} = &thaw_unescape($value);
                   4211:             }
                   4212:         }
                   4213:     }
                   4214:     return;
                   4215: }
                   4216: 
1.658     raeburn  4217: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4218: 
                   4219: sub dcmailput {
1.685     raeburn  4220:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4221:     my $status = &Apache::lonnet::critical(
1.740     www      4222:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4223:        &escape($message),$server);
1.662     raeburn  4224:     return $status;
                   4225: }
                   4226: 
1.658     raeburn  4227: sub dcmaildump {
                   4228:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4229:     my %returnhash=();
1.846     albertel 4230: 
                   4231:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4232:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4233:                                                          &escape($enddate).':';
                   4234: 	my @esc_senders=map { &escape($_)} @$senders;
                   4235: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4236: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4237:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4238:             if (($key) && ($value)) {
                   4239:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4240:             }
                   4241:         }
                   4242:     }
                   4243:     return %returnhash;
                   4244: }
1.662     raeburn  4245: # ---------------------------------------------------------- Domain roles
                   4246: 
                   4247: sub get_domain_roles {
                   4248:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4249:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4250:         $startdate = '.';
                   4251:     }
1.1018    raeburn  4252:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4253:         $enddate = '.';
                   4254:     }
1.922     raeburn  4255:     my $rolelist;
                   4256:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4257:         $rolelist = join('&',@{$roles});
1.922     raeburn  4258:     }
1.662     raeburn  4259:     my %personnel = ();
1.841     albertel 4260: 
                   4261:     my %servers = &get_servers($dom,'library');
                   4262:     foreach my $tryserver (keys(%servers)) {
                   4263: 	%{$personnel{$tryserver}}=();
                   4264: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4265: 					    &escape($startdate).':'.
                   4266: 					    &escape($enddate).':'.
                   4267: 					    &escape($rolelist), $tryserver))) {
                   4268: 	    my ($key,$value) = split(/\=/,$line,2);
                   4269: 	    if (($key) && ($value)) {
                   4270: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4271: 	    }
                   4272: 	}
1.662     raeburn  4273:     }
                   4274:     return %personnel;
                   4275: }
1.658     raeburn  4276: 
1.1057    www      4277: # ----------------------------------------------------------- Interval timing 
1.149     www      4278: 
1.1153    www      4279: {
                   4280: # Caches needed for speedup of navmaps
                   4281: # We don't want to cache this for very long at all (5 seconds at most)
                   4282: # 
                   4283: # The user for whom we cache
                   4284: my $cachedkey='';
                   4285: # The cached times for this user
                   4286: my %cachedtimes=();
                   4287: # When this was last done
                   4288: my $cachedtime=();
                   4289: 
                   4290: sub load_all_first_access {
1.1154    raeburn  4291:     my ($uname,$udom)=@_;
1.1156    www      4292:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4293:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4294:         return;
                   4295:     }
                   4296:     $cachedtime=time;
                   4297:     $cachedkey=$uname.':'.$udom;
                   4298:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4299: }
                   4300: 
1.504     albertel 4301: sub get_first_access {
1.1162    raeburn  4302:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4303:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4304:     if ($argsymb) { $symb=$argsymb; }
                   4305:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4306:     if ($argmap) { $map = $argmap; }
1.926     albertel 4307:     if ($type eq 'course') {
                   4308: 	$res='course';
                   4309:     } elsif ($type eq 'map') {
1.588     albertel 4310: 	$res=&symbread($map);
                   4311:     } else {
                   4312: 	$res=$symb;
                   4313:     }
1.1153    www      4314:     &load_all_first_access($uname,$udom);
                   4315:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4316: }
                   4317: 
                   4318: sub set_first_access {
1.1162    raeburn  4319:     my ($type,$interval)=@_;
1.790     albertel 4320:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4321:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4322:     if ($type eq 'course') {
                   4323: 	$res='course';
                   4324:     } elsif ($type eq 'map') {
1.588     albertel 4325: 	$res=&symbread($map);
                   4326:     } else {
                   4327: 	$res=$symb;
                   4328:     }
1.1153    www      4329:     $cachedkey='';
1.1162    raeburn  4330:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4331:     if (!$firstaccess) {
1.1162    raeburn  4332:         my $start = time;
                   4333: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4334:                           $udom,$uname);
                   4335:         if ($putres eq 'ok') {
                   4336:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4337:                  $udom,$uname); 
                   4338:             &appenv(
                   4339:                      {
                   4340:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4341:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4342:                      }
                   4343:                   );
                   4344:         }
                   4345:         return $putres;
1.505     albertel 4346:     }
                   4347:     return 'already_set';
1.504     albertel 4348: }
1.1153    www      4349: }
1.110     www      4350: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4351: 
                   4352: sub expirespread {
                   4353:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4354:     my $cid=$env{'request.course.id'}; 
1.110     www      4355:     if ($cid) {
                   4356:        my $now=time;
                   4357:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4358:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4359:                             $env{'course.'.$cid.'.num'}.
1.110     www      4360: 	        	    ':nohist_expirationdates:'.
                   4361:                             &escape($key).'='.$now,
1.620     albertel 4362:                             $env{'course.'.$cid.'.home'})
1.110     www      4363:     }
                   4364:     return 'ok';
1.14      www      4365: }
                   4366: 
1.109     www      4367: # ----------------------------------------------------- Devalidate Spreadsheets
                   4368: 
                   4369: sub devalidate {
1.325     www      4370:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4371:     my $cid=$env{'request.course.id'}; 
1.109     www      4372:     if ($cid) {
1.391     matthew  4373:         # delete the stored spreadsheets for
                   4374:         # - the student level sheet of this user in course's homespace
                   4375:         # - the assessment level sheet for this resource 
                   4376:         #   for this user in user's homespace
1.553     albertel 4377: 	# - current conditional state info
1.325     www      4378: 	my $key=$uname.':'.$udom.':';
1.109     www      4379:         my $status=
1.299     matthew  4380: 	    &del('nohist_calculatedsheets',
1.391     matthew  4381: 		 [$key.'studentcalc:'],
1.620     albertel 4382: 		 $env{'course.'.$cid.'.domain'},
                   4383: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4384: 		.' '.
                   4385: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4386: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4387:         unless ($status eq 'ok ok') {
                   4388:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4389:                     $uname.' at '.$udom.' for '.
1.109     www      4390: 		    $symb.': '.$status);
1.133     albertel 4391:         }
1.553     albertel 4392: 	&delenv('user.state.'.$cid);
1.109     www      4393:     }
                   4394: }
                   4395: 
1.265     albertel 4396: sub get_scalar {
                   4397:     my ($string,$end) = @_;
                   4398:     my $value;
                   4399:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4400: 	$value = $1;
                   4401:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4402: 	$value = $1;
                   4403:     }
                   4404:     return &unescape($value);
                   4405: }
                   4406: 
                   4407: sub array2str {
                   4408:   my (@array) = @_;
                   4409:   my $result=&arrayref2str(\@array);
                   4410:   $result=~s/^__ARRAY_REF__//;
                   4411:   $result=~s/__END_ARRAY_REF__$//;
                   4412:   return $result;
                   4413: }
                   4414: 
1.204     albertel 4415: sub arrayref2str {
                   4416:   my ($arrayref) = @_;
1.265     albertel 4417:   my $result='__ARRAY_REF__';
1.204     albertel 4418:   foreach my $elem (@$arrayref) {
1.265     albertel 4419:     if(ref($elem) eq 'ARRAY') {
                   4420:       $result.=&arrayref2str($elem).'&';
                   4421:     } elsif(ref($elem) eq 'HASH') {
                   4422:       $result.=&hashref2str($elem).'&';
                   4423:     } elsif(ref($elem)) {
                   4424:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4425:     } else {
                   4426:       $result.=&escape($elem).'&';
                   4427:     }
                   4428:   }
                   4429:   $result=~s/\&$//;
1.265     albertel 4430:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4431:   return $result;
                   4432: }
                   4433: 
1.168     albertel 4434: sub hash2str {
1.204     albertel 4435:   my (%hash) = @_;
                   4436:   my $result=&hashref2str(\%hash);
1.265     albertel 4437:   $result=~s/^__HASH_REF__//;
                   4438:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4439:   return $result;
                   4440: }
                   4441: 
                   4442: sub hashref2str {
                   4443:   my ($hashref)=@_;
1.265     albertel 4444:   my $result='__HASH_REF__';
1.800     albertel 4445:   foreach my $key (sort(keys(%$hashref))) {
                   4446:     if (ref($key) eq 'ARRAY') {
                   4447:       $result.=&arrayref2str($key).'=';
                   4448:     } elsif (ref($key) eq 'HASH') {
                   4449:       $result.=&hashref2str($key).'=';
                   4450:     } elsif (ref($key)) {
1.265     albertel 4451:       $result.='=';
1.800     albertel 4452:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4453:     } else {
1.1132    raeburn  4454: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4455:     }
                   4456: 
1.800     albertel 4457:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4458:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4459:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4460:       $result.=&hashref2str($hashref->{$key}).'&';
                   4461:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4462:        $result.='&';
1.800     albertel 4463:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4464:     } else {
1.800     albertel 4465:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4466:     }
                   4467:   }
1.168     albertel 4468:   $result=~s/\&$//;
1.265     albertel 4469:   $result .= '__END_HASH_REF__';
1.168     albertel 4470:   return $result;
                   4471: }
                   4472: 
                   4473: sub str2hash {
1.265     albertel 4474:     my ($string)=@_;
                   4475:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4476:     return %$hash;
                   4477: }
                   4478: 
                   4479: sub str2hashref {
1.168     albertel 4480:   my ($string) = @_;
1.265     albertel 4481: 
                   4482:   my %hash;
                   4483: 
                   4484:   if($string !~ /^__HASH_REF__/) {
                   4485:       if (! ($string eq '' || !defined($string))) {
                   4486: 	  $hash{'error'}='Not hash reference';
                   4487:       }
                   4488:       return (\%hash, $string);
                   4489:   }
                   4490: 
                   4491:   $string =~ s/^__HASH_REF__//;
                   4492: 
                   4493:   while($string !~ /^__END_HASH_REF__/) {
                   4494:       #key
                   4495:       my $key='';
                   4496:       if($string =~ /^__HASH_REF__/) {
                   4497:           ($key, $string)=&str2hashref($string);
                   4498:           if(defined($key->{'error'})) {
                   4499:               $hash{'error'}='Bad data';
                   4500:               return (\%hash, $string);
                   4501:           }
                   4502:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4503:           ($key, $string)=&str2arrayref($string);
                   4504:           if($key->[0] eq 'Array reference error') {
                   4505:               $hash{'error'}='Bad data';
                   4506:               return (\%hash, $string);
                   4507:           }
                   4508:       } else {
                   4509:           $string =~ s/^(.*?)=//;
1.267     albertel 4510: 	  $key=&unescape($1);
1.265     albertel 4511:       }
                   4512:       $string =~ s/^=//;
                   4513: 
                   4514:       #value
                   4515:       my $value='';
                   4516:       if($string =~ /^__HASH_REF__/) {
                   4517:           ($value, $string)=&str2hashref($string);
                   4518:           if(defined($value->{'error'})) {
                   4519:               $hash{'error'}='Bad data';
                   4520:               return (\%hash, $string);
                   4521:           }
                   4522:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4523:           ($value, $string)=&str2arrayref($string);
                   4524:           if($value->[0] eq 'Array reference error') {
                   4525:               $hash{'error'}='Bad data';
                   4526:               return (\%hash, $string);
                   4527:           }
                   4528:       } else {
                   4529: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4530:       }
                   4531:       $string =~ s/^&//;
                   4532: 
                   4533:       $hash{$key}=$value;
1.204     albertel 4534:   }
1.265     albertel 4535: 
                   4536:   $string =~ s/^__END_HASH_REF__//;
                   4537: 
                   4538:   return (\%hash, $string);
1.204     albertel 4539: }
                   4540: 
                   4541: sub str2array {
1.265     albertel 4542:     my ($string)=@_;
                   4543:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4544:     return @$array;
                   4545: }
                   4546: 
                   4547: sub str2arrayref {
1.204     albertel 4548:   my ($string) = @_;
1.265     albertel 4549:   my @array;
                   4550: 
                   4551:   if($string !~ /^__ARRAY_REF__/) {
                   4552:       if (! ($string eq '' || !defined($string))) {
                   4553: 	  $array[0]='Array reference error';
                   4554:       }
                   4555:       return (\@array, $string);
                   4556:   }
                   4557: 
                   4558:   $string =~ s/^__ARRAY_REF__//;
                   4559: 
                   4560:   while($string !~ /^__END_ARRAY_REF__/) {
                   4561:       my $value='';
                   4562:       if($string =~ /^__HASH_REF__/) {
                   4563:           ($value, $string)=&str2hashref($string);
                   4564:           if(defined($value->{'error'})) {
                   4565:               $array[0] ='Array reference error';
                   4566:               return (\@array, $string);
                   4567:           }
                   4568:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4569:           ($value, $string)=&str2arrayref($string);
                   4570:           if($value->[0] eq 'Array reference error') {
                   4571:               $array[0] ='Array reference error';
                   4572:               return (\@array, $string);
                   4573:           }
                   4574:       } else {
                   4575: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4576:       }
                   4577:       $string =~ s/^&//;
                   4578: 
                   4579:       push(@array, $value);
1.191     harris41 4580:   }
1.265     albertel 4581: 
                   4582:   $string =~ s/^__END_ARRAY_REF__//;
                   4583: 
                   4584:   return (\@array, $string);
1.168     albertel 4585: }
                   4586: 
1.167     albertel 4587: # -------------------------------------------------------------------Temp Store
                   4588: 
1.168     albertel 4589: sub tmpreset {
                   4590:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4591:   if (!$symb) {
                   4592:     $symb=&symbread();
1.620     albertel 4593:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4594:   }
                   4595:   $symb=escape($symb);
                   4596: 
1.620     albertel 4597:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4598:   $namespace=~s/\//\_/g;
                   4599:   $namespace=~s/\W//g;
                   4600: 
1.620     albertel 4601:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4602:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4603:   if ($domain eq 'public' && $stuname eq 'public') {
                   4604:       $stuname=$ENV{'REMOTE_ADDR'};
                   4605:   }
1.1117    foxr     4606:   my $path=LONCAPA::tempdir();
1.168     albertel 4607:   my %hash;
                   4608:   if (tie(%hash,'GDBM_File',
                   4609: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4610: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4611:     foreach my $key (keys(%hash)) {
1.180     albertel 4612:       if ($key=~ /:$symb/) {
1.168     albertel 4613: 	delete($hash{$key});
                   4614:       }
                   4615:     }
                   4616:   }
                   4617: }
                   4618: 
1.167     albertel 4619: sub tmpstore {
1.168     albertel 4620:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4621: 
                   4622:   if (!$symb) {
                   4623:     $symb=&symbread();
1.620     albertel 4624:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4625:   }
                   4626:   $symb=escape($symb);
                   4627: 
                   4628:   if (!$namespace) {
                   4629:     # I don't think we would ever want to store this for a course.
                   4630:     # it seems this will only be used if we don't have a course.
1.620     albertel 4631:     #$namespace=$env{'request.course.id'};
1.168     albertel 4632:     #if (!$namespace) {
1.620     albertel 4633:       $namespace=$env{'request.state'};
1.168     albertel 4634:     #}
                   4635:   }
                   4636:   $namespace=~s/\//\_/g;
                   4637:   $namespace=~s/\W//g;
1.620     albertel 4638:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4639:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4640:   if ($domain eq 'public' && $stuname eq 'public') {
                   4641:       $stuname=$ENV{'REMOTE_ADDR'};
                   4642:   }
1.168     albertel 4643:   my $now=time;
                   4644:   my %hash;
1.1117    foxr     4645:   my $path=LONCAPA::tempdir();
1.168     albertel 4646:   if (tie(%hash,'GDBM_File',
                   4647: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4648: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4649:     $hash{"version:$symb"}++;
                   4650:     my $version=$hash{"version:$symb"};
                   4651:     my $allkeys=''; 
                   4652:     foreach my $key (keys(%$storehash)) {
                   4653:       $allkeys.=$key.':';
1.591     albertel 4654:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4655:     }
                   4656:     $hash{"$version:$symb:timestamp"}=$now;
                   4657:     $allkeys.='timestamp';
                   4658:     $hash{"$version:keys:$symb"}=$allkeys;
                   4659:     if (untie(%hash)) {
                   4660:       return 'ok';
                   4661:     } else {
                   4662:       return "error:$!";
                   4663:     }
                   4664:   } else {
                   4665:     return "error:$!";
                   4666:   }
                   4667: }
1.167     albertel 4668: 
1.168     albertel 4669: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4670: 
1.168     albertel 4671: sub tmprestore {
                   4672:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4673: 
1.168     albertel 4674:   if (!$symb) {
                   4675:     $symb=&symbread();
1.620     albertel 4676:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4677:   }
                   4678:   $symb=escape($symb);
                   4679: 
1.620     albertel 4680:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4681: 
1.620     albertel 4682:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4683:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4684:   if ($domain eq 'public' && $stuname eq 'public') {
                   4685:       $stuname=$ENV{'REMOTE_ADDR'};
                   4686:   }
1.168     albertel 4687:   my %returnhash;
                   4688:   $namespace=~s/\//\_/g;
                   4689:   $namespace=~s/\W//g;
                   4690:   my %hash;
1.1117    foxr     4691:   my $path=LONCAPA::tempdir();
1.168     albertel 4692:   if (tie(%hash,'GDBM_File',
                   4693: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4694: 	  &GDBM_READER(),0640)) {
1.168     albertel 4695:     my $version=$hash{"version:$symb"};
                   4696:     $returnhash{'version'}=$version;
                   4697:     my $scope;
                   4698:     for ($scope=1;$scope<=$version;$scope++) {
                   4699:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4700:       my @keys=split(/:/,$vkeys);
                   4701:       my $key;
                   4702:       $returnhash{"$scope:keys"}=$vkeys;
                   4703:       foreach $key (@keys) {
1.591     albertel 4704: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4705: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4706:       }
                   4707:     }
1.168     albertel 4708:     if (!(untie(%hash))) {
                   4709:       return "error:$!";
                   4710:     }
                   4711:   } else {
                   4712:     return "error:$!";
                   4713:   }
                   4714:   return %returnhash;
1.167     albertel 4715: }
                   4716: 
1.9       www      4717: # ----------------------------------------------------------------------- Store
                   4718: 
                   4719: sub store {
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'};
                   4743: 
1.12      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.12      www      4748:     $namevalue=~s/\&$//;
1.187     www      4749:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4750:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4751: }
                   4752: 
1.47      www      4753: # -------------------------------------------------------------- Critical Store
                   4754: 
                   4755: sub cstore {
1.124     www      4756:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4757:     my $home='';
                   4758: 
1.168     albertel 4759:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4760: 
1.213     www      4761:     $symb=&symbclean($symb);
1.122     albertel 4762:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4763: 
1.620     albertel 4764:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4765:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4766: 
                   4767:     &devalidate($symb,$stuname,$domain);
1.109     www      4768: 
                   4769:     $symb=escape($symb);
1.187     www      4770:     if (!$namespace) { 
1.620     albertel 4771:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4772:           return ''; 
                   4773:        } 
                   4774:     }
1.620     albertel 4775:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4776: 
                   4777:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4778:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4779: 
1.47      www      4780:     my $namevalue='';
1.800     albertel 4781:     foreach my $key (keys(%$storehash)) {
                   4782:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4783:     }
1.47      www      4784:     $namevalue=~s/\&$//;
1.187     www      4785:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4786:     return critical
                   4787:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4788: }
                   4789: 
1.9       www      4790: # --------------------------------------------------------------------- Restore
                   4791: 
                   4792: sub restore {
1.124     www      4793:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4794:     my $home='';
                   4795: 
1.168     albertel 4796:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4797: 
1.122     albertel 4798:     if (!$symb) {
                   4799:       unless ($symb=escape(&symbread())) { return ''; }
                   4800:     } else {
1.213     www      4801:       $symb=&escape(&symbclean($symb));
1.122     albertel 4802:     }
1.188     www      4803:     if (!$namespace) { 
1.620     albertel 4804:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4805:           return ''; 
                   4806:        } 
                   4807:     }
1.620     albertel 4808:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4809:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4810:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4811:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4812: 
1.12      www      4813:     my %returnhash=();
1.800     albertel 4814:     foreach my $line (split(/\&/,$answer)) {
                   4815: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4816:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4817:     }
1.75      www      4818:     my $version;
                   4819:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4820:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4821:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4822:        }
1.75      www      4823:     }
1.13      www      4824:     return %returnhash;
1.34      www      4825: }
                   4826: 
                   4827: # ---------------------------------------------------------- Course Description
1.1118    foxr     4828: #
                   4829: #  
1.34      www      4830: 
                   4831: sub coursedescription {
1.731     albertel 4832:     my ($courseid,$args)=@_;
1.34      www      4833:     $courseid=~s/^\///;
1.49      www      4834:     $courseid=~s/\_/\//g;
1.34      www      4835:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4836:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4837:     my $normalid=$cdomain.'_'.$cnum;
                   4838:     # need to always cache even if we get errors otherwise we keep 
                   4839:     # trying and trying and trying to get the course description.
                   4840:     my %envhash=();
                   4841:     my %returnhash=();
1.731     albertel 4842:     
                   4843:     my $expiretime=600;
                   4844:     if ($env{'request.course.id'} eq $normalid) {
                   4845: 	$expiretime=120;
                   4846:     }
                   4847: 
                   4848:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4849:     if (!$args->{'freshen_cache'}
                   4850: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4851: 	foreach my $key (keys(%env)) {
                   4852: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4853: 	    my ($setting) = $1;
                   4854: 	    $returnhash{$setting} = $env{$key};
                   4855: 	}
                   4856: 	return %returnhash;
                   4857:     }
                   4858: 
1.1118    foxr     4859:     # get the data again
                   4860: 
1.731     albertel 4861:     if (!$args->{'one_time'}) {
                   4862: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4863:     }
1.811     albertel 4864: 
1.34      www      4865:     if ($chome ne 'no_host') {
1.302     albertel 4866:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4867:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4868: 	   my $username = $env{'user.name'}; # Defult username
                   4869: 	   if(defined $args->{'user'}) {
                   4870: 	       $username = $args->{'user'};
                   4871: 	   }
1.129     albertel 4872:            $returnhash{'home'}= $chome;
                   4873: 	   $returnhash{'domain'} = $cdomain;
                   4874: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4875:            if (!defined($returnhash{'type'})) {
                   4876:                $returnhash{'type'} = 'Course';
                   4877:            }
1.130     albertel 4878:            while (my ($name,$value) = each %returnhash) {
1.53      www      4879:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4880:            }
1.270     www      4881:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4882:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4883: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4884:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4885:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4886:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4887:        }
                   4888:     }
1.731     albertel 4889:     if (!$args->{'one_time'}) {
1.949     raeburn  4890: 	&appenv(\%envhash);
1.731     albertel 4891:     }
1.302     albertel 4892:     return %returnhash;
1.461     www      4893: }
                   4894: 
1.1080    raeburn  4895: sub update_released_required {
                   4896:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4897:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4898:         $cid = $env{'request.course.id'};
                   4899:         $cdom = $env{'course.'.$cid.'.domain'};
                   4900:         $cnum = $env{'course.'.$cid.'.num'};
                   4901:         $chome = $env{'course.'.$cid.'.home'};
                   4902:     }
                   4903:     if ($needsrelease) {
                   4904:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4905:         my $needsupdate;
                   4906:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4907:             $needsupdate = 1;
                   4908:         } else {
                   4909:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4910:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4911:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4912:                 $needsupdate = 1;
                   4913:             }
                   4914:         }
                   4915:         if ($needsupdate) {
                   4916:             my %needshash = (
                   4917:                              'internal.releaserequired' => $needsrelease,
                   4918:                             );
                   4919:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4920:             if ($putresult eq 'ok') {
                   4921:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4922:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4923:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4924:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4925:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4926:                 }
                   4927:             }
                   4928:         }
                   4929:     }
                   4930:     return;
                   4931: }
                   4932: 
1.461     www      4933: # -------------------------------------------------See if a user is privileged
                   4934: 
                   4935: sub privileged {
1.1219    raeburn  4936:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 4937:     my $now = time;
1.1219    raeburn  4938:     my $roles;
                   4939:     if (ref($possroles) eq 'ARRAY') {
                   4940:         $roles = $possroles; 
                   4941:     } else {
                   4942:         $roles = ['dc','su'];
                   4943:     }
                   4944:     if (ref($possdomains) eq 'ARRAY') {
                   4945:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   4946:         foreach my $dom (@{$possdomains}) {
                   4947:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   4948:                 (ref($privileged{$dom}) eq 'HASH')) {
                   4949:                 foreach my $role (@{$roles}) {
                   4950:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   4951:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   4952:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   4953:                             return 1 unless (($end && $end < $now) ||
                   4954:                                              ($start && $start > $now));
                   4955:                         }
                   4956:                     }
                   4957:                 }
                   4958:             }
                   4959:         }
                   4960:     } else {
                   4961:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4962:         my $now = time;
1.1170    droeschl 4963: 
1.1219    raeburn  4964:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 4965:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  4966:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 4967:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  4968:                         or ($tstart && $tstart > $now);
1.1170    droeschl 4969:             }
1.1219    raeburn  4970:         }
                   4971:     }
                   4972:     return 0;
                   4973: }
1.1170    droeschl 4974: 
1.1219    raeburn  4975: sub privileged_by_domain {
                   4976:     my ($domains,$roles) = @_;
                   4977:     my %privileged = ();
                   4978:     my $cachetime = 60*60*24;
                   4979:     my $now = time;
                   4980:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   4981:         return %privileged;
                   4982:     }
                   4983:     foreach my $dom (@{$domains}) {
                   4984:         next if (ref($privileged{$dom}) eq 'HASH');
                   4985:         my $needroles;
                   4986:         foreach my $role (@{$roles}) {
                   4987:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   4988:             if (defined($cached)) {
                   4989:                 if (ref($result) eq 'HASH') {
                   4990:                     $privileged{$dom}{$role} = $result;
                   4991:                 }
                   4992:             } else {
                   4993:                 $needroles = 1;
                   4994:             }
                   4995:         }
                   4996:         if ($needroles) {
                   4997:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   4998:             $privileged{$dom} = {};
                   4999:             foreach my $server (keys(%dompersonnel)) {
                   5000:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5001:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5002:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5003:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5004:                         next if ($end && $end < $now);
                   5005:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5006:                             $dompersonnel{$server}{$item};
                   5007:                     }
                   5008:                 }
                   5009:             }
                   5010:             if (ref($privileged{$dom}) eq 'HASH') {
                   5011:                 foreach my $role (@{$roles}) {
                   5012:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5013:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5014:                     } else {
                   5015:                         my %hash = ();
                   5016:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5017:                     }
                   5018:                 }
                   5019:             }
                   5020:         }
                   5021:     }
                   5022:     return %privileged;
1.9       www      5023: }
1.1       albertel 5024: 
1.103     harris41 5025: # -------------------------------------------------------- Get user privileges
1.11      www      5026: 
                   5027: sub rolesinit {
1.1169    droeschl 5028:     my ($domain, $username) = @_;
                   5029:     my %userroles = ('user.login.time' => time);
                   5030:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5031: 
                   5032:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5033:     # also, blocking can be triggered by an activating timer
                   5034:     # it's saved in the user's %env.
                   5035:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5036:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5037:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5038:         %timerintchk, %timerintenv);
                   5039: 
1.1162    raeburn  5040:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5041:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5042:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5043:     }
1.1169    droeschl 5044: 
1.1162    raeburn  5045:     foreach my $key (keys(%timerinterval)) {
                   5046:         my ($cid,$rest) = split(/\0/,$key);
                   5047:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5048:     }
1.1169    droeschl 5049: 
1.11      www      5050:     my %allroles=();
1.1162    raeburn  5051:     my %allgroups=();
1.11      www      5052: 
1.1169    droeschl 5053:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5054:         my $role = $rolesdump{$area};
                   5055:         $area =~ s/\_\w\w$//;
                   5056: 
                   5057:         my ($trole, $tend, $tstart, $group_privs);
                   5058: 
                   5059:         if ($role =~ /^cr/) {
                   5060:         # Custom role, defined by a user 
                   5061:         # e.g., user.role.cr/msu/smith/mynewrole
                   5062:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5063:                 $trole = $1;
                   5064:                 ($tend, $tstart) = split('_', $2);
                   5065:             } else {
                   5066:                 $trole = $role;
                   5067:             }
                   5068:         } elsif ($role =~ m|^gr/|) {
                   5069:         # Role of member in a group, defined within a course/community
                   5070:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5071:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5072:             next if $tstart eq '-1';
                   5073:             ($trole, $group_privs) = split(/\//, $trole);
                   5074:             $group_privs = &unescape($group_privs);
                   5075:         } else {
                   5076:         # Just a normal role, defined in roles.tab
                   5077:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5078:         }
                   5079: 
                   5080:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5081:                  $username);
                   5082:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5083: 
                   5084:         # role expired or not available yet?
                   5085:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5086:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5087: 
                   5088:         next if $area eq '' or $trole eq '';
                   5089: 
                   5090:         my $spec = "$trole.$area";
                   5091:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5092: 
                   5093:         if ($trole =~ /^cr\//) {
                   5094:         # Custom role, defined by a user
                   5095:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5096:         } elsif ($trole eq 'gr') {
                   5097:         # Role of a member in a group, defined within a course/community
                   5098:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5099:             next;
                   5100:         } else {
                   5101:         # Normal role, defined in roles.tab
                   5102:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5103:         }
                   5104: 
                   5105:         my $cid = $tdomain.'_'.$trest;
                   5106:         unless ($firstaccchk{$cid}) {
                   5107:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5108:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5109:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5110:                         $coursetimerstarts{$cid}{$item}; 
                   5111:                 }
                   5112:             }
                   5113:             $firstaccchk{$cid} = 1;
                   5114:         }
                   5115:         unless ($timerintchk{$cid}) {
                   5116:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5117:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5118:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5119:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5120:                 }
1.12      www      5121:             }
1.1169    droeschl 5122:             $timerintchk{$cid} = 1;
1.191     harris41 5123:         }
1.11      www      5124:     }
1.1169    droeschl 5125: 
                   5126:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5127:         \%allroles, \%allgroups);
                   5128:     $env{'user.adv'} = $userroles{'user.adv'};
                   5129: 
1.1162    raeburn  5130:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5131: }
                   5132: 
1.567     raeburn  5133: sub set_arearole {
1.1215    raeburn  5134:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5135:     unless ($nolog) {
1.567     raeburn  5136: # log the associated role with the area
1.1215    raeburn  5137:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5138:     }
1.743     albertel 5139:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5140: }
                   5141: 
                   5142: sub custom_roleprivs {
                   5143:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5144:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5145:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5146:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5147:         my ($rdummy,$roledef)=
                   5148:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5149:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5150:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5151:             if (defined($syspriv)) {
1.1043    raeburn  5152:                 if ($trest =~ /^$match_community$/) {
                   5153:                     $syspriv =~ s/bre\&S//; 
                   5154:                 }
1.567     raeburn  5155:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5156:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5157:             }
                   5158:             if ($tdomain ne '') {
                   5159:                 if (defined($dompriv)) {
                   5160:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5161:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5162:                 }
                   5163:                 if (($trest ne '') && (defined($coursepriv))) {
                   5164:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5165:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5166:                 }
                   5167:             }
                   5168:         }
                   5169:     }
                   5170: }
                   5171: 
1.678     raeburn  5172: sub group_roleprivs {
                   5173:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5174:     my $access = 1;
                   5175:     my $now = time;
                   5176:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5177:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5178:     if ($access) {
1.811     albertel 5179:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5180:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5181:     }
                   5182: }
1.567     raeburn  5183: 
                   5184: sub standard_roleprivs {
                   5185:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5186:     if (defined($pr{$trole.':s'})) {
                   5187:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5188:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5189:     }
                   5190:     if ($tdomain ne '') {
                   5191:         if (defined($pr{$trole.':d'})) {
                   5192:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5193:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5194:         }
                   5195:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5196:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5197:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5198:         }
                   5199:     }
                   5200: }
                   5201: 
                   5202: sub set_userprivs {
1.1064    raeburn  5203:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5204:     my $author=0;
                   5205:     my $adv=0;
1.678     raeburn  5206:     my %grouproles = ();
                   5207:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5208:         my @groupkeys; 
1.1000    raeburn  5209:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5210:             push(@groupkeys,$role);
                   5211:         }
                   5212:         if (ref($groups_roles) eq 'HASH') {
                   5213:             foreach my $key (keys(%{$groups_roles})) {
                   5214:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5215:                     push(@groupkeys,$key);
                   5216:                 }
                   5217:             }
                   5218:         }
                   5219:         if (@groupkeys > 0) {
                   5220:             foreach my $role (@groupkeys) {
                   5221:                 my ($trole,$area,$sec,$extendedarea);
                   5222:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5223:                     $trole = $1;
                   5224:                     $area = $2;
                   5225:                     $sec = $3;
                   5226:                     $extendedarea = $area.$sec;
                   5227:                     if (exists($$allgroups{$area})) {
                   5228:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5229:                             my $spec = $trole.'.'.$extendedarea;
                   5230:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5231:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5232:                         }
1.678     raeburn  5233:                     }
                   5234:                 }
                   5235:             }
                   5236:         }
                   5237:     }
1.800     albertel 5238:     foreach my $group (keys(%grouproles)) {
                   5239:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5240:     }
1.800     albertel 5241:     foreach my $role (keys(%{$allroles})) {
                   5242:         my %thesepriv;
1.941     raeburn  5243:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5244:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5245:             if ($item ne '') {
                   5246:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5247:                 if ($restrictions eq '') {
                   5248:                     $thesepriv{$privilege}='F';
                   5249:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5250:                     $thesepriv{$privilege}.=$restrictions;
                   5251:                 }
                   5252:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5253:             }
                   5254:         }
                   5255:         my $thesestr='';
1.1104    raeburn  5256:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5257: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5258: 	}
                   5259:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5260:     }
                   5261:     return ($author,$adv);
                   5262: }
                   5263: 
1.994     raeburn  5264: sub role_status {
1.1104    raeburn  5265:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5266:     my @pwhere = ();
                   5267:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5268:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5269:         unless (!defined($$role) || $$role eq '') {
                   5270:             $$where=join('.',@pwhere);
                   5271:             $$trolecode=$$role.'.'.$$where;
                   5272:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5273:             $$tstatus='is';
1.1104    raeburn  5274:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5275:                 $$tstatus='future';
1.1034    raeburn  5276:                 if ($$tstart<$now) {
                   5277:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5278:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5279:                             my (%allroles,%allgroups,$group_privs,
                   5280:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5281:                             my %userroles = (
                   5282:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5283:                             );
1.1064    raeburn  5284:                             @rolecodes = ('cm'); 
1.1002    raeburn  5285:                             my $spec=$$role.'.'.$$where;
                   5286:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5287:                             if ($$role =~ /^cr\//) {
                   5288:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5289:                                 push(@rolecodes,'cr');
1.1002    raeburn  5290:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5291:                                 push(@rolecodes,$$role);
1.1002    raeburn  5292:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5293:                                                     $env{'user.name'});
1.1064    raeburn  5294:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5295:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5296:                                 $group_privs = &unescape($group_privs);
                   5297:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5298:                                 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  5299:                                 &get_groups_roles($tdomain,$trest,
                   5300:                                                   \%course_roles,\@rolecodes,
                   5301:                                                   \%groups_roles);
1.1002    raeburn  5302:                             } else {
1.1064    raeburn  5303:                                 push(@rolecodes,$$role);
1.1002    raeburn  5304:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5305:                             }
1.1064    raeburn  5306:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5307:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5308:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5309:                         }
                   5310:                     }
1.1034    raeburn  5311:                     $$tstatus = 'is';
1.1002    raeburn  5312:                 }
1.994     raeburn  5313:             }
                   5314:             if ($$tend) {
1.1104    raeburn  5315:                 if ($$tend<$update) {
1.994     raeburn  5316:                     $$tstatus='expired';
                   5317:                 } elsif ($$tend<$now) {
                   5318:                     $$tstatus='will_not';
                   5319:                 }
                   5320:             }
                   5321:         }
                   5322:     }
                   5323: }
                   5324: 
1.1104    raeburn  5325: sub get_groups_roles {
                   5326:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5327:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5328:                   (ref($rolecodes) eq 'ARRAY') && 
                   5329:                   (ref($groups_roles) eq 'HASH')); 
                   5330:     if (keys(%{$cdom_courseroles}) > 0) {
                   5331:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5332:         if ($cdom ne '' && $cnum ne '') {
                   5333:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5334:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5335:                     my $crsrole = $1;
                   5336:                     my $crssec = $2;
                   5337:                     if ($crsrole =~ /^cr/) {
                   5338:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5339:                             push(@{$rolecodes},'cr');
                   5340:                         }
                   5341:                     } else {
                   5342:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5343:                             push(@{$rolecodes},$crsrole);
                   5344:                         }
                   5345:                     }
                   5346:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5347:                     if ($crssec ne '') {
                   5348:                         $rolekey .= "/$crssec";
                   5349:                     }
                   5350:                     $rolekey .= './';
                   5351:                     $groups_roles->{$rolekey} = $rolecodes;
                   5352:                 }
                   5353:             }
                   5354:         }
                   5355:     }
                   5356:     return;
                   5357: }
                   5358: 
                   5359: sub delete_env_groupprivs {
                   5360:     my ($where,$courseroles,$possroles) = @_;
                   5361:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5362:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5363:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5364:         %{$courseroles->{$udom}} =
                   5365:             &get_my_roles('','','userroles',['active'],
                   5366:                           $possroles,[$udom],1);
                   5367:     }
                   5368:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5369:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5370:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5371:             my $area = '/'.$cdom.'/'.$cnum;
                   5372:             my $privkey = "user.priv.$crsrole.$area";
                   5373:             if ($crssec ne '') {
                   5374:                 $privkey .= '/'.$crssec;
                   5375:             }
                   5376:             $privkey .= ".$area/$group";
                   5377:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5378:         }
                   5379:     }
                   5380:     return;
                   5381: }
                   5382: 
1.994     raeburn  5383: sub check_adhoc_privs {
1.1104    raeburn  5384:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5385:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5386:     my $setprivs;
1.994     raeburn  5387:     if ($env{$cckey}) {
                   5388:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5389:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5390:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5391:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5392:             $setprivs = 1;
1.994     raeburn  5393:         }
                   5394:     } else {
1.1088    raeburn  5395:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5396:         $setprivs = 1;
1.994     raeburn  5397:     }
1.1185    raeburn  5398:     return $setprivs;
1.994     raeburn  5399: }
                   5400: 
                   5401: sub set_adhoc_privileges {
                   5402: # role can be cc or ca
1.1088    raeburn  5403:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5404:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5405:     my $spec = $role.'.'.$area;
                   5406:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5407:                                   $env{'user.name'},1);
1.994     raeburn  5408:     my %ccrole = ();
                   5409:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5410:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5411:     &appenv(\%userroles,[$role,'cm']);
                   5412:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5413:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5414:         &appenv( {'request.role'        => $spec,
                   5415:                   'request.role.domain' => $dcdom,
                   5416:                   'request.course.sec'  => ''
                   5417:                  }
                   5418:                );
                   5419:         my $tadv=0;
                   5420:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5421:         &appenv({'request.role.adv'    => $tadv});
                   5422:     }
1.994     raeburn  5423: }
                   5424: 
1.12      www      5425: # --------------------------------------------------------------- get interface
                   5426: 
                   5427: sub get {
1.131     albertel 5428:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5429:    my $items='';
1.800     albertel 5430:    foreach my $item (@$storearr) {
                   5431:        $items.=&escape($item).'&';
1.191     harris41 5432:    }
1.12      www      5433:    $items=~s/\&$//;
1.620     albertel 5434:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5435:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5436:    my $uhome=&homeserver($uname,$udomain);
                   5437: 
1.133     albertel 5438:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5439:    my @pairs=split(/\&/,$rep);
1.273     albertel 5440:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5441:      return @pairs;
                   5442:    }
1.15      www      5443:    my %returnhash=();
1.42      www      5444:    my $i=0;
1.800     albertel 5445:    foreach my $item (@$storearr) {
                   5446:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5447:       $i++;
1.191     harris41 5448:    }
1.15      www      5449:    return %returnhash;
1.27      www      5450: }
                   5451: 
                   5452: # --------------------------------------------------------------- del interface
                   5453: 
                   5454: sub del {
1.133     albertel 5455:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5456:    my $items='';
1.800     albertel 5457:    foreach my $item (@$storearr) {
                   5458:        $items.=&escape($item).'&';
1.191     harris41 5459:    }
1.984     neumanie 5460: 
1.27      www      5461:    $items=~s/\&$//;
1.620     albertel 5462:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5463:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5464:    my $uhome=&homeserver($uname,$udomain);
                   5465:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5466: }
                   5467: 
                   5468: # -------------------------------------------------------------- dump interface
                   5469: 
1.1180    droeschl 5470: sub unserialize {
                   5471:     my ($rep, $escapedkeys) = @_;
                   5472: 
                   5473:     return {} if $rep =~ /^error/;
                   5474: 
                   5475:     my %returnhash=();
                   5476: 	foreach my $item (split /\&/, $rep) {
                   5477: 	    my ($key, $value) = split(/=/, $item, 2);
                   5478: 	    $key = unescape($key) unless $escapedkeys;
                   5479: 	    next if $key =~ /^error: 2 /;
                   5480: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5481: 	}
                   5482:     #return %returnhash;
                   5483:     return \%returnhash;
                   5484: }        
                   5485: 
                   5486: # see Lond::dump_with_regexp
                   5487: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5488: sub dump {
1.1180    droeschl 5489:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5490:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5491:     if (!$uname) { $uname=$env{'user.name'}; }
                   5492:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5493: 
1.1180    droeschl 5494:     my $reply;
                   5495:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5496:         # user is hosted on this machine
                   5497:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
                   5498:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5499:         return %{unserialize($reply, $escapedkeys)};
                   5500:     }
1.755     albertel 5501:     if ($regexp) {
                   5502: 	$regexp=&escape($regexp);
                   5503:     } else {
                   5504: 	$regexp='.';
                   5505:     }
1.1166    raeburn  5506:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5507:     my @pairs=split(/\&/,$rep);
                   5508:     my %returnhash=();
1.1098    foxr     5509:     if (!($rep =~ /^error/ )) {
                   5510: 	foreach my $item (@pairs) {
                   5511: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5512:         $key = unescape($key) unless $escapedkeys;
                   5513:         #$key = &unescape($key);
1.1098    foxr     5514: 	    next if ($key =~ /^error: 2 /);
                   5515: 	    $returnhash{$key}=&thaw_unescape($value);
                   5516: 	}
1.755     albertel 5517:     }
                   5518:     return %returnhash;
1.407     www      5519: }
                   5520: 
1.1098    foxr     5521: 
1.717     albertel 5522: # --------------------------------------------------------- dumpstore interface
                   5523: 
                   5524: sub dumpstore {
                   5525:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5526:    # same as dump but keys must be escaped. They may contain colon separated
                   5527:    # lists of values that may themself contain colons (e.g. symbs).
                   5528:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5529: }
                   5530: 
1.407     www      5531: # -------------------------------------------------------------- keys interface
                   5532: 
                   5533: sub getkeys {
                   5534:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5535:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5536:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5537:    my $uhome=&homeserver($uname,$udomain);
                   5538:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5539:    my @keyarray=();
1.800     albertel 5540:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5541:       next if ($key =~ /^error: 2 /);
1.800     albertel 5542:       push(@keyarray,&unescape($key));
1.407     www      5543:    }
                   5544:    return @keyarray;
1.318     matthew  5545: }
                   5546: 
1.319     matthew  5547: # --------------------------------------------------------------- currentdump
                   5548: sub currentdump {
1.328     matthew  5549:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5550:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5551:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5552:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5553:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5554:    my $rep;
                   5555: 
                   5556:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5557:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5558:                    $courseid)));
                   5559:    } else {
                   5560:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5561:    }
                   5562: 
1.318     matthew  5563:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5564:    #
1.318     matthew  5565:    my %returnhash=();
1.319     matthew  5566:    #
                   5567:    if ($rep eq "unknown_cmd") { 
                   5568:        # an old lond will not know currentdump
                   5569:        # Do a dump and make it look like a currentdump
1.822     albertel 5570:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5571:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5572:        my %hash = @tmp;
                   5573:        @tmp=();
1.424     matthew  5574:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5575:    } else {
                   5576:        my @pairs=split(/\&/,$rep);
1.800     albertel 5577:        foreach my $pair (@pairs) {
                   5578:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5579:            my ($symb,$param) = split(/:/,$key);
                   5580:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5581:                                                         &thaw_unescape($value);
1.319     matthew  5582:        }
1.191     harris41 5583:    }
1.12      www      5584:    return %returnhash;
1.424     matthew  5585: }
                   5586: 
                   5587: sub convert_dump_to_currentdump{
                   5588:     my %hash = %{shift()};
                   5589:     my %returnhash;
                   5590:     # Code ripped from lond, essentially.  The only difference
                   5591:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5592:     # we might run in to problems with parameter names =~ /^v\./
                   5593:     while (my ($key,$value) = each(%hash)) {
                   5594:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5595: 	$symb  = &unescape($symb);
                   5596: 	$param = &unescape($param);
1.424     matthew  5597:         next if ($v eq 'version' || $symb eq 'keys');
                   5598:         next if (exists($returnhash{$symb}) &&
                   5599:                  exists($returnhash{$symb}->{$param}) &&
                   5600:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5601:         $returnhash{$symb}->{$param}=$value;
                   5602:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5603:     }
                   5604:     #
                   5605:     # Remove all of the keys in the hashes which keep track of
                   5606:     # the version of the parameter.
                   5607:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5608:         # use a foreach because we are going to delete from the hash.
                   5609:         foreach my $key (keys(%$param_hash)) {
                   5610:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5611:         }
                   5612:     }
                   5613:     return \%returnhash;
1.12      www      5614: }
                   5615: 
1.627     albertel 5616: # ------------------------------------------------------ critical inc interface
                   5617: 
                   5618: sub cinc {
                   5619:     return &inc(@_,'critical');
                   5620: }
                   5621: 
1.449     matthew  5622: # --------------------------------------------------------------- inc interface
                   5623: 
                   5624: sub inc {
1.627     albertel 5625:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5626:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5627:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5628:     my $uhome=&homeserver($uname,$udomain);
                   5629:     my $items='';
                   5630:     if (! ref($store)) {
                   5631:         # got a single value, so use that instead
                   5632:         $items = &escape($store).'=&';
                   5633:     } elsif (ref($store) eq 'SCALAR') {
                   5634:         $items = &escape($$store).'=&';        
                   5635:     } elsif (ref($store) eq 'ARRAY') {
                   5636:         $items = join('=&',map {&escape($_);} @{$store});
                   5637:     } elsif (ref($store) eq 'HASH') {
                   5638:         while (my($key,$value) = each(%{$store})) {
                   5639:             $items.= &escape($key).'='.&escape($value).'&';
                   5640:         }
                   5641:     }
                   5642:     $items=~s/\&$//;
1.627     albertel 5643:     if ($critical) {
                   5644: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5645:     } else {
                   5646: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5647:     }
1.449     matthew  5648: }
                   5649: 
1.12      www      5650: # --------------------------------------------------------------- put interface
                   5651: 
                   5652: sub put {
1.134     albertel 5653:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5654:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5655:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5656:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5657:    my $items='';
1.800     albertel 5658:    foreach my $item (keys(%$storehash)) {
                   5659:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5660:    }
1.12      www      5661:    $items=~s/\&$//;
1.134     albertel 5662:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5663: }
                   5664: 
1.631     albertel 5665: # ------------------------------------------------------------ newput interface
                   5666: 
                   5667: sub newput {
                   5668:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5669:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5670:    if (!$uname) { $uname=$env{'user.name'}; }
                   5671:    my $uhome=&homeserver($uname,$udomain);
                   5672:    my $items='';
                   5673:    foreach my $key (keys(%$storehash)) {
                   5674:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5675:    }
                   5676:    $items=~s/\&$//;
                   5677:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5678: }
                   5679: 
                   5680: # ---------------------------------------------------------  putstore interface
                   5681: 
1.524     raeburn  5682: sub putstore {
1.715     albertel 5683:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5684:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5685:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5686:    my $uhome=&homeserver($uname,$udomain);
                   5687:    my $items='';
1.715     albertel 5688:    foreach my $key (keys(%$storehash)) {
                   5689:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5690:    }
1.715     albertel 5691:    $items=~s/\&$//;
1.716     albertel 5692:    my $esc_symb=&escape($symb);
                   5693:    my $esc_v=&escape($version);
1.715     albertel 5694:    my $reply =
1.716     albertel 5695:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5696: 	      $uhome);
                   5697:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5698:        # gfall back to way things use to be done
1.715     albertel 5699:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5700: 			    $uname);
1.524     raeburn  5701:    }
1.715     albertel 5702:    return $reply;
                   5703: }
                   5704: 
                   5705: sub old_putstore {
1.716     albertel 5706:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5707:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5708:     if (!$uname) { $uname=$env{'user.name'}; }
                   5709:     my $uhome=&homeserver($uname,$udomain);
                   5710:     my %newstorehash;
1.800     albertel 5711:     foreach my $item (keys(%$storehash)) {
                   5712: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5713: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5714:     }
                   5715:     my $items='';
                   5716:     my %allitems = ();
1.800     albertel 5717:     foreach my $item (keys(%newstorehash)) {
                   5718: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5719: 	    my $key = $1.':keys:'.$2;
                   5720: 	    $allitems{$key} .= $3.':';
                   5721: 	}
1.800     albertel 5722: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5723:     }
1.800     albertel 5724:     foreach my $item (keys(%allitems)) {
                   5725: 	$allitems{$item} =~ s/\:$//;
                   5726: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5727:     }
                   5728:     $items=~s/\&$//;
                   5729:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5730: }
                   5731: 
1.47      www      5732: # ------------------------------------------------------ critical put interface
                   5733: 
                   5734: sub cput {
1.134     albertel 5735:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5736:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5737:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5738:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5739:    my $items='';
1.800     albertel 5740:    foreach my $item (keys(%$storehash)) {
                   5741:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5742:    }
1.47      www      5743:    $items=~s/\&$//;
1.134     albertel 5744:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5745: }
                   5746: 
                   5747: # -------------------------------------------------------------- eget interface
                   5748: 
                   5749: sub eget {
1.133     albertel 5750:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5751:    my $items='';
1.800     albertel 5752:    foreach my $item (@$storearr) {
                   5753:        $items.=&escape($item).'&';
1.191     harris41 5754:    }
1.12      www      5755:    $items=~s/\&$//;
1.620     albertel 5756:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5757:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5758:    my $uhome=&homeserver($uname,$udomain);
                   5759:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5760:    my @pairs=split(/\&/,$rep);
                   5761:    my %returnhash=();
1.42      www      5762:    my $i=0;
1.800     albertel 5763:    foreach my $item (@$storearr) {
                   5764:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5765:       $i++;
1.191     harris41 5766:    }
1.12      www      5767:    return %returnhash;
                   5768: }
                   5769: 
1.667     albertel 5770: # ------------------------------------------------------------ tmpput interface
                   5771: sub tmpput {
1.802     raeburn  5772:     my ($storehash,$server,$context)=@_;
1.667     albertel 5773:     my $items='';
1.800     albertel 5774:     foreach my $item (keys(%$storehash)) {
                   5775: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5776:     }
                   5777:     $items=~s/\&$//;
1.802     raeburn  5778:     if (defined($context)) {
                   5779:         $items .= ':'.&escape($context);
                   5780:     }
1.667     albertel 5781:     return &reply("tmpput:$items",$server);
                   5782: }
                   5783: 
                   5784: # ------------------------------------------------------------ tmpget interface
                   5785: sub tmpget {
1.688     albertel 5786:     my ($token,$server)=@_;
                   5787:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5788:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5789:     my %returnhash;
                   5790:     foreach my $item (split(/\&/,$rep)) {
                   5791: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5792:         next if ($key =~ /^error: 2 /);
1.667     albertel 5793: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5794:     }
                   5795:     return %returnhash;
                   5796: }
                   5797: 
1.1113    raeburn  5798: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5799: sub tmpdel {
                   5800:     my ($token,$server)=@_;
                   5801:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5802:     return &reply("tmpdel:$token",$server);
                   5803: }
                   5804: 
1.1198    raeburn  5805: # ------------------------------------------------------------ get_timebased_id 
                   5806: 
                   5807: sub get_timebased_id {
                   5808:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5809:         $maxtries) = @_;
                   5810:     my ($newid,$error,$dellock);
                   5811:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5812:         return ('','ok','invalid call to get suffix');
                   5813:     }
                   5814: 
                   5815: # set defaults for any optional args for which values were not supplied
                   5816:     if ($who eq '') {
                   5817:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5818:     }
                   5819:     if (!$locktries) {
                   5820:         $locktries = 3;
                   5821:     }
                   5822:     if (!$maxtries) {
                   5823:         $maxtries = 10;
                   5824:     }
                   5825:     
                   5826:     if (($cdom eq '') || ($cnum eq '')) {
                   5827:         if ($env{'request.course.id'}) {
                   5828:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5829:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5830:         }
                   5831:         if (($cdom eq '') || ($cnum eq '')) {
                   5832:             return ('','ok','call to get suffix not in course context');
                   5833:         }
                   5834:     }
                   5835: 
                   5836: # construct locking item
                   5837:     my $lockhash = {
                   5838:                       $prefix."\0".'locked_'.$keyid => $who,
                   5839:                    };
                   5840:     my $tries = 0;
                   5841: 
                   5842: # attempt to get lock on nohist_$namespace file
                   5843:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5844:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5845:         $tries ++;
                   5846:         sleep 1;
                   5847:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5848:     }
                   5849: 
                   5850: # attempt to get unique identifier, based on current timestamp
                   5851:     if ($gotlock eq 'ok') {
                   5852:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5853:         my $id = time;
                   5854:         $newid = $id;
                   5855:         my $idtries = 0;
                   5856:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5857:             if ($idtype eq 'concat') {
                   5858:                 $newid = $id.$idtries;
                   5859:             } else {
                   5860:                 $newid ++;
                   5861:             }
                   5862:             $idtries ++;
                   5863:         }
                   5864:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5865:             my %new_item =  (
                   5866:                               $prefix."\0".$newid => $who,
                   5867:                             );
                   5868:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5869:                                                  $cdom,$cnum);
                   5870:             if ($putresult ne 'ok') {
                   5871:                 undef($newid);
                   5872:                 $error = 'error saving new item: '.$putresult;
                   5873:             }
                   5874:         } else {
                   5875:              $error = ('error: no unique suffix available for the new item ');
                   5876:         }
                   5877: #  remove lock
                   5878:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5879:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5880:     } else {
                   5881:         $error = "error: could not obtain lockfile\n";
                   5882:         $dellock = 'ok';
                   5883:     }
                   5884:     return ($newid,$dellock,$error);
                   5885: }
                   5886: 
1.765     albertel 5887: # -------------------------------------------------- portfolio access checking
                   5888: 
                   5889: sub portfolio_access {
1.766     albertel 5890:     my ($requrl) = @_;
1.765     albertel 5891:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5892:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5893:     if ($result) {
                   5894:         my %setters;
                   5895:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5896:             my ($startblock,$endblock) =
                   5897:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5898:             if ($startblock && $endblock) {
                   5899:                 return 'B';
                   5900:             }
                   5901:         } else {
                   5902:             my ($startblock,$endblock) =
                   5903:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5904:             if ($startblock && $endblock) {
                   5905:                 return 'B';
                   5906:             }
                   5907:         }
                   5908:     }
1.765     albertel 5909:     if ($result eq 'ok') {
1.766     albertel 5910:        return 'F';
1.765     albertel 5911:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5912:        return 'A';
1.765     albertel 5913:     }
1.766     albertel 5914:     return '';
1.765     albertel 5915: }
                   5916: 
                   5917: sub get_portfolio_access {
1.767     albertel 5918:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5919: 
                   5920:     if (!ref($access_hash)) {
                   5921: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5922: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5923: 						   $file_name);
                   5924: 	$access_hash = $access_controls{$file_name};
                   5925:     }
                   5926: 
1.765     albertel 5927:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5928:     my $now = time;
                   5929:     if (ref($access_hash) eq 'HASH') {
                   5930:         foreach my $key (keys(%{$access_hash})) {
                   5931:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5932:             if ($start > $now) {
                   5933:                 next;
                   5934:             }
                   5935:             if ($end && $end<$now) {
                   5936:                 next;
                   5937:             }
                   5938:             if ($scope eq 'public') {
                   5939:                 $public = $key;
                   5940:                 last;
                   5941:             } elsif ($scope eq 'guest') {
                   5942:                 $guest = $key;
                   5943:             } elsif ($scope eq 'domains') {
                   5944:                 push(@domains,$key);
                   5945:             } elsif ($scope eq 'users') {
                   5946:                 push(@users,$key);
                   5947:             } elsif ($scope eq 'course') {
                   5948:                 push(@courses,$key);
                   5949:             } elsif ($scope eq 'group') {
                   5950:                 push(@groups,$key);
                   5951:             }
                   5952:         }
                   5953:         if ($public) {
                   5954:             return 'ok';
                   5955:         }
                   5956:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5957:             if ($guest) {
                   5958:                 return $guest;
                   5959:             }
                   5960:         } else {
                   5961:             if (@domains > 0) {
                   5962:                 foreach my $domkey (@domains) {
                   5963:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5964:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5965:                             return 'ok';
                   5966:                         }
                   5967:                     }
                   5968:                 }
                   5969:             }
                   5970:             if (@users > 0) {
                   5971:                 foreach my $userkey (@users) {
1.865     raeburn  5972:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5973:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5974:                             if (ref($item) eq 'HASH') {
                   5975:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5976:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5977:                                     return 'ok';
                   5978:                                 }
                   5979:                             }
                   5980:                         }
                   5981:                     } 
1.765     albertel 5982:                 }
                   5983:             }
                   5984:             my %roleshash;
                   5985:             my @courses_and_groups = @courses;
                   5986:             push(@courses_and_groups,@groups); 
                   5987:             if (@courses_and_groups > 0) {
                   5988:                 my (%allgroups,%allroles); 
                   5989:                 my ($start,$end,$role,$sec,$group);
                   5990:                 foreach my $envkey (%env) {
1.1060    raeburn  5991:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5992:                         my $cid = $2.'_'.$3; 
                   5993:                         if ($1 eq 'gr') {
                   5994:                             $group = $4;
                   5995:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5996:                         } else {
                   5997:                             if ($4 eq '') {
                   5998:                                 $sec = 'none';
                   5999:                             } else {
                   6000:                                 $sec = $4;
                   6001:                             }
                   6002:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6003:                         }
1.811     albertel 6004:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6005:                         my $cid = $2.'_'.$3;
                   6006:                         if ($4 eq '') {
                   6007:                             $sec = 'none';
                   6008:                         } else {
                   6009:                             $sec = $4;
                   6010:                         }
                   6011:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6012:                     }
                   6013:                 }
                   6014:                 if (keys(%allroles) == 0) {
                   6015:                     return;
                   6016:                 }
                   6017:                 foreach my $key (@courses_and_groups) {
                   6018:                     my %content = %{$$access_hash{$key}};
                   6019:                     my $cnum = $content{'number'};
                   6020:                     my $cdom = $content{'domain'};
                   6021:                     my $cid = $cdom.'_'.$cnum;
                   6022:                     if (!exists($allroles{$cid})) {
                   6023:                         next;
                   6024:                     }    
                   6025:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6026:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6027:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6028:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6029:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6030:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6031:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6032:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6033:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6034:                                         if (grep/^all$/,@sections) {
                   6035:                                             return 'ok';
                   6036:                                         } else {
                   6037:                                             if (grep/^$sec$/,@sections) {
                   6038:                                                 return 'ok';
                   6039:                                             }
                   6040:                                         }
                   6041:                                     }
                   6042:                                 }
                   6043:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6044:                                     if (grep/^none$/,@groups) {
                   6045:                                         return 'ok';
                   6046:                                     }
                   6047:                                 } else {
                   6048:                                     if (grep/^all$/,@groups) {
                   6049:                                         return 'ok';
                   6050:                                     } 
                   6051:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6052:                                         if (grep/^$group$/,@groups) {
                   6053:                                             return 'ok';
                   6054:                                         }
                   6055:                                     }
                   6056:                                 } 
                   6057:                             }
                   6058:                         }
                   6059:                     }
                   6060:                 }
                   6061:             }
                   6062:             if ($guest) {
                   6063:                 return $guest;
                   6064:             }
                   6065:         }
                   6066:     }
                   6067:     return;
                   6068: }
                   6069: 
                   6070: sub course_group_datechecker {
                   6071:     my ($dates,$now,$status) = @_;
                   6072:     my ($start,$end) = split(/\./,$dates);
                   6073:     if (!$start && !$end) {
                   6074:         return 'ok';
                   6075:     }
                   6076:     if (grep/^active$/,@{$status}) {
                   6077:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6078:             return 'ok';
                   6079:         }
                   6080:     }
                   6081:     if (grep/^previous$/,@{$status}) {
                   6082:         if ($end > $now ) {
                   6083:             return 'ok';
                   6084:         }
                   6085:     }
                   6086:     if (grep/^future$/,@{$status}) {
                   6087:         if ($start > $now) {
                   6088:             return 'ok';
                   6089:         }
                   6090:     }
                   6091:     return; 
                   6092: }
                   6093: 
                   6094: sub parse_portfolio_url {
                   6095:     my ($url) = @_;
                   6096: 
                   6097:     my ($type,$udom,$unum,$group,$file_name);
                   6098:     
1.823     albertel 6099:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6100: 	$type = 1;
                   6101:         $udom = $1;
                   6102:         $unum = $2;
                   6103:         $file_name = $3;
1.823     albertel 6104:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6105: 	$type = 2;
                   6106:         $udom = $1;
                   6107:         $unum = $2;
                   6108:         $group = $3;
                   6109:         $file_name = $3.'/'.$4;
                   6110:     }
                   6111:     if (wantarray) {
                   6112: 	return ($type,$udom,$unum,$file_name,$group);
                   6113:     }
                   6114:     return $type;
                   6115: }
                   6116: 
                   6117: sub is_portfolio_url {
                   6118:     my ($url) = @_;
                   6119:     return scalar(&parse_portfolio_url($url));
                   6120: }
                   6121: 
1.798     raeburn  6122: sub is_portfolio_file {
                   6123:     my ($file) = @_;
1.820     raeburn  6124:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6125:         return 1;
                   6126:     }
                   6127:     return;
                   6128: }
                   6129: 
1.976     raeburn  6130: sub usertools_access {
1.1084    raeburn  6131:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6132:     my ($access,%tools);
                   6133:     if ($context eq '') {
                   6134:         $context = 'tools';
                   6135:     }
                   6136:     if ($context eq 'requestcourses') {
                   6137:         %tools = (
                   6138:                       official   => 1,
                   6139:                       unofficial => 1,
1.1006    raeburn  6140:                       community  => 1,
1.985     raeburn  6141:                  );
1.1183    raeburn  6142:     } elsif ($context eq 'requestauthor') {
                   6143:         %tools = (
                   6144:                       requestauthor => 1,
                   6145:                  );
1.985     raeburn  6146:     } else {
                   6147:         %tools = (
                   6148:                       aboutme   => 1,
                   6149:                       blog      => 1,
1.1177    raeburn  6150:                       webdav    => 1,
1.985     raeburn  6151:                       portfolio => 1,
                   6152:                  );
                   6153:     }
1.976     raeburn  6154:     return if (!defined($tools{$tool}));
                   6155: 
                   6156:     if ((!defined($udom)) || (!defined($uname))) {
                   6157:         $udom = $env{'user.domain'};
                   6158:         $uname = $env{'user.name'};
                   6159:     }
                   6160: 
1.978     raeburn  6161:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6162:         if ($action ne 'reload') {
1.985     raeburn  6163:             if ($context eq 'requestcourses') {
                   6164:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6165:             } elsif ($context eq 'requestauthor') {
                   6166:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6167:             } else {
                   6168:                 return $env{'environment.availabletools.'.$tool};
                   6169:             }
                   6170:         }
1.976     raeburn  6171:     }
                   6172: 
1.1183    raeburn  6173:     my ($toolstatus,$inststatus,$envkey);
                   6174:     if ($context eq 'requestauthor') {
                   6175:         $envkey = $context; 
                   6176:     } else {
                   6177:         $envkey = $context.'.'.$tool;
                   6178:     }
1.976     raeburn  6179: 
1.985     raeburn  6180:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6181:          ($action ne 'reload')) {
1.1183    raeburn  6182:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6183:         $inststatus = $env{'environment.inststatus'};
                   6184:     } else {
1.1084    raeburn  6185:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6186:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6187:             $inststatus = $userenvref->{'inststatus'};
                   6188:         } else {
1.1183    raeburn  6189:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6190:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6191:             $inststatus = $userenv{'inststatus'};
                   6192:         }
1.976     raeburn  6193:     }
                   6194: 
                   6195:     if ($toolstatus ne '') {
                   6196:         if ($toolstatus) {
                   6197:             $access = 1;
                   6198:         } else {
                   6199:             $access = 0;
                   6200:         }
                   6201:         return $access;
                   6202:     }
                   6203: 
1.1084    raeburn  6204:     my ($is_adv,%domdef);
                   6205:     if (ref($is_advref) eq 'HASH') {
                   6206:         $is_adv = $is_advref->{'is_adv'};
                   6207:     } else {
                   6208:         $is_adv = &is_advanced_user($udom,$uname);
                   6209:     }
                   6210:     if (ref($domdefref) eq 'HASH') {
                   6211:         %domdef = %{$domdefref};
                   6212:     } else {
                   6213:         %domdef = &get_domain_defaults($udom);
                   6214:     }
1.976     raeburn  6215:     if (ref($domdef{$tool}) eq 'HASH') {
                   6216:         if ($is_adv) {
                   6217:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6218:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6219:                     $access = 1;
                   6220:                 } else {
                   6221:                     $access = 0;
                   6222:                 }
                   6223:                 return $access;
                   6224:             }
                   6225:         }
                   6226:         if ($inststatus ne '') {
                   6227:             my ($hasaccess,$hasnoaccess);
                   6228:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6229:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6230:                     if ($domdef{$tool}{$affiliation}) {
                   6231:                         $hasaccess = 1;
                   6232:                     } else {
                   6233:                         $hasnoaccess = 1;
                   6234:                     }
                   6235:                 }
                   6236:             }
                   6237:             if ($hasaccess || $hasnoaccess) {
                   6238:                 if ($hasaccess) {
                   6239:                     $access = 1;
                   6240:                 } elsif ($hasnoaccess) {
                   6241:                     $access = 0; 
                   6242:                 }
                   6243:                 return $access;
                   6244:             }
                   6245:         } else {
                   6246:             if ($domdef{$tool}{'default'} ne '') {
                   6247:                 if ($domdef{$tool}{'default'}) {
                   6248:                     $access = 1;
                   6249:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6250:                     $access = 0;
                   6251:                 }
                   6252:                 return $access;
                   6253:             }
                   6254:         }
                   6255:     } else {
1.1177    raeburn  6256:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6257:             $access = 1;
                   6258:         } else {
                   6259:             $access = 0;
                   6260:         }
1.976     raeburn  6261:         return $access;
                   6262:     }
                   6263: }
                   6264: 
1.1050    raeburn  6265: sub is_course_owner {
                   6266:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6267:     if (($udom eq '') || ($uname eq '')) {
                   6268:         $udom = $env{'user.domain'};
                   6269:         $uname = $env{'user.name'};
                   6270:     }
                   6271:     unless (($udom eq '') || ($uname eq '')) {
                   6272:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6273:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6274:                 return 1;
                   6275:             } else {
                   6276:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6277:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6278:                     return 1;
                   6279:                 }
                   6280:             }
                   6281:         }
                   6282:     }
                   6283:     return;
                   6284: }
                   6285: 
1.976     raeburn  6286: sub is_advanced_user {
                   6287:     my ($udom,$uname) = @_;
1.1085    raeburn  6288:     if ($udom ne '' && $uname ne '') {
                   6289:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6290:             if (wantarray) {
                   6291:                 return ($env{'user.adv'},$env{'user.author'});
                   6292:             } else {
                   6293:                 return $env{'user.adv'};
                   6294:             }
1.1085    raeburn  6295:         }
                   6296:     }
1.976     raeburn  6297:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6298:     my %allroles;
1.1128    raeburn  6299:     my ($is_adv,$is_author);
1.976     raeburn  6300:     foreach my $role (keys(%roleshash)) {
                   6301:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6302:         my $area = '/'.$tdomain.'/'.$trest;
                   6303:         if ($sec ne '') {
                   6304:             $area .= '/'.$sec;
                   6305:         }
                   6306:         if (($area ne '') && ($trole ne '')) {
                   6307:             my $spec=$trole.'.'.$area;
                   6308:             if ($trole =~ /^cr\//) {
                   6309:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6310:             } elsif ($trole ne 'gr') {
                   6311:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6312:             }
1.1128    raeburn  6313:             if ($trole eq 'au') {
                   6314:                 $is_author = 1;
                   6315:             }
1.976     raeburn  6316:         }
                   6317:     }
                   6318:     foreach my $role (keys(%allroles)) {
                   6319:         last if ($is_adv);
                   6320:         foreach my $item (split(/:/,$allroles{$role})) {
                   6321:             if ($item ne '') {
                   6322:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6323:                 if ($privilege eq 'adv') {
                   6324:                     $is_adv = 1;
                   6325:                     last;
                   6326:                 }
                   6327:             }
                   6328:         }
                   6329:     }
1.1128    raeburn  6330:     if (wantarray) {
                   6331:         return ($is_adv,$is_author);
                   6332:     }
1.976     raeburn  6333:     return $is_adv;
                   6334: }
1.798     raeburn  6335: 
1.1035    raeburn  6336: sub check_can_request {
1.1036    raeburn  6337:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6338:     my $canreq = 0;
                   6339:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6340:     my @options = ('approval','validate','autolimit');
                   6341:     my $optregex = join('|',@options);
                   6342:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6343:         foreach my $type (@{$types}) {
                   6344:             if (&usertools_access($env{'user.name'},
                   6345:                                   $env{'user.domain'},
                   6346:                                   $type,undef,'requestcourses')) {
                   6347:                 $canreq ++;
1.1036    raeburn  6348:                 if (ref($request_domains) eq 'HASH') {
                   6349:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6350:                 }
1.1035    raeburn  6351:                 if ($dom eq $env{'user.domain'}) {
                   6352:                     $can_request->{$type} = 1;
                   6353:                 }
                   6354:             }
                   6355:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6356:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6357:                 if (@curr > 0) {
1.1036    raeburn  6358:                     foreach my $item (@curr) {
                   6359:                         if (ref($request_domains) eq 'HASH') {
                   6360:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6361:                             if ($otherdom ne '') {
                   6362:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6363:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6364:                                         push(@{$request_domains->{$type}},$otherdom);
                   6365:                                     }
                   6366:                                 } else {
                   6367:                                     push(@{$request_domains->{$type}},$otherdom);
                   6368:                                 }
                   6369:                             }
                   6370:                         }
                   6371:                     }
                   6372:                     unless($dom eq $env{'user.domain'}) {
                   6373:                         $canreq ++;
1.1035    raeburn  6374:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6375:                             $can_request->{$type} = 1;
                   6376:                         }
                   6377:                     }
                   6378:                 }
                   6379:             }
                   6380:         }
                   6381:     }
                   6382:     return $canreq;
                   6383: }
                   6384: 
1.341     www      6385: # ---------------------------------------------- Custom access rule evaluation
                   6386: 
                   6387: sub customaccess {
                   6388:     my ($priv,$uri)=@_;
1.807     albertel 6389:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6390:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6391:     $udom = &LONCAPA::clean_domain($udom);
                   6392:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6393:     my $access=0;
1.800     albertel 6394:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6395: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6396: 	if ($type eq 'user') {
                   6397: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6398: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6399: 		if ($tdom) {
                   6400: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6401: 		}
1.896     albertel 6402: 		if ($tuname) {
                   6403: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6404: 		}
                   6405: 		$access=($effect eq 'allow');
                   6406: 		last;
                   6407: 	    }
                   6408: 	} else {
                   6409: 	    if ($role) {
                   6410: 		if ($role ne $urole) { next; }
                   6411: 	    }
                   6412: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6413: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6414: 		if ($tdom) {
                   6415: 		    if ($tdom ne $udom) { next; }
                   6416: 		}
                   6417: 		if ($tcrs) {
                   6418: 		    if ($tcrs ne $ucrs) { next; }
                   6419: 		}
                   6420: 		if ($tsec) {
                   6421: 		    if ($tsec ne $usec) { next; }
                   6422: 		}
                   6423: 		$access=($effect eq 'allow');
                   6424: 		last;
                   6425: 	    }
                   6426: 	    if ($realm eq '' && $role eq '') {
                   6427: 		$access=($effect eq 'allow');
                   6428: 	    }
1.402     bowersj2 6429: 	}
1.341     www      6430:     }
                   6431:     return $access;
                   6432: }
                   6433: 
1.103     harris41 6434: # ------------------------------------------------- Check for a user privilege
1.12      www      6435: 
                   6436: sub allowed {
1.810     raeburn  6437:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6438:     my $ver_orguri=$uri;
1.439     www      6439:     $uri=&deversion($uri);
1.152     www      6440:     my $orguri=$uri;
1.52      www      6441:     $uri=&declutter($uri);
1.809     raeburn  6442: 
1.810     raeburn  6443:     if ($priv eq 'evb') {
                   6444: # Evade communication block restrictions for specified role in a course
                   6445:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6446:             return $1;
                   6447:         } else {
                   6448:             return;
                   6449:         }
                   6450:     }
                   6451: 
1.620     albertel 6452:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6453: # Free bre access to adm and meta resources
1.775     albertel 6454:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6455: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6456: 	&& ($priv eq 'bre')) {
1.14      www      6457: 	return 'F';
1.159     www      6458:     }
                   6459: 
1.545     banghart 6460: # Free bre access to user's own portfolio contents
1.714     raeburn  6461:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6462:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6463: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6464:         my %setters;
                   6465:         my ($startblock,$endblock) = 
                   6466:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6467:         if ($startblock && $endblock) {
                   6468:             return 'B';
                   6469:         } else {
                   6470:             return 'F';
                   6471:         }
1.545     banghart 6472:     }
                   6473: 
1.762     raeburn  6474: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6475:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6476:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6477:         if (exists($env{'request.course.id'})) {
                   6478:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6479:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6480:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6481:                 my $courseprivid=$env{'request.course.id'};
                   6482:                 $courseprivid=~s/\_/\//;
                   6483:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6484:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6485:                     return $1; 
1.762     raeburn  6486:                 } else {
                   6487:                     if ($env{'request.course.sec'}) {
                   6488:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6489:                     }
                   6490:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6491:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6492:                         return $2;
                   6493:                     }
1.714     raeburn  6494:                 }
                   6495:             }
                   6496:         }
                   6497:     }
                   6498: 
1.159     www      6499: # Free bre to public access
                   6500: 
                   6501:     if ($priv eq 'bre') {
1.238     www      6502:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6503: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6504:            return 'F'; 
                   6505:         }
1.238     www      6506:         if ($copyright eq 'priv') {
                   6507:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6508: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6509: 		return '';
                   6510:             }
                   6511:         }
                   6512:         if ($copyright eq 'domain') {
                   6513:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6514: 	    unless (($env{'user.domain'} eq $1) ||
                   6515:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6516: 		return '';
                   6517:             }
1.262     matthew  6518:         }
1.620     albertel 6519:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6520:             # Library role, so allow browsing of resources in this domain.
                   6521:             return 'F';
1.238     www      6522:         }
1.341     www      6523:         if ($copyright eq 'custom') {
                   6524: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6525:         }
1.14      www      6526:     }
1.264     matthew  6527:     # Domain coordinator is trying to create a course
1.620     albertel 6528:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6529:         # uri is the requested domain in this case.
                   6530:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6531:         # a role of dc for the domain in question.
1.620     albertel 6532:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6533:     }
1.29      www      6534: 
1.52      www      6535:     my $thisallowed='';
                   6536:     my $statecond=0;
                   6537:     my $courseprivid='';
                   6538: 
1.1039    raeburn  6539:     my $ownaccess;
1.1043    raeburn  6540:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6541:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6542:         if ($uri eq '') {
                   6543:             $ownaccess = 1;
                   6544:         } else {
                   6545:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6546:                 my $udom = $env{'user.domain'};
                   6547:                 my $uname = $env{'user.name'};
                   6548:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6549:                     $ownaccess = 1;
1.1040    raeburn  6550:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6551:                     unless ($uri =~ m{\.\./}) {
                   6552:                         $ownaccess = 1;
                   6553:                     }
                   6554:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6555:                     my $now = time;
                   6556:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6557:                         my $adom = $1;
                   6558:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6559:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6560:                                 my ($start,$end) = split('.',$env{$key});
                   6561:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6562:                                     $ownaccess = 1;
                   6563:                                     last;
                   6564:                                 }
                   6565:                             }
                   6566:                         }
                   6567:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6568:                         my $adom = $1;
                   6569:                         my $aname = $2;
1.1042    raeburn  6570:                         foreach my $role ('ca','aa') { 
                   6571:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6572:                                 my ($start,$end) =
                   6573:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6574:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6575:                                     $ownaccess = 1;
                   6576:                                     last;
                   6577:                                 }
1.1039    raeburn  6578:                             }
                   6579:                         }
                   6580:                     }
                   6581:                 }
                   6582:             }
                   6583:         }
                   6584:     }
                   6585: 
1.52      www      6586: # Course
                   6587: 
1.620     albertel 6588:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6589:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6590:             $thisallowed.=$1;
                   6591:         }
1.52      www      6592:     }
1.29      www      6593: 
1.52      www      6594: # Domain
                   6595: 
1.620     albertel 6596:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6597:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6598:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6599:             $thisallowed.=$1;
                   6600:         }
1.12      www      6601:     }
1.52      www      6602: 
1.1141    raeburn  6603: # User who is not author or co-author might still be able to edit
                   6604: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6605:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6606:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6607:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6608:             $thisallowed.=$1;
                   6609:         }
                   6610:     }
                   6611: 
1.52      www      6612: # Course: uri itself is a course
1.66      www      6613:     my $courseuri=$uri;
                   6614:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6615:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6616: 
1.620     albertel 6617:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6618:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6619:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6620:             $thisallowed.=$1;
                   6621:         }
1.12      www      6622:     }
1.29      www      6623: 
1.665     albertel 6624: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6625: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6626:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6627: 	$thisallowed='';
1.671     raeburn  6628:         my ($match)=&is_on_map($uri);
                   6629:         if ($match) {
                   6630:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6631:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6632:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6633:                 if (@blockers > 0) {
                   6634:                     $thisallowed = 'B';
                   6635:                 } else {
                   6636:                     $thisallowed.=$1;
                   6637:                 }
1.671     raeburn  6638:             }
                   6639:         } else {
1.705     albertel 6640:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6641:             if ($refuri) {
                   6642:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6643:                     $thisallowed='F';
1.671     raeburn  6644:                 } else {
                   6645:                     $refuri=&declutter($refuri);
                   6646:                     my ($match) = &is_on_map($refuri);
                   6647:                     if ($match) {
1.1162    raeburn  6648:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6649:                         if (@blockers > 0) {
                   6650:                             $thisallowed = 'B';
                   6651:                         } else {
                   6652:                             $thisallowed='F';
                   6653:                         }
1.671     raeburn  6654:                     }
1.669     raeburn  6655:                 }
1.671     raeburn  6656:             }
                   6657:         }
1.314     www      6658:     }
1.492     albertel 6659: 
1.766     albertel 6660:     if ($priv eq 'bre'
                   6661: 	&& $thisallowed ne 'F' 
                   6662: 	&& $thisallowed ne '2'
                   6663: 	&& &is_portfolio_url($uri)) {
                   6664: 	$thisallowed = &portfolio_access($uri);
                   6665:     }
                   6666:     
1.52      www      6667: # Full access at system, domain or course-wide level? Exit.
1.29      www      6668:     if ($thisallowed=~/F/) {
                   6669: 	return 'F';
                   6670:     }
                   6671: 
1.52      www      6672: # If this is generating or modifying users, exit with special codes
1.29      www      6673: 
1.643     www      6674:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6675: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6676: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6677: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6678: 	    unless ($auname) { return $thisallowed; }
                   6679: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6680: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6681: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6682: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6683: 	}
1.52      www      6684: 	return $thisallowed;
                   6685:     }
                   6686: #
1.103     harris41 6687: # Gathered so far: system, domain and course wide privileges
1.52      www      6688: #
                   6689: # Course: See if uri or referer is an individual resource that is part of 
                   6690: # the course
                   6691: 
1.620     albertel 6692:     if ($env{'request.course.id'}) {
1.232     www      6693: 
1.620     albertel 6694:        $courseprivid=$env{'request.course.id'};
                   6695:        if ($env{'request.course.sec'}) {
                   6696:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6697:        }
                   6698:        $courseprivid=~s/\_/\//;
                   6699:        my $checkreferer=1;
1.232     www      6700:        my ($match,$cond)=&is_on_map($uri);
                   6701:        if ($match) {
                   6702:            $statecond=$cond;
1.620     albertel 6703:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6704:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6705:                my $value = $1;
                   6706:                if ($priv eq 'bre') {
                   6707:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6708:                    if (@blockers > 0) {
                   6709:                        $thisallowed = 'B';
                   6710:                    } else {
                   6711:                        $thisallowed.=$value;
                   6712:                    }
                   6713:                } else {
                   6714:                    $thisallowed.=$value;
                   6715:                }
1.52      www      6716:                $checkreferer=0;
                   6717:            }
1.29      www      6718:        }
1.83      www      6719:        
1.148     www      6720:        if ($checkreferer) {
1.620     albertel 6721: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6722:             unless ($refuri) {
1.800     albertel 6723:                 foreach my $key (keys(%env)) {
                   6724: 		    if ($key=~/^httpref\..*\*/) {
                   6725: 			my $pattern=$key;
1.156     www      6726:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6727:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6728:                         $pattern=~s/\//\\\//g;
1.152     www      6729:                         if ($orguri=~/$pattern/) {
1.800     albertel 6730: 			    $refuri=$env{$key};
1.148     www      6731:                         }
                   6732:                     }
1.191     harris41 6733:                 }
1.148     www      6734:             }
1.232     www      6735: 
1.148     www      6736:          if ($refuri) { 
1.152     www      6737: 	  $refuri=&declutter($refuri);
1.232     www      6738:           my ($match,$cond)=&is_on_map($refuri);
                   6739:             if ($match) {
                   6740:               my $refstatecond=$cond;
1.620     albertel 6741:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6742:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6743:                   my $value = $1;
                   6744:                   if ($priv eq 'bre') {
                   6745:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6746:                       if (@blockers > 0) {
                   6747:                           $thisallowed = 'B';
                   6748:                       } else {
                   6749:                           $thisallowed.=$value;
                   6750:                       }
                   6751:                   } else {
                   6752:                       $thisallowed.=$value;
                   6753:                   }
1.53      www      6754:                   $uri=$refuri;
                   6755:                   $statecond=$refstatecond;
1.52      www      6756:               }
                   6757:           }
1.148     www      6758:         }
1.29      www      6759:        }
1.52      www      6760:    }
1.29      www      6761: 
1.52      www      6762: #
1.103     harris41 6763: # Gathered now: all privileges that could apply, and condition number
1.52      www      6764: # 
                   6765: #
                   6766: # Full or no access?
                   6767: #
1.29      www      6768: 
1.52      www      6769:     if ($thisallowed=~/F/) {
                   6770: 	return 'F';
                   6771:     }
1.29      www      6772: 
1.52      www      6773:     unless ($thisallowed) {
                   6774:         return '';
                   6775:     }
1.29      www      6776: 
1.52      www      6777: # Restrictions exist, deal with them
                   6778: #
                   6779: #   C:according to course preferences
                   6780: #   R:according to resource settings
                   6781: #   L:unless locked
                   6782: #   X:according to user session state
                   6783: #
                   6784: 
                   6785: # Possibly locked functionality, check all courses
1.54      www      6786: # Locks might take effect only after 10 minutes cache expiration for other
                   6787: # courses, and 2 minutes for current course
1.52      www      6788: 
                   6789:     my $envkey;
                   6790:     if ($thisallowed=~/L/) {
1.1000    raeburn  6791:         foreach $envkey (keys(%env)) {
1.54      www      6792:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6793:                my $courseid=$2;
                   6794:                my $roleid=$1.'.'.$2;
1.92      www      6795:                $courseid=~s/^\///;
1.54      www      6796:                my $expiretime=600;
1.620     albertel 6797:                if ($env{'request.role'} eq $roleid) {
1.54      www      6798: 		  $expiretime=120;
                   6799:                }
                   6800: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6801:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6802:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6803: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6804:                }
1.620     albertel 6805:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6806:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6807: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6808:                        &log($env{'user.domain'},$env{'user.name'},
                   6809:                             $env{'user.home'},
1.57      www      6810:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6811:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6812:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6813: 		       return '';
                   6814:                    }
                   6815:                }
1.620     albertel 6816:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6817:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6818: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6819:                        &log($env{'user.domain'},$env{'user.name'},
                   6820:                             $env{'user.home'},
1.57      www      6821:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6822:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6823:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6824: 		       return '';
                   6825:                    }
                   6826:                }
                   6827: 	   }
1.29      www      6828:        }
1.52      www      6829:     }
                   6830:    
                   6831: #
                   6832: # Rest of the restrictions depend on selected course
                   6833: #
                   6834: 
1.620     albertel 6835:     unless ($env{'request.course.id'}) {
1.766     albertel 6836: 	if ($thisallowed eq 'A') {
                   6837: 	    return 'A';
1.814     raeburn  6838:         } elsif ($thisallowed eq 'B') {
                   6839:             return 'B';
1.766     albertel 6840: 	} else {
                   6841: 	    return '1';
                   6842: 	}
1.52      www      6843:     }
1.29      www      6844: 
1.52      www      6845: #
                   6846: # Now user is definitely in a course
                   6847: #
1.53      www      6848: 
                   6849: 
                   6850: # Course preferences
                   6851: 
                   6852:    if ($thisallowed=~/C/) {
1.620     albertel 6853:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6854:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6855:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6856: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6857: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6858: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6859: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6860: 			$env{'request.course.id'});
                   6861: 	   }
1.237     www      6862:            return '';
                   6863:        }
                   6864: 
1.620     albertel 6865:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6866: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6867: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6868: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6869: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6870: 			$env{'request.course.id'});
                   6871: 	   }
1.54      www      6872:            return '';
                   6873:        }
1.53      www      6874:    }
                   6875: 
                   6876: # Resource preferences
                   6877: 
                   6878:    if ($thisallowed=~/R/) {
1.620     albertel 6879:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6880:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6881: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6882: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6883: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6884: 	   }
                   6885: 	   return '';
1.54      www      6886:        }
1.53      www      6887:    }
1.30      www      6888: 
1.246     www      6889: # Restricted by state or randomout?
1.30      www      6890: 
1.52      www      6891:    if ($thisallowed=~/X/) {
1.620     albertel 6892:       if ($env{'acc.randomout'}) {
1.579     albertel 6893: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6894:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6895:             return ''; 
                   6896:          }
1.247     www      6897:       }
                   6898:       if (&condval($statecond)) {
1.52      www      6899: 	 return '2';
                   6900:       } else {
                   6901:          return '';
                   6902:       }
                   6903:    }
1.30      www      6904: 
1.766     albertel 6905:     if ($thisallowed eq 'A') {
                   6906: 	return 'A';
1.814     raeburn  6907:     } elsif ($thisallowed eq 'B') {
                   6908:         return 'B';
1.766     albertel 6909:     }
1.52      www      6910:    return 'F';
1.232     www      6911: }
1.1162    raeburn  6912: 
1.1192    raeburn  6913: # ------------------------------------------- Check construction space access
                   6914: 
                   6915: sub constructaccess {
                   6916:     my ($url,$setpriv)=@_;
                   6917: 
                   6918: # We do not allow editing of previous versions of files
                   6919:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6920: 
                   6921: # Get username and domain from URL
                   6922:     my ($ownername,$ownerdomain,$ownerhome);
                   6923: 
                   6924:     ($ownerdomain,$ownername) =
                   6925:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6926: 
                   6927: # The URL does not really point to any authorspace, forget it
                   6928:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6929: 
                   6930: # Now we need to see if the user has access to the authorspace of
                   6931: # $ownername at $ownerdomain
                   6932: 
                   6933:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6934: # Real author for this?
                   6935:        $ownerhome = $env{'user.home'};
                   6936:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6937:           return ($ownername,$ownerdomain,$ownerhome);
                   6938:        }
                   6939:     } else {
                   6940: # Co-author for this?
                   6941:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6942:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6943:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6944:             return ($ownername,$ownerdomain,$ownerhome);
                   6945:         }
                   6946:     }
                   6947: 
                   6948: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6949: # we might as well leave
                   6950:    unless ($setpriv) { return ''; }
                   6951: 
                   6952: # Backdoor access?
                   6953:     my $allowed=&allowed('eco',$ownerdomain);
                   6954: # Nope
                   6955:     unless ($allowed) { return ''; }
                   6956: # Looks like we may have access, but could be locked by the owner of the construction space
                   6957:     if ($allowed eq 'U') {
                   6958:         my %blocked=&get('environment',['domcoord.author'],
                   6959:                          $ownerdomain,$ownername);
                   6960: # Is blocked by owner
                   6961:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6962:     }
                   6963:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6964: # Grant temporary access
                   6965:         my $then=$env{'user.login.time'};
1.1209    raeburn  6966:         my $update=$env{'user.update.time'};
1.1192    raeburn  6967:         if (!$update) { $update = $then; }
                   6968:         my $refresh=$env{'user.refresh.time'};
                   6969:         if (!$refresh) { $refresh = $update; }
                   6970:         my $now = time;
                   6971:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6972:                            $now,'ca','constructaccess');
                   6973:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6974:         return($ownername,$ownerdomain,$ownerhome);
                   6975:     }
                   6976: # No business here
                   6977:     return '';
                   6978: }
                   6979: 
1.1162    raeburn  6980: sub get_comm_blocks {
                   6981:     my ($cdom,$cnum) = @_;
                   6982:     if ($cdom eq '' || $cnum eq '') {
                   6983:         return unless ($env{'request.course.id'});
                   6984:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6985:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6986:     }
                   6987:     my %commblocks;
                   6988:     my $hashid=$cdom.'_'.$cnum;
                   6989:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6990:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6991:         %commblocks = %{$blocksref};
                   6992:     } else {
                   6993:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6994:         my $cachetime = 600;
                   6995:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6996:     }
                   6997:     return %commblocks;
                   6998: }
                   6999: 
                   7000: sub has_comm_blocking {
                   7001:     my ($priv,$symb,$uri,$blocks) = @_;
                   7002:     return unless ($env{'request.course.id'});
                   7003:     return unless ($priv eq 'bre');
                   7004:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7005:     my %commblocks;
                   7006:     if (ref($blocks) eq 'HASH') {
                   7007:         %commblocks = %{$blocks};
                   7008:     } else {
                   7009:         %commblocks = &get_comm_blocks();
                   7010:     }
                   7011:     return unless (keys(%commblocks) > 0);
                   7012:     if (!$symb) { $symb=&symbread($uri,1); }
                   7013:     my ($map,$resid,undef)=&decode_symb($symb);
                   7014:     my %tocheck = (
                   7015:                     maps      => $map,
                   7016:                     resources => $symb,
                   7017:                   );
                   7018:     my @blockers;
                   7019:     my $now = time;
1.1163    raeburn  7020:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7021:     foreach my $block (keys(%commblocks)) {
                   7022:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7023:             my ($start,$end) = ($1,$2);
                   7024:             if ($start <= $now && $end >= $now) {
                   7025:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7026:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7027:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7028:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7029:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7030:                                     push(@blockers,$block);
                   7031:                                 }
                   7032:                             }
                   7033:                         }
                   7034:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7035:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7036:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7037:                                     push(@blockers,$block);
                   7038:                                 }
                   7039:                             }
                   7040:                         }
                   7041:                     }
                   7042:                 }
                   7043:             }
                   7044:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7045:             my $item = $1;
1.1163    raeburn  7046:             my @to_test;
1.1162    raeburn  7047:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7048:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7049:                     my $check_interval;
                   7050:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7051:                         my @interval;
                   7052:                         my $type = 'map';
                   7053:                         if ($item eq 'course') {
                   7054:                             $type = 'course';
                   7055:                             @interval=&EXT("resource.0.interval");
                   7056:                         } else {
                   7057:                             if ($item =~ /___\d+___/) {
                   7058:                                 $type = 'resource';
                   7059:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7060:                                 if (ref($navmap)) {                        
                   7061:                                     my $res = $navmap->getBySymb($item); 
                   7062:                                     push(@to_test,$res);
                   7063:                                 }
1.1162    raeburn  7064:                             } else {
                   7065:                                 my $mapsymb = &symbread($item,1);
                   7066:                                 if ($mapsymb) {
                   7067:                                     if (ref($navmap)) {
                   7068:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7069:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7070:                                         foreach my $res (@to_test) {
1.1162    raeburn  7071:                                             my $symb = $res->symb();
                   7072:                                             next if ($symb eq $mapsymb);
                   7073:                                             if ($symb ne '') {
                   7074:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7075:                                                 last;
                   7076:                                             }
                   7077:                                         }
                   7078:                                     }
                   7079:                                 }
                   7080:                             }
                   7081:                         }
                   7082:                         if ($interval[0] =~ /\d+/) {
                   7083:                             my $first_access;
                   7084:                             if ($type eq 'resource') {
                   7085:                                 $first_access=&get_first_access($interval[1],$item);
                   7086:                             } elsif ($type eq 'map') {
                   7087:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7088:                             } else {
                   7089:                                 $first_access=&get_first_access($interval[1]);
                   7090:                             }
                   7091:                             if ($first_access) {
                   7092:                                 my $timesup = $first_access+$interval[0];
                   7093:                                 if ($timesup > $now) {
1.1163    raeburn  7094:                                     foreach my $res (@to_test) {
                   7095:                                         if ($res->is_problem()) {
                   7096:                                             if ($res->completable()) {
                   7097:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7098:                                                     push(@blockers,$block);
                   7099:                                                 }
                   7100:                                                 last;
                   7101:                                             }
                   7102:                                         }
1.1162    raeburn  7103:                                     }
                   7104:                                 }
                   7105:                             }
                   7106:                         }
                   7107:                     }
                   7108:                 }
                   7109:             }
                   7110:         }
                   7111:     }
                   7112:     return @blockers;
                   7113: }
                   7114: 
                   7115: sub check_docs_block {
                   7116:     my ($docsblock,$tocheck) =@_;
                   7117:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7118:         return;
                   7119:     }
                   7120:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7121:         if ($tocheck->{'maps'}) {
                   7122:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7123:                 return 1;
                   7124:             }
                   7125:         }
                   7126:     }
                   7127:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7128:         if ($tocheck->{'resources'}) {
                   7129:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7130:                 return 1;
                   7131:             }
                   7132:         }
                   7133:     }
                   7134:     return;
                   7135: }
                   7136: 
1.1133    foxr     7137: #
                   7138: #   Removes the versino from a URI and
                   7139: #   splits it in to its filename and path to the filename.
                   7140: #   Seems like File::Basename could have done this more clearly.
                   7141: #   Parameters:
                   7142: #      $uri   - input URI
                   7143: #   Returns:
                   7144: #     Two element list consisting of 
                   7145: #     $pathname  - the URI up to and excluding the trailing /
                   7146: #     $filename  - The part of the URI following the last /
                   7147: #  NOTE:
                   7148: #    Another realization of this is simply:
                   7149: #    use File::Basename;
                   7150: #    ...
                   7151: #    $uri = shift;
                   7152: #    $filename = basename($uri);
                   7153: #    $path     = dirname($uri);
                   7154: #    return ($filename, $path);
                   7155: #
                   7156: #     The implementation below is probably faster however.
                   7157: #
1.710     albertel 7158: sub split_uri_for_cond {
                   7159:     my $uri=&deversion(&declutter(shift));
                   7160:     my @uriparts=split(/\//,$uri);
                   7161:     my $filename=pop(@uriparts);
                   7162:     my $pathname=join('/',@uriparts);
                   7163:     return ($pathname,$filename);
                   7164: }
1.232     www      7165: # --------------------------------------------------- Is a resource on the map?
                   7166: 
                   7167: sub is_on_map {
1.710     albertel 7168:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7169:     #Trying to find the conditional for the file
1.620     albertel 7170:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7171: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7172:     if ($match) {
1.289     bowersj2 7173: 	return (1,$1);
                   7174:     } else {
1.434     www      7175: 	return (0,0);
1.289     bowersj2 7176:     }
1.12      www      7177: }
                   7178: 
1.427     www      7179: # --------------------------------------------------------- Get symb from alias
                   7180: 
                   7181: sub get_symb_from_alias {
                   7182:     my $symb=shift;
                   7183:     my ($map,$resid,$url)=&decode_symb($symb);
                   7184: # Already is a symb
                   7185:     if ($url) { return $symb; }
                   7186: # Must be an alias
                   7187:     my $aliassymb='';
                   7188:     my %bighash;
1.620     albertel 7189:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7190:                             &GDBM_READER(),0640)) {
                   7191:         my $rid=$bighash{'mapalias_'.$symb};
                   7192: 	if ($rid) {
                   7193: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7194: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7195: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7196: 	}
                   7197:         untie %bighash;
                   7198:     }
                   7199:     return $aliassymb;
                   7200: }
                   7201: 
1.12      www      7202: # ----------------------------------------------------------------- Define Role
                   7203: 
                   7204: sub definerole {
                   7205:   if (allowed('mcr','/')) {
                   7206:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7207:     foreach my $role (split(':',$sysrole)) {
                   7208: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7209:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7210:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7211: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7212:                return "refused:s:$crole&$cqual"; 
                   7213:             }
                   7214:         }
1.191     harris41 7215:     }
1.800     albertel 7216:     foreach my $role (split(':',$domrole)) {
                   7217: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7218:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7219:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7220: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7221:                return "refused:d:$crole&$cqual"; 
                   7222:             }
                   7223:         }
1.191     harris41 7224:     }
1.800     albertel 7225:     foreach my $role (split(':',$courole)) {
                   7226: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7227:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7228:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7229: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7230:                return "refused:c:$crole&$cqual"; 
                   7231:             }
                   7232:         }
1.191     harris41 7233:     }
1.620     albertel 7234:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7235:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7236: 	        "rolesdef_$rolename=".
                   7237:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7238:     return reply($command,$env{'user.home'});
1.12      www      7239:   } else {
                   7240:     return 'refused';
                   7241:   }
1.105     harris41 7242: }
                   7243: 
                   7244: # ---------------- Make a metadata query against the network of library servers
                   7245: 
                   7246: sub metadata_query {
1.244     matthew  7247:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7248:     my %rhash;
1.845     albertel 7249:     my %libserv = &all_library();
1.244     matthew  7250:     my @server_list = (defined($server_array) ? @$server_array
                   7251:                                               : keys(%libserv) );
                   7252:     for my $server (@server_list) {
1.118     harris41 7253: 	unless ($custom or $customshow) {
                   7254: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7255: 	    $rhash{$server}=$reply;
                   7256: 	}
                   7257: 	else {
                   7258: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7259: 			     &escape($custom).':'.&escape($customshow),
                   7260: 			     $server);
                   7261: 	    $rhash{$server}=$reply;
                   7262: 	}
1.112     harris41 7263:     }
1.118     harris41 7264:     return \%rhash;
1.240     www      7265: }
                   7266: 
                   7267: # ----------------------------------------- Send log queries and wait for reply
                   7268: 
                   7269: sub log_query {
                   7270:     my ($uname,$udom,$query,%filters)=@_;
                   7271:     my $uhome=&homeserver($uname,$udom);
                   7272:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7273:     my $uhost=&hostname($uhome);
1.800     albertel 7274:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7275:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7276:                        $uhome);
1.479     albertel 7277:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7278:     return get_query_reply($queryid);
                   7279: }
                   7280: 
1.818     raeburn  7281: # -------------------------- Update MySQL table for portfolio file
                   7282: 
                   7283: sub update_portfolio_table {
1.821     raeburn  7284:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7285:     if ($group ne '') {
                   7286:         $file_name =~s /^\Q$group\E//;
                   7287:     }
1.818     raeburn  7288:     my $homeserver = &homeserver($uname,$udom);
                   7289:     my $queryid=
1.821     raeburn  7290:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7291:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7292:     my $reply = &get_query_reply($queryid);
                   7293:     return $reply;
                   7294: }
                   7295: 
1.899     raeburn  7296: # -------------------------- Update MySQL allusers table
                   7297: 
                   7298: sub update_allusers_table {
                   7299:     my ($uname,$udom,$names) = @_;
                   7300:     my $homeserver = &homeserver($uname,$udom);
                   7301:     my $queryid=
                   7302:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7303:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7304:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7305:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7306:                'generation='.&escape($names->{'generation'}).'%%'.
                   7307:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7308:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7309:     return;
1.899     raeburn  7310: }
                   7311: 
1.508     raeburn  7312: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7313: 
                   7314: sub fetch_enrollment_query {
1.511     raeburn  7315:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7316:     my $homeserver;
1.547     raeburn  7317:     my $maxtries = 1;
1.508     raeburn  7318:     if ($context eq 'automated') {
                   7319:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7320:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7321:     } else {
                   7322:         $homeserver = &homeserver($cnum,$dom);
                   7323:     }
1.838     albertel 7324:     my $host=&hostname($homeserver);
1.506     raeburn  7325:     my $cmd = '';
1.1000    raeburn  7326:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7327:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7328:     }
                   7329:     $cmd =~ s/%%$//;
                   7330:     $cmd = &escape($cmd);
                   7331:     my $query = 'fetchenrollment';
1.620     albertel 7332:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7333:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7334:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7335:         return 'error: '.$queryid;
                   7336:     }
1.506     raeburn  7337:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7338:     my $tries = 1;
                   7339:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7340:         $reply = &get_query_reply($queryid);
                   7341:         $tries ++;
                   7342:     }
1.526     raeburn  7343:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7344:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7345:     } else {
1.901     albertel 7346:         my @responses = split(/:/,$reply);
1.515     raeburn  7347:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7348:             foreach my $line (@responses) {
                   7349:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7350:                 $$replyref{$key} = $value;
                   7351:             }
                   7352:         } else {
1.1117    foxr     7353:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7354:             foreach my $line (@responses) {
                   7355:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7356:                 $$replyref{$key} = $value;
                   7357:                 if ($value > 0) {
1.800     albertel 7358:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7359:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7360:                         my $destname = $pathname.'/'.$filename;
                   7361:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7362:                         if ($xml_classlist =~ /^error/) {
                   7363:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7364:                         } else {
1.506     raeburn  7365:                             if ( open(FILE,">$destname") ) {
                   7366:                                 print FILE &unescape($xml_classlist);
                   7367:                                 close(FILE);
1.526     raeburn  7368:                             } else {
                   7369:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7370:                             }
                   7371:                         }
                   7372:                     }
                   7373:                 }
                   7374:             }
                   7375:         }
                   7376:         return 'ok';
                   7377:     }
                   7378:     return 'error';
                   7379: }
                   7380: 
1.242     www      7381: sub get_query_reply {
                   7382:     my $queryid=shift;
1.1117    foxr     7383:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7384:     my $reply='';
                   7385:     for (1..100) {
                   7386: 	sleep 2;
                   7387:         if (-e $replyfile.'.end') {
1.448     albertel 7388: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7389: 		$reply = join('',<$fh>);
                   7390: 		close($fh);
1.240     www      7391: 	   } else { return 'error: reply_file_error'; }
1.242     www      7392:            return &unescape($reply);
                   7393: 	}
1.240     www      7394:     }
1.242     www      7395:     return 'timeout:'.$queryid;
1.240     www      7396: }
                   7397: 
                   7398: sub courselog_query {
1.241     www      7399: #
                   7400: # possible filters:
                   7401: # url: url or symb
                   7402: # username
                   7403: # domain
                   7404: # action: view, submit, grade
                   7405: # start: timestamp
                   7406: # end: timestamp
                   7407: #
1.240     www      7408:     my (%filters)=@_;
1.620     albertel 7409:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7410:     if ($filters{'url'}) {
                   7411: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7412:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7413:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7414:     }
1.620     albertel 7415:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7416:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7417:     return &log_query($cname,$cdom,'courselog',%filters);
                   7418: }
                   7419: 
                   7420: sub userlog_query {
1.858     raeburn  7421: #
                   7422: # possible filters:
                   7423: # action: log check role
                   7424: # start: timestamp
                   7425: # end: timestamp
                   7426: #
1.240     www      7427:     my ($uname,$udom,%filters)=@_;
                   7428:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7429: }
                   7430: 
1.506     raeburn  7431: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7432: 
                   7433: sub auto_run {
1.508     raeburn  7434:     my ($cnum,$cdom) = @_;
1.876     raeburn  7435:     my $response = 0;
                   7436:     my $settings;
                   7437:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7438:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7439:         $settings = $domconfig{'autoenroll'};
                   7440:         if ($settings->{'run'} eq '1') {
                   7441:             $response = 1;
                   7442:         }
                   7443:     } else {
1.934     raeburn  7444:         my $homeserver;
                   7445:         if (&is_course($cdom,$cnum)) {
                   7446:             $homeserver = &homeserver($cnum,$cdom);
                   7447:         } else {
                   7448:             $homeserver = &domain($cdom,'primary');
                   7449:         }
                   7450:         if ($homeserver ne 'no_host') {
                   7451:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7452:         }
1.876     raeburn  7453:     }
1.506     raeburn  7454:     return $response;
                   7455: }
1.776     albertel 7456: 
1.506     raeburn  7457: sub auto_get_sections {
1.508     raeburn  7458:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7459:     my $homeserver;
                   7460:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7461:         $homeserver = &homeserver($cnum,$cdom);
                   7462:     }
                   7463:     if (!defined($homeserver)) { 
                   7464:         if ($cdom =~ /^$match_domain$/) {
                   7465:             $homeserver = &domain($cdom,'primary');
                   7466:         }
                   7467:     }
                   7468:     my @secs;
                   7469:     if (defined($homeserver)) {
                   7470:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7471:         unless ($response eq 'refused') {
                   7472:             @secs = split(/:/,$response);
                   7473:         }
1.506     raeburn  7474:     }
                   7475:     return @secs;
                   7476: }
1.776     albertel 7477: 
1.506     raeburn  7478: sub auto_new_course {
1.1099    raeburn  7479:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7480:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7481:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7482:     return $response;
                   7483: }
1.776     albertel 7484: 
1.506     raeburn  7485: sub auto_validate_courseID {
1.508     raeburn  7486:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7487:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7488:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7489:     return $response;
                   7490: }
1.776     albertel 7491: 
1.1007    raeburn  7492: sub auto_validate_instcode {
1.1020    raeburn  7493:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7494:     my ($homeserver,$response);
                   7495:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7496:         $homeserver = &homeserver($cnum,$cdom);
                   7497:     }
                   7498:     if (!defined($homeserver)) {
                   7499:         if ($cdom =~ /^$match_domain$/) {
                   7500:             $homeserver = &domain($cdom,'primary');
                   7501:         }
                   7502:     }
1.1065    raeburn  7503:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7504:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7505:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7506:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7507: }
                   7508: 
1.506     raeburn  7509: sub auto_create_password {
1.873     raeburn  7510:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7511:     my ($homeserver,$response);
1.506     raeburn  7512:     my $create_passwd = 0;
                   7513:     my $authchk = '';
1.873     raeburn  7514:     if ($udom =~ /^$match_domain$/) {
                   7515:         $homeserver = &domain($udom,'primary');
                   7516:     }
                   7517:     if ($homeserver eq '') {
                   7518:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7519:             $homeserver = &homeserver($cnum,$cdom);
                   7520:         }
                   7521:     }
                   7522:     if ($homeserver eq '') {
                   7523:         $authchk = 'nodomain';
1.506     raeburn  7524:     } else {
1.873     raeburn  7525:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7526:         if ($response eq 'refused') {
                   7527:             $authchk = 'refused';
                   7528:         } else {
1.901     albertel 7529:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7530:         }
1.506     raeburn  7531:     }
                   7532:     return ($authparam,$create_passwd,$authchk);
                   7533: }
                   7534: 
1.706     raeburn  7535: sub auto_photo_permission {
                   7536:     my ($cnum,$cdom,$students) = @_;
                   7537:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7538:     my ($outcome,$perm_reqd,$conditions) = 
                   7539: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7540:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7541: 	return (undef,undef);
                   7542:     }
1.706     raeburn  7543:     return ($outcome,$perm_reqd,$conditions);
                   7544: }
                   7545: 
                   7546: sub auto_checkphotos {
                   7547:     my ($uname,$udom,$pid) = @_;
                   7548:     my $homeserver = &homeserver($uname,$udom);
                   7549:     my ($result,$resulttype);
                   7550:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7551: 				   &escape($uname).':'.&escape($pid),
                   7552: 				   $homeserver));
1.709     albertel 7553:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7554: 	return (undef,undef);
                   7555:     }
1.706     raeburn  7556:     if ($outcome) {
                   7557:         ($result,$resulttype) = split(/:/,$outcome);
                   7558:     } 
                   7559:     return ($result,$resulttype);
                   7560: }
                   7561: 
                   7562: sub auto_photochoice {
                   7563:     my ($cnum,$cdom) = @_;
                   7564:     my $homeserver = &homeserver($cnum,$cdom);
                   7565:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7566: 						       &escape($cdom),
                   7567: 						       $homeserver)));
1.709     albertel 7568:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7569: 	return (undef,undef);
                   7570:     }
1.706     raeburn  7571:     return ($update,$comment);
                   7572: }
                   7573: 
                   7574: sub auto_photoupdate {
                   7575:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7576:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7577:     my $host=&hostname($homeserver);
1.706     raeburn  7578:     my $cmd = '';
                   7579:     my $maxtries = 1;
1.800     albertel 7580:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7581:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7582:     }
                   7583:     $cmd =~ s/%%$//;
                   7584:     $cmd = &escape($cmd);
                   7585:     my $query = 'institutionalphotos';
                   7586:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7587:     unless ($queryid=~/^\Q$host\E\_/) {
                   7588:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7589:         return 'error: '.$queryid;
                   7590:     }
                   7591:     my $reply = &get_query_reply($queryid);
                   7592:     my $tries = 1;
                   7593:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7594:         $reply = &get_query_reply($queryid);
                   7595:         $tries ++;
                   7596:     }
                   7597:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7598:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7599:     } else {
                   7600:         my @responses = split(/:/,$reply);
                   7601:         my $outcome = shift(@responses); 
                   7602:         foreach my $item (@responses) {
                   7603:             my ($key,$value) = split(/=/,$item);
                   7604:             $$photo{$key} = $value;
                   7605:         }
                   7606:         return $outcome;
                   7607:     }
                   7608:     return 'error';
                   7609: }
                   7610: 
1.521     raeburn  7611: sub auto_instcode_format {
1.793     albertel 7612:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7613: 	$cat_order) = @_;
1.521     raeburn  7614:     my $courses = '';
1.772     raeburn  7615:     my @homeservers;
1.521     raeburn  7616:     if ($caller eq 'global') {
1.841     albertel 7617: 	my %servers = &get_servers($codedom,'library');
                   7618: 	foreach my $tryserver (keys(%servers)) {
                   7619: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7620: 		push(@homeservers,$tryserver);
                   7621: 	    }
1.584     raeburn  7622:         }
1.1022    raeburn  7623:     } elsif ($caller eq 'requests') {
                   7624:         if ($codedom =~ /^$match_domain$/) {
                   7625:             my $chome = &domain($codedom,'primary');
                   7626:             unless ($chome eq 'no_host') {
                   7627:                 push(@homeservers,$chome);
                   7628:             }
                   7629:         }
1.521     raeburn  7630:     } else {
1.772     raeburn  7631:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7632:     }
1.793     albertel 7633:     foreach my $code (keys(%{$instcodes})) {
                   7634:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7635:     }
                   7636:     chop($courses);
1.772     raeburn  7637:     my $ok_response = 0;
                   7638:     my $response;
                   7639:     while (@homeservers > 0 && $ok_response == 0) {
                   7640:         my $server = shift(@homeservers); 
                   7641:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7642:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7643:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7644: 		split(/:/,$response);
1.772     raeburn  7645:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7646:             push(@{$codetitles},&str2array($codetitles_str));
                   7647:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7648:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7649:             $ok_response = 1;
                   7650:         }
                   7651:     }
                   7652:     if ($ok_response) {
1.521     raeburn  7653:         return 'ok';
1.772     raeburn  7654:     } else {
                   7655:         return $response;
1.521     raeburn  7656:     }
                   7657: }
                   7658: 
1.792     raeburn  7659: sub auto_instcode_defaults {
                   7660:     my ($domain,$returnhash,$code_order) = @_;
                   7661:     my @homeservers;
1.841     albertel 7662: 
                   7663:     my %servers = &get_servers($domain,'library');
                   7664:     foreach my $tryserver (keys(%servers)) {
                   7665: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7666: 	    push(@homeservers,$tryserver);
                   7667: 	}
1.792     raeburn  7668:     }
1.841     albertel 7669: 
1.792     raeburn  7670:     my $response;
1.841     albertel 7671:     foreach my $server (@homeservers) {
1.792     raeburn  7672:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7673:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7674: 	
                   7675: 	foreach my $pair (split(/\&/,$response)) {
                   7676: 	    my ($name,$value)=split(/\=/,$pair);
                   7677: 	    if ($name eq 'code_order') {
                   7678: 		@{$code_order} = split(/\&/,&unescape($value));
                   7679: 	    } else {
                   7680: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7681: 	    }
                   7682: 	}
                   7683: 	return 'ok';
1.792     raeburn  7684:     }
1.841     albertel 7685: 
                   7686:     return $response;
1.1003    raeburn  7687: }
                   7688: 
                   7689: sub auto_possible_instcodes {
1.1007    raeburn  7690:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7691:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7692:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7693:         return;
                   7694:     }
1.1003    raeburn  7695:     my (@homeservers,$uhome);
                   7696:     if (defined(&domain($domain,'primary'))) {
                   7697:         $uhome=&domain($domain,'primary');
                   7698:         push(@homeservers,&domain($domain,'primary'));
                   7699:     } else {
                   7700:         my %servers = &get_servers($domain,'library');
                   7701:         foreach my $tryserver (keys(%servers)) {
                   7702:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7703:                 push(@homeservers,$tryserver);
                   7704:             }
                   7705:         }
                   7706:     }
                   7707:     my $response;
                   7708:     foreach my $server (@homeservers) {
                   7709:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7710:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7711:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7712:             split(':',$response);
                   7713:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7714:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7715:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7716:             my ($name,$value)=split('=',$item);
                   7717:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7718:         }
                   7719:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7720:             my ($name,$value)=split('=',$item);
                   7721:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7722:         }
                   7723:         return 'ok';
                   7724:     }
                   7725:     return $response;
                   7726: }
1.792     raeburn  7727: 
1.1010    raeburn  7728: sub auto_courserequest_checks {
                   7729:     my ($dom) = @_;
1.1020    raeburn  7730:     my ($homeserver,%validations);
                   7731:     if ($dom =~ /^$match_domain$/) {
                   7732:         $homeserver = &domain($dom,'primary');
                   7733:     }
                   7734:     unless ($homeserver eq 'no_host') {
                   7735:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7736:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7737:             my @items = split(/&/,$response);
                   7738:             foreach my $item (@items) {
                   7739:                 my ($key,$value) = split('=',$item);
                   7740:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7741:             }
                   7742:         }
                   7743:     }
1.1010    raeburn  7744:     return %validations; 
                   7745: }
                   7746: 
1.1020    raeburn  7747: sub auto_courserequest_validation {
                   7748:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7749:     my ($homeserver,$response);
                   7750:     if ($dom =~ /^$match_domain$/) {
                   7751:         $homeserver = &domain($dom,'primary');
                   7752:     }
                   7753:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7754:           
1.1020    raeburn  7755:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7756:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7757:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7758:                                     $homeserver));
                   7759:     }
                   7760:     return $response;
                   7761: }
                   7762: 
1.777     albertel 7763: sub auto_validate_class_sec {
1.918     raeburn  7764:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7765:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7766:     my $ownerlist;
                   7767:     if (ref($owners) eq 'ARRAY') {
                   7768:         $ownerlist = join(',',@{$owners});
                   7769:     } else {
                   7770:         $ownerlist = $owners;
                   7771:     }
1.773     raeburn  7772:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7773:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7774:     return $response;
                   7775: }
                   7776: 
1.679     raeburn  7777: # ------------------------------------------------------- Course Group routines
                   7778: 
                   7779: sub get_coursegroups {
1.809     raeburn  7780:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7781:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7782: }
                   7783: 
1.679     raeburn  7784: sub modify_coursegroup {
                   7785:     my ($cdom,$cnum,$groupsettings) = @_;
                   7786:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7787: }
                   7788: 
1.809     raeburn  7789: sub toggle_coursegroup_status {
                   7790:     my ($cdom,$cnum,$group,$action) = @_;
                   7791:     my ($from_namespace,$to_namespace);
                   7792:     if ($action eq 'delete') {
                   7793:         $from_namespace = 'coursegroups';
                   7794:         $to_namespace = 'deleted_groups';
                   7795:     } else {
                   7796:         $from_namespace = 'deleted_groups';
                   7797:         $to_namespace = 'coursegroups';
                   7798:     }
                   7799:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7800:     if (my $tmp = &error(%curr_group)) {
                   7801:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7802:         return ('read error',$tmp);
                   7803:     } else {
                   7804:         my %savedsettings = %curr_group; 
1.809     raeburn  7805:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7806:         my $deloutcome;
                   7807:         if ($result eq 'ok') {
1.809     raeburn  7808:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7809:         } else {
                   7810:             return ('write error',$result);
                   7811:         }
                   7812:         if ($deloutcome eq 'ok') {
                   7813:             return 'ok';
                   7814:         } else {
                   7815:             return ('delete error',$deloutcome);
                   7816:         }
                   7817:     }
                   7818: }
                   7819: 
1.679     raeburn  7820: sub modify_group_roles {
1.957     raeburn  7821:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7822:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7823:     my $role = 'gr/'.&escape($userprivs);
                   7824:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7825:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7826:     if ($result eq 'ok') {
                   7827:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7828:     }
1.679     raeburn  7829:     return $result;
                   7830: }
                   7831: 
                   7832: sub modify_coursegroup_membership {
                   7833:     my ($cdom,$cnum,$membership) = @_;
                   7834:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7835:     return $result;
                   7836: }
                   7837: 
1.682     raeburn  7838: sub get_active_groups {
                   7839:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7840:     my $now = time;
                   7841:     my %groups = ();
                   7842:     foreach my $key (keys(%env)) {
1.811     albertel 7843:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7844:             my ($start,$end) = split(/\./,$env{$key});
                   7845:             if (($end!=0) && ($end<$now)) { next; }
                   7846:             if (($start!=0) && ($start>$now)) { next; }
                   7847:             if ($1 eq $cdom && $2 eq $cnum) {
                   7848:                 $groups{$3} = $env{$key} ;
                   7849:             }
                   7850:         }
                   7851:     }
                   7852:     return %groups;
                   7853: }
                   7854: 
1.683     raeburn  7855: sub get_group_membership {
                   7856:     my ($cdom,$cnum,$group) = @_;
                   7857:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7858: }
                   7859: 
                   7860: sub get_users_groups {
                   7861:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7862:     my @usersgroups;
1.683     raeburn  7863:     my $cachetime=1800;
                   7864: 
                   7865:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7866:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7867:     if (defined($cached)) {
1.734     albertel 7868:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7869:     } else {  
                   7870:         $grouplist = '';
1.816     raeburn  7871:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7872:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7873:         my $access_end = $env{'course.'.$courseid.
                   7874:                               '.default_enrollment_end_date'};
                   7875:         my $now = time;
                   7876:         foreach my $key (keys(%roleshash)) {
                   7877:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7878:                 my $group = $1;
                   7879:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7880:                     my $start = $2;
                   7881:                     my $end = $1;
                   7882:                     if ($start == -1) { next; } # deleted from group
                   7883:                     if (($start!=0) && ($start>$now)) { next; }
                   7884:                     if (($end!=0) && ($end<$now)) {
                   7885:                         if ($access_end && $access_end < $now) {
                   7886:                             if ($access_end - $end < 86400) {
                   7887:                                 push(@usersgroups,$group);
1.733     raeburn  7888:                             }
                   7889:                         }
1.817     raeburn  7890:                         next;
1.733     raeburn  7891:                     }
1.817     raeburn  7892:                     push(@usersgroups,$group);
1.683     raeburn  7893:                 }
                   7894:             }
                   7895:         }
1.817     raeburn  7896:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7897:         $grouplist = join(':',@usersgroups);
                   7898:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7899:     }
1.733     raeburn  7900:     return @usersgroups;
1.683     raeburn  7901: }
                   7902: 
                   7903: sub devalidate_getgroups_cache {
                   7904:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7905:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7906: 
1.683     raeburn  7907:     my $hashid="$udom:$uname:$courseid";
                   7908:     &devalidate_cache_new('getgroups',$hashid);
                   7909: }
                   7910: 
1.12      www      7911: # ------------------------------------------------------------------ Plain Text
                   7912: 
                   7913: sub plaintext {
1.988     raeburn  7914:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7915:     if ($short =~ m{^cr/}) {
1.758     albertel 7916: 	return (split('/',$short))[-1];
                   7917:     }
1.742     raeburn  7918:     if (!defined($cid)) {
                   7919:         $cid = $env{'request.course.id'};
                   7920:     }
                   7921:     my %rolenames = (
1.1008    raeburn  7922:                       Course    => 'std',
                   7923:                       Community => 'alt1',
1.742     raeburn  7924:                     );
1.1037    raeburn  7925:     if ($cid ne '') {
                   7926:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7927:             unless ($forcedefault) {
                   7928:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7929:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7930:                 return &Apache::lonlocal::mt($roletext);
                   7931:             }
                   7932:         }
                   7933:     }
                   7934:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7935:         (defined($rolenames{$type})) && 
                   7936:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7937:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7938:     } elsif ($cid ne '') {
                   7939:         my $crstype = $env{'course.'.$cid.'.type'};
                   7940:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7941:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7942:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7943:         }
1.742     raeburn  7944:     }
1.1037    raeburn  7945:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7946: }
                   7947: 
                   7948: # ----------------------------------------------------------------- Assign Role
                   7949: 
                   7950: sub assignrole {
1.957     raeburn  7951:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7952:         $context)=@_;
1.21      www      7953:     my $mrole;
                   7954:     if ($role =~ /^cr\//) {
1.393     www      7955:         my $cwosec=$url;
1.811     albertel 7956:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7957: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7958:            my $refused = 1;
                   7959:            if ($context eq 'requestcourses') {
                   7960:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7961:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7962:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7963:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7964:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7965:                            if ($crsenv{'internal.courseowner'} eq
                   7966:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7967:                                $refused = '';
                   7968:                            }
                   7969:                        }
                   7970:                    }
                   7971:                }
                   7972:            }
                   7973:            if ($refused) {
                   7974:                &logthis('Refused custom assignrole: '.
                   7975:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7976:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7977:                return 'refused';
                   7978:            }
1.104     www      7979:         }
1.21      www      7980:         $mrole='cr';
1.678     raeburn  7981:     } elsif ($role =~ /^gr\//) {
                   7982:         my $cwogrp=$url;
1.811     albertel 7983:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7984:         unless (&allowed('mdg',$cwogrp)) {
                   7985:             &logthis('Refused group assignrole: '.
                   7986:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7987:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7988:             return 'refused';
                   7989:         }
                   7990:         $mrole='gr';
1.21      www      7991:     } else {
1.82      www      7992:         my $cwosec=$url;
1.811     albertel 7993:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7994:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7995:             my $refused;
                   7996:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7997:                 if (!(&allowed('c'.$role,$url))) {
                   7998:                     $refused = 1;
                   7999:                 }
                   8000:             } else {
                   8001:                 $refused = 1;
                   8002:             }
1.947     raeburn  8003:             if ($refused) {
1.1045    raeburn  8004:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8005:                 if (!$selfenroll && $context eq 'course') {
                   8006:                     my %crsenv;
                   8007:                     if ($role eq 'cc' || $role eq 'co') {
                   8008:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8009:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8010:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8011:                                 if ($crsenv{'internal.courseowner'} eq 
                   8012:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8013:                                     $refused = '';
                   8014:                                 }
                   8015:                             }
                   8016:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8017:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8018:                                 if ($crsenv{'internal.courseowner'} eq 
                   8019:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8020:                                     $refused = '';
                   8021:                                 }
                   8022:                             }
                   8023:                         }
                   8024:                     }
                   8025:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8026:                     $refused = '';
1.1017    raeburn  8027:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8028:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8029:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8030:                         my $wrongcc;
                   8031:                         if ($cnum =~ /^$match_community$/) {
                   8032:                             $wrongcc = 1 if ($role eq 'cc');
                   8033:                         } else {
                   8034:                             $wrongcc = 1 if ($role eq 'co');
                   8035:                         }
                   8036:                         unless ($wrongcc) {
                   8037:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8038:                             if ($crsenv{'internal.courseowner'} eq 
                   8039:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8040:                                 $refused = '';
                   8041:                             }
1.1017    raeburn  8042:                         }
                   8043:                     }
1.1183    raeburn  8044:                 } elsif ($context eq 'requestauthor') {
                   8045:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8046:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8047:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8048:                             $refused = '';
                   8049:                         } else {
                   8050:                             my %domdefaults = &get_domain_defaults($udom);
                   8051:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8052:                                 my $checkbystatus;
                   8053:                                 if ($env{'user.adv'}) { 
                   8054:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8055:                                     if ($disposition eq 'automatic') {
                   8056:                                         $refused = '';
                   8057:                                     } elsif ($disposition eq '') {
                   8058:                                         $checkbystatus = 1;
                   8059:                                     } 
                   8060:                                 } else {
                   8061:                                     $checkbystatus = 1;
                   8062:                                 }
                   8063:                                 if ($checkbystatus) {
                   8064:                                     if ($env{'environment.inststatus'}) {
                   8065:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8066:                                         foreach my $type (@inststatuses) {
                   8067:                                             if (($type ne '') &&
                   8068:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8069:                                                 $refused = '';
                   8070:                                             }
                   8071:                                         }
                   8072:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8073:                                         $refused = '';
                   8074:                                     }
                   8075:                                 }
                   8076:                             }
                   8077:                         }
                   8078:                     }
1.1017    raeburn  8079:                 }
                   8080:                 if ($refused) {
1.947     raeburn  8081:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8082:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8083: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8084:                     return 'refused';
                   8085:                 }
1.932     raeburn  8086:             }
1.1131    raeburn  8087:         } elsif ($role eq 'au') {
                   8088:             if ($url ne '/'.$udom.'/') {
                   8089:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8090:                          ' to assign author role for '.$uname.':'.$udom.
                   8091:                          ' in domain: '.$url.' refused (wrong domain).');
                   8092:                 return 'refused';
                   8093:             }
1.104     www      8094:         }
1.21      www      8095:         $mrole=$role;
                   8096:     }
1.620     albertel 8097:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8098:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8099:     if ($end) { $command.='_'.$end; }
1.21      www      8100:     if ($start) {
                   8101: 	if ($end) { 
1.81      www      8102:            $command.='_'.$start; 
1.21      www      8103:         } else {
1.81      www      8104:            $command.='_0_'.$start;
1.21      www      8105:         }
                   8106:     }
1.739     raeburn  8107:     my $origstart = $start;
                   8108:     my $origend = $end;
1.957     raeburn  8109:     my $delflag;
1.357     www      8110: # actually delete
                   8111:     if ($deleteflag) {
1.373     www      8112: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8113: # modify command to delete the role
1.620     albertel 8114:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8115:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8116: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8117: # set start and finish to negative values for userrolelog
                   8118:            $start=-1;
                   8119:            $end=-1;
1.957     raeburn  8120:            $delflag = 1;
1.357     www      8121:         }
                   8122:     }
                   8123: # send command
1.349     www      8124:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8125: # log new user role if status is ok
1.349     www      8126:     if ($answer eq 'ok') {
1.663     raeburn  8127: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8128:         if (($role eq 'cc') || ($role eq 'in') ||
                   8129:             ($role eq 'ep') || ($role eq 'ad') ||
                   8130:             ($role eq 'ta') || ($role eq 'st') ||
                   8131:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8132:             ($role eq 'co')) {
1.1200    raeburn  8133: # for course roles, perform group memberships changes triggered by role change.
                   8134:             unless ($role =~ /^gr/) {
                   8135:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8136:                                                  $origstart,$selfenroll,$context);
                   8137:             }
1.1184    raeburn  8138:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8139:                            $selfenroll,$context);
                   8140:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8141:                  ($role eq 'au') || ($role eq 'dc')) {
                   8142:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8143:                            $context);
                   8144:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8145:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8146:                              $context); 
                   8147:         }
1.1053    raeburn  8148:         if ($role eq 'cc') {
                   8149:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8150:         }
1.349     www      8151:     }
                   8152:     return $answer;
1.169     harris41 8153: }
                   8154: 
1.1053    raeburn  8155: sub autoupdate_coowners {
                   8156:     my ($url,$end,$start,$uname,$udom) = @_;
                   8157:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8158:     if (($cdom ne '') && ($cnum ne '')) {
                   8159:         my $now = time;
                   8160:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8161:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8162:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8163:             my $instcode = $coursehash{'internal.coursecode'};
                   8164:             if ($instcode ne '') {
1.1056    raeburn  8165:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8166:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8167:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8168:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8169:                         if ($result eq 'valid') {
                   8170:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8171:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8172:                                     push(@newcoowners,$coowner);
                   8173:                                 }
                   8174:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8175:                                     push(@newcoowners,$uname.':'.$udom);
                   8176:                                 }
                   8177:                                 @newcoowners = sort(@newcoowners);
                   8178:                             } else {
                   8179:                                 push(@newcoowners,$uname.':'.$udom);
                   8180:                             }
                   8181:                         } else {
                   8182:                             if ($coursehash{'internal.co-owners'}) {
                   8183:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8184:                                     unless ($coowner eq $uname.':'.$udom) {
                   8185:                                         push(@newcoowners,$coowner);
                   8186:                                     }
                   8187:                                 }
                   8188:                                 unless (@newcoowners > 0) {
                   8189:                                     $delcoowners = 1;
                   8190:                                     $coowners = '';
                   8191:                                 }
                   8192:                             }
                   8193:                         }
                   8194:                         if (@newcoowners || $delcoowners) {
                   8195:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8196:                                             $delcoowners,@newcoowners);
                   8197:                         }
                   8198:                     }
                   8199:                 }
                   8200:             }
                   8201:         }
                   8202:     }
                   8203: }
                   8204: 
                   8205: sub store_coowners {
                   8206:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8207:     my $cid = $cdom.'_'.$cnum;
                   8208:     my ($coowners,$delresult,$putresult);
                   8209:     if (@newcoowners) {
                   8210:         $coowners = join(',',@newcoowners);
                   8211:         my %coownershash = (
                   8212:                             'internal.co-owners' => $coowners,
                   8213:                            );
                   8214:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8215:         if ($putresult eq 'ok') {
                   8216:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8217:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8218:             }
                   8219:         }
                   8220:     }
                   8221:     if ($delcoowners) {
                   8222:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8223:         if ($delresult eq 'ok') {
                   8224:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8225:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8226:             }
                   8227:         }
                   8228:     }
                   8229:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8230:         my %crsinfo =
                   8231:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8232:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8233:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8234:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8235:         }
                   8236:     }
                   8237: }
                   8238: 
1.169     harris41 8239: # -------------------------------------------------- Modify user authentication
1.197     www      8240: # Overrides without validation
                   8241: 
1.169     harris41 8242: sub modifyuserauth {
                   8243:     my ($udom,$uname,$umode,$upass)=@_;
                   8244:     my $uhome=&homeserver($uname,$udom);
1.197     www      8245:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8246:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8247:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8248:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8249:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8250: 		     &escape($upass),$uhome);
1.620     albertel 8251:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8252:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8253:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8254:     &log($udom,,$uname,$uhome,
1.620     albertel 8255:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8256:                                      $env{'user.name'}.', '.$umode.
1.197     www      8257:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8258:     unless ($reply eq 'ok') {
1.197     www      8259:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8260: 	return 'error: '.$reply;
                   8261:     }   
1.170     harris41 8262:     return 'ok';
1.80      www      8263: }
                   8264: 
1.81      www      8265: # --------------------------------------------------------------- Modify a user
1.80      www      8266: 
1.81      www      8267: sub modifyuser {
1.206     matthew  8268:     my ($udom,    $uname, $uid,
                   8269:         $umode,   $upass, $first,
                   8270:         $middle,  $last,  $gene,
1.1058    raeburn  8271:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8272:     $udom= &LONCAPA::clean_domain($udom);
                   8273:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8274:     my $showcandelete = 'none';
                   8275:     if (ref($candelete) eq 'ARRAY') {
                   8276:         if (@{$candelete} > 0) {
                   8277:             $showcandelete = join(', ',@{$candelete});
                   8278:         }
                   8279:     }
1.81      www      8280:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8281:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8282: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8283:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8284:                                      ' desiredhome not specified'). 
1.620     albertel 8285:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8286:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8287:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8288:     my $newuser;
                   8289:     if ($uhome eq 'no_host') {
                   8290:         $newuser = 1;
                   8291:     }
1.80      www      8292: # ----------------------------------------------------------------- Create User
1.406     albertel 8293:     if (($uhome eq 'no_host') && 
                   8294: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8295:         my $unhome='';
1.844     albertel 8296:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8297:             $unhome = $desiredhome;
1.620     albertel 8298: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8299: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8300:         } else { # load balancing routine for determining $unhome
1.81      www      8301:             my $loadm=10000000;
1.841     albertel 8302: 	    my %servers = &get_servers($udom,'library');
                   8303: 	    foreach my $tryserver (keys(%servers)) {
                   8304: 		my $answer=reply('load',$tryserver);
                   8305: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8306: 		    $loadm=$answer;
                   8307: 		    $unhome=$tryserver;
                   8308: 		}
1.80      www      8309: 	    }
                   8310:         }
                   8311:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8312: 	    return 'error: unable to find a home server for '.$uname.
                   8313:                    ' in domain '.$udom;
1.80      www      8314:         }
                   8315:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8316:                          &escape($upass),$unhome);
                   8317: 	unless ($reply eq 'ok') {
                   8318:             return 'error: '.$reply;
                   8319:         }   
1.230     stredwic 8320:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8321:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8322: 	    return 'error: unable verify users home machine.';
1.80      www      8323:         }
1.209     matthew  8324:     }   # End of creation of new user
1.80      www      8325: # ---------------------------------------------------------------------- Add ID
                   8326:     if ($uid) {
                   8327:        $uid=~tr/A-Z/a-z/;
                   8328:        my %uidhash=&idrget($udom,$uname);
1.196     www      8329:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8330:          && (!$forceid)) {
1.80      www      8331: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8332: 	      return 'error: user id "'.$uid.'" does not match '.
                   8333:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8334:           }
                   8335:        } else {
                   8336: 	  &idput($udom,($uname => $uid));
                   8337:        }
                   8338:     }
                   8339: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8340:     my @tmp=&get('environment',
1.899     raeburn  8341: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8342:                     'permanentemail','inststatus'],
1.134     albertel 8343: 		   $udom,$uname);
1.1075    raeburn  8344:     my (%names,%oldnames);
1.313     matthew  8345:     if ($tmp[0] =~ m/^error:.*/) { 
                   8346:         %names=(); 
                   8347:     } else {
                   8348:         %names = @tmp;
1.1075    raeburn  8349:         %oldnames = %names;
1.313     matthew  8350:     }
1.388     www      8351: #
1.1058    raeburn  8352: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8353: # of users did not contain them), do not overwrite existing values
                   8354: # unless field is in $candelete array ref.  
                   8355: #
                   8356: 
                   8357:     my @fields = ('firstname','middlename','lastname','generation',
                   8358:                   'permanentemail','id');
                   8359:     my %newvalues;
                   8360:     if (ref($candelete) eq 'ARRAY') {
                   8361:         foreach my $field (@fields) {
                   8362:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8363:                 if ($field eq 'firstname') {
                   8364:                     $names{$field} = $first;
                   8365:                 } elsif ($field eq 'middlename') {
                   8366:                     $names{$field} = $middle;
                   8367:                 } elsif ($field eq 'lastname') {
                   8368:                     $names{$field} = $last;
                   8369:                 } elsif ($field eq 'generation') { 
                   8370:                     $names{$field} = $gene;
                   8371:                 } elsif ($field eq 'permanentemail') {
                   8372:                     $names{$field} = $email;
                   8373:                 } elsif ($field eq 'id') {
                   8374:                     $names{$field}  = $uid;
                   8375:                 }
                   8376:             }
                   8377:         }
                   8378:     }
1.388     www      8379:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8380:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8381:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8382:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8383:     if ($email) {
                   8384:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8385:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8386:     }
1.899     raeburn  8387:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8388:     if (defined($inststatus)) {
                   8389:         $names{'inststatus'} = '';
                   8390:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8391:         if (ref($usertypes) eq 'HASH') {
                   8392:             my @okstatuses; 
                   8393:             foreach my $item (split(/:/,$inststatus)) {
                   8394:                 if (defined($usertypes->{$item})) {
                   8395:                     push(@okstatuses,$item);  
                   8396:                 }
                   8397:             }
                   8398:             if (@okstatuses) {
                   8399:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8400:             }
                   8401:         }
                   8402:     }
1.1075    raeburn  8403:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8404:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8405:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8406:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8407:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8408:     } else {
                   8409:         $logmsg .= ' during self creation';
                   8410:     }
1.1075    raeburn  8411:     my $changed;
                   8412:     if ($newuser) {
                   8413:         $changed = 1;
                   8414:     } else {
                   8415:         foreach my $field (@fields) {
                   8416:             if ($names{$field} ne $oldnames{$field}) {
                   8417:                 $changed = 1;
                   8418:                 last;
                   8419:             }
                   8420:         }
                   8421:     }
                   8422:     unless ($changed) {
                   8423:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8424:         &logthis($logmsg);
                   8425:         return 'ok';
                   8426:     }
                   8427:     my $reply = &put('environment', \%names, $udom,$uname);
                   8428:     if ($reply ne 'ok') { 
                   8429:         return 'error: '.$reply;
                   8430:     }
1.1087    raeburn  8431:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8432:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8433:     }
1.1075    raeburn  8434:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8435:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8436:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8437:     &logthis($logmsg);
1.134     albertel 8438:     return 'ok';
1.80      www      8439: }
                   8440: 
1.81      www      8441: # -------------------------------------------------------------- Modify student
1.80      www      8442: 
1.81      www      8443: sub modifystudent {
                   8444:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8445:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8446:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8447:     if (!$cid) {
1.620     albertel 8448: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8449: 	    return 'not_in_class';
                   8450: 	}
1.80      www      8451:     }
                   8452: # --------------------------------------------------------------- Make the user
1.81      www      8453:     my $reply=&modifyuser
1.209     matthew  8454: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8455:          $desiredhome,$email,$inststatus);
1.80      www      8456:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8457:     # This will cause &modify_student_enrollment to get the uid from the
                   8458:     # students environment
                   8459:     $uid = undef if (!$forceid);
1.455     albertel 8460:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8461:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8462:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8463:     return $reply;
                   8464: }
                   8465: 
                   8466: sub modify_student_enrollment {
1.1216    raeburn  8467:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8468:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8469:     my ($cdom,$cnum,$chome);
                   8470:     if (!$cid) {
1.620     albertel 8471: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8472: 	    return 'not_in_class';
                   8473: 	}
1.620     albertel 8474: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8475: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8476:     } else {
                   8477: 	($cdom,$cnum)=split(/_/,$cid);
                   8478:     }
1.620     albertel 8479:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8480:     if (!$chome) {
1.457     raeburn  8481: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8482:     }
1.455     albertel 8483:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8484:     # Make sure the user exists
1.81      www      8485:     my $uhome=&homeserver($uname,$udom);
                   8486:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8487: 	return 'error: no such user';
                   8488:     }
1.297     matthew  8489:     # Get student data if we were not given enough information
                   8490:     if (!defined($first)  || $first  eq '' || 
                   8491:         !defined($last)   || $last   eq '' || 
                   8492:         !defined($uid)    || $uid    eq '' || 
                   8493:         !defined($middle) || $middle eq '' || 
                   8494:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8495:         # They did not supply us with enough data to enroll the student, so
                   8496:         # we need to pick up more information.
1.297     matthew  8497:         my %tmp = &get('environment',
1.294     matthew  8498:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8499:                        ,$udom,$uname);
                   8500: 
1.800     albertel 8501:         #foreach my $key (keys(%tmp)) {
                   8502:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8503:         #}
1.294     matthew  8504:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8505:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8506:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8507:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8508:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8509:     }
1.556     albertel 8510:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8511:     my $user = "$uname:$udom";
                   8512:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8513:     my $reply=cput('classlist',
1.1148    raeburn  8514: 		   {$user => 
1.1216    raeburn  8515: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8516: 		   $cdom,$cnum);
1.1148    raeburn  8517:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8518:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8519:     } else { 
1.81      www      8520: 	return 'error: '.$reply;
                   8521:     }
1.297     matthew  8522:     # Add student role to user
1.83      www      8523:     my $uurl='/'.$cid;
1.81      www      8524:     $uurl=~s/\_/\//g;
                   8525:     if ($usec) {
                   8526: 	$uurl.='/'.$usec;
                   8527:     }
1.1148    raeburn  8528:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8529:                              $selfenroll,$context);
                   8530:     if ($result ne 'ok') {
                   8531:         if ($old_entry{$user} ne '') {
                   8532:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8533:         } else {
                   8534:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8535:         }
                   8536:     }
                   8537:     return $result; 
1.21      www      8538: }
                   8539: 
1.556     albertel 8540: sub format_name {
                   8541:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8542:     my $name;
                   8543:     if ($first ne 'lastname') {
                   8544: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8545:     } else {
                   8546: 	if ($lastname=~/\S/) {
                   8547: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8548: 	    $name=~s/\s+,/,/;
                   8549: 	} else {
                   8550: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8551: 	}
                   8552:     }
                   8553:     $name=~s/^\s+//;
                   8554:     $name=~s/\s+$//;
                   8555:     $name=~s/\s+/ /g;
                   8556:     return $name;
                   8557: }
                   8558: 
1.84      www      8559: # ------------------------------------------------- Write to course preferences
                   8560: 
                   8561: sub writecoursepref {
                   8562:     my ($courseid,%prefs)=@_;
                   8563:     $courseid=~s/^\///;
                   8564:     $courseid=~s/\_/\//g;
                   8565:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8566:     my $chome=homeserver($cnum,$cdomain);
                   8567:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8568: 	return 'error: no such course';
                   8569:     }
                   8570:     my $cstring='';
1.800     albertel 8571:     foreach my $pref (keys(%prefs)) {
                   8572: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8573:     }
1.84      www      8574:     $cstring=~s/\&$//;
                   8575:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8576: }
                   8577: 
                   8578: # ---------------------------------------------------------- Make/modify course
                   8579: 
                   8580: sub createcourse {
1.741     raeburn  8581:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8582:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8583:     $url=&declutter($url);
                   8584:     my $cid='';
1.1028    raeburn  8585:     if ($context eq 'requestcourses') {
                   8586:         my $can_create = 0;
                   8587:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8588:         if ($udom eq $ownerdom) {
                   8589:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8590:                                   $context)) {
                   8591:                 $can_create = 1;
                   8592:             }
                   8593:         } else {
                   8594:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8595:                                            $category);
                   8596:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8597:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8598:                 if (@curr > 0) {
                   8599:                     my @options = qw(approval validate autolimit);
                   8600:                     my $optregex = join('|',@options);
                   8601:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8602:                         $can_create = 1;
                   8603:                     }
                   8604:                 }
                   8605:             }
                   8606:         }
                   8607:         if ($can_create) {
                   8608:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8609:                 unless (&allowed('ccc',$udom)) {
                   8610:                     return 'refused'; 
                   8611:                 }
1.1017    raeburn  8612:             }
                   8613:         } else {
                   8614:             return 'refused';
                   8615:         }
1.1028    raeburn  8616:     } elsif (!&allowed('ccc',$udom)) {
                   8617:         return 'refused';
1.84      www      8618:     }
1.1011    raeburn  8619: # --------------------------------------------------------------- Get Unique ID
                   8620:     my $uname;
                   8621:     if ($cnum =~ /^$match_courseid$/) {
                   8622:         my $chome=&homeserver($cnum,$udom,'true');
                   8623:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8624:             $uname = $cnum;
                   8625:         } else {
1.1038    raeburn  8626:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8627:         }
                   8628:     } else {
1.1038    raeburn  8629:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8630:     }
                   8631:     return $uname if ($uname =~ /^error/);
                   8632: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8633:     if (!defined($course_server)) {
                   8634:         if (defined(&domain($udom,'primary'))) {
                   8635:             $course_server = &domain($udom,'primary');
                   8636:         } else {
                   8637:             $course_server = $env{'user.home'}; 
                   8638:         }
                   8639:     }
                   8640:     my %host_servers =
                   8641:         &Apache::lonnet::get_servers($udom,'library');
                   8642:     unless ($host_servers{$course_server}) {
                   8643:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8644:     }
1.84      www      8645: # ------------------------------------------------------------- Make the course
                   8646:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8647:                       $course_server);
1.84      www      8648:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8649:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8650:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8651: 	return 'error: no such course';
                   8652:     }
1.271     www      8653: # ----------------------------------------------------------------- Course made
1.516     raeburn  8654: # log existence
1.1029    raeburn  8655:     my $now = time;
1.918     raeburn  8656:     my $newcourse = {
                   8657:                     $udom.'_'.$uname => {
1.921     raeburn  8658:                                      description => $description,
                   8659:                                      inst_code   => $inst_code,
                   8660:                                      owner       => $course_owner,
                   8661:                                      type        => $crstype,
1.1029    raeburn  8662:                                      creator     => $env{'user.name'}.':'.
                   8663:                                                     $env{'user.domain'},
                   8664:                                      created     => $now,
                   8665:                                      context     => $context,
1.918     raeburn  8666:                                                 },
                   8667:                     };
1.921     raeburn  8668:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8669: # set toplevel url
1.271     www      8670:     my $topurl=$url;
                   8671:     unless ($nonstandard) {
                   8672: # ------------------------------------------ For standard courses, make top url
                   8673:         my $mapurl=&clutter($url);
1.278     www      8674:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8675:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8676: <map>
                   8677: <resource id="1" type="start"></resource>
                   8678: <resource id="2" src="$mapurl"></resource>
                   8679: <resource id="3" type="finish"></resource>
                   8680: <link index="1" from="1" to="2"></link>
                   8681: <link index="2" from="2" to="3"></link>
                   8682: </map>
                   8683: ENDINITMAP
                   8684:         $topurl=&declutter(
1.638     albertel 8685:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8686:                           );
                   8687:     }
                   8688: # ----------------------------------------------------------- Write preferences
1.84      www      8689:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8690:                      ('description'              => $description,
                   8691:                       'url'                      => $topurl,
                   8692:                       'internal.creator'         => $env{'user.name'}.':'.
                   8693:                                                     $env{'user.domain'},
                   8694:                       'internal.created'         => $now,
                   8695:                       'internal.creationcontext' => $context)
                   8696:                     );
1.84      www      8697:     return '/'.$udom.'/'.$uname;
                   8698: }
                   8699: 
1.1011    raeburn  8700: # ------------------------------------------------------------------- Create ID
                   8701: sub generate_coursenum {
1.1038    raeburn  8702:     my ($udom,$crstype) = @_;
1.1011    raeburn  8703:     my $domdesc = &domain($udom);
                   8704:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8705:     my $first;
                   8706:     if ($crstype eq 'Community') {
                   8707:         $first = '0';
                   8708:     } else {
                   8709:         $first = int(1+rand(9)); 
                   8710:     } 
                   8711:     my $uname=$first.
1.1011    raeburn  8712:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8713:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8714:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8715: # ----------------------------------------------- Make sure that does not exist
                   8716:     my $uhome=&homeserver($uname,$udom,'true');
                   8717:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8718:         if ($crstype eq 'Community') {
                   8719:             $first = '0';
                   8720:         } else {
                   8721:             $first = int(1+rand(9));
                   8722:         }
                   8723:         $uname=$first.
1.1011    raeburn  8724:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8725:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8726:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8727:         $uhome=&homeserver($uname,$udom,'true');
                   8728:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8729:             return 'error: unable to generate unique course-ID';
                   8730:         }
                   8731:     }
                   8732:     return $uname;
                   8733: }
                   8734: 
1.813     albertel 8735: sub is_course {
1.1167    droeschl 8736:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8737:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8738: 
                   8739:     return unless $cdom and $cnum;
                   8740: 
                   8741:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8742:         '.');
                   8743: 
1.1219    raeburn  8744:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8745:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8746: }
                   8747: 
1.1015    raeburn  8748: sub store_userdata {
                   8749:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8750:     my $result;
1.1016    raeburn  8751:     if ($datakey ne '') {
1.1013    raeburn  8752:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8753:             if ($udom eq '' || $uname eq '') {
                   8754:                 $udom = $env{'user.domain'};
                   8755:                 $uname = $env{'user.name'};
                   8756:             }
                   8757:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8758:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8759:                 $result = 'error: no_host';
                   8760:             } else {
                   8761:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8762:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8763: 
                   8764:                 my $namevalue='';
                   8765:                 foreach my $key (keys(%{$storehash})) {
                   8766:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8767:                 }
                   8768:                 $namevalue=~s/\&$//;
1.1105    raeburn  8769:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8770:                                   $namevalue,$uhome);
1.1013    raeburn  8771:             }
                   8772:         } else {
                   8773:             $result = 'error: data to store was not a hash reference'; 
                   8774:         }
                   8775:     } else {
                   8776:         $result= 'error: invalid requestkey'; 
                   8777:     }
                   8778:     return $result;
                   8779: }
                   8780: 
1.21      www      8781: # ---------------------------------------------------------- Assign Custom Role
                   8782: 
                   8783: sub assigncustomrole {
1.957     raeburn  8784:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8785:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8786:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8787: }
                   8788: 
                   8789: # ----------------------------------------------------------------- Revoke Role
                   8790: 
                   8791: sub revokerole {
1.957     raeburn  8792:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8793:     my $now=time;
1.965     raeburn  8794:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8795: }
                   8796: 
                   8797: # ---------------------------------------------------------- Revoke Custom Role
                   8798: 
                   8799: sub revokecustomrole {
1.957     raeburn  8800:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8801:     my $now=time;
1.357     www      8802:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8803:            $deleteflag,$selfenroll,$context);
1.17      www      8804: }
                   8805: 
1.533     banghart 8806: # ------------------------------------------------------------ Disk usage
1.535     albertel 8807: sub diskusage {
1.955     raeburn  8808:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8809:     $directorypath =~ s/\/$//;
                   8810:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8811:                        .&escape($getpropath).':'.&escape($uname).':'
                   8812:                        .&escape($udom),homeserver($uname,$udom));
                   8813:     if ($listing eq 'unknown_cmd') {
                   8814:         if ($getpropath) {
                   8815:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8816:         }
                   8817:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8818:     }
1.514     albertel 8819:     return $listing;
1.512     banghart 8820: }
                   8821: 
1.566     banghart 8822: sub is_locked {
1.1096    raeburn  8823:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8824:     my @check;
                   8825:     my $is_locked;
1.1093    raeburn  8826:     push (@check,$file_name);
1.613     albertel 8827:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8828: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8829:     my ($tmp)=keys(%locked);
                   8830:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8831:     
1.566     banghart 8832:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8833:         $is_locked = 'false';
                   8834:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8835:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8836:                $is_locked = 'true';
1.1096    raeburn  8837:                if (ref($which) eq 'ARRAY') {
                   8838:                    push(@{$which},$entry);
                   8839:                } else {
                   8840:                    last;
                   8841:                }
1.745     raeburn  8842:            }
                   8843:        }
1.566     banghart 8844:     } else {
                   8845:         $is_locked = 'false';
                   8846:     }
1.1093    raeburn  8847:     return $is_locked;
1.566     banghart 8848: }
                   8849: 
1.759     albertel 8850: sub declutter_portfile {
                   8851:     my ($file) = @_;
1.833     albertel 8852:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8853:     return $file;
                   8854: }
                   8855: 
1.559     banghart 8856: # ------------------------------------------------------------- Mark as Read Only
                   8857: 
                   8858: sub mark_as_readonly {
                   8859:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8860:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8861:     my ($tmp)=keys(%current_permissions);
                   8862:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8863:     foreach my $file (@{$files}) {
1.759     albertel 8864: 	$file = &declutter_portfile($file);
1.561     banghart 8865:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8866:     }
1.613     albertel 8867:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8868:     return;
                   8869: }
                   8870: 
1.572     banghart 8871: # ------------------------------------------------------------Save Selected Files
                   8872: 
                   8873: sub save_selected_files {
                   8874:     my ($user, $path, @files) = @_;
                   8875:     my $filename = $user."savedfiles";
1.573     banghart 8876:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8877:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8878:     foreach my $file (@files) {
1.620     albertel 8879:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8880:     }
                   8881:     foreach my $file (@other_files) {
1.574     banghart 8882:         print (OUT $file."\n");
1.572     banghart 8883:     }
1.574     banghart 8884:     close (OUT);
1.572     banghart 8885:     return 'ok';
                   8886: }
                   8887: 
1.574     banghart 8888: sub clear_selected_files {
                   8889:     my ($user) = @_;
                   8890:     my $filename = $user."savedfiles";
1.1117    foxr     8891:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8892:     print (OUT undef);
                   8893:     close (OUT);
                   8894:     return ("ok");    
                   8895: }
                   8896: 
1.572     banghart 8897: sub files_in_path {
                   8898:     my ($user, $path) = @_;
                   8899:     my $filename = $user."savedfiles";
                   8900:     my %return_files;
1.1117    foxr     8901:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8902:     while (my $line_in = <IN>) {
1.574     banghart 8903:         chomp ($line_in);
                   8904:         my @paths_and_file = split (m!/!, $line_in);
                   8905:         my $file_part = pop (@paths_and_file);
                   8906:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8907:         $path_part.='/';
                   8908:         my $path_and_file = $path_part.$file_part;
                   8909:         if ($path_part eq $path) {
                   8910:             $return_files{$file_part}= 'selected';
                   8911:         }
                   8912:     }
1.574     banghart 8913:     close (IN);
                   8914:     return (\%return_files);
1.572     banghart 8915: }
                   8916: 
                   8917: # called in portfolio select mode, to show files selected NOT in current directory
                   8918: sub files_not_in_path {
                   8919:     my ($user, $path) = @_;
                   8920:     my $filename = $user."savedfiles";
                   8921:     my @return_files;
                   8922:     my $path_part;
1.1117    foxr     8923:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8924:     while (my $line = <IN>) {
1.572     banghart 8925:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8926:         my @paths_and_file = split(m|/|, $line);
                   8927:         my $file_part = pop(@paths_and_file);
                   8928:         chomp($file_part);
                   8929:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8930:         $path_part .= '/';
                   8931:         my $path_and_file = $path_part.$file_part;
                   8932:         if ($path_part ne $path) {
1.800     albertel 8933:             push(@return_files, ($path_and_file));
1.572     banghart 8934:         }
                   8935:     }
1.800     albertel 8936:     close(OUT);
1.574     banghart 8937:     return (@return_files);
1.572     banghart 8938: }
                   8939: 
1.745     raeburn  8940: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8941: 
1.745     raeburn  8942: sub get_portfile_permissions {
                   8943:     my ($domain,$user) = @_;
1.613     albertel 8944:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8945:     my ($tmp)=keys(%current_permissions);
                   8946:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8947:     return \%current_permissions;
                   8948: }
                   8949: 
                   8950: #---------------------------------------------Get portfolio file access controls
                   8951: 
1.749     raeburn  8952: sub get_access_controls {
1.745     raeburn  8953:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8954:     my %access;
                   8955:     my $real_file = $file;
                   8956:     $file =~ s/\.meta$//;
1.745     raeburn  8957:     if (defined($file)) {
1.749     raeburn  8958:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8959:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8960:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8961:             }
                   8962:         }
1.745     raeburn  8963:     } else {
1.749     raeburn  8964:         foreach my $key (keys(%{$current_permissions})) {
                   8965:             if ($key =~ /\0accesscontrol$/) {
                   8966:                 if (defined($group)) {
                   8967:                     if ($key !~ m-^\Q$group\E/-) {
                   8968:                         next;
                   8969:                     }
                   8970:                 }
                   8971:                 my ($fullpath) = split(/\0/,$key);
                   8972:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8973:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8974:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8975:                     }
                   8976:                 }
                   8977:             }
                   8978:         }
                   8979:     }
                   8980:     return %access;
                   8981: }
                   8982: 
                   8983: sub modify_access_controls {
                   8984:     my ($file_name,$changes,$domain,$user)=@_;
                   8985:     my ($outcome,$deloutcome);
                   8986:     my %store_permissions;
                   8987:     my %new_values;
                   8988:     my %new_control;
                   8989:     my %translation;
                   8990:     my @deletions = ();
                   8991:     my $now = time;
                   8992:     if (exists($$changes{'activate'})) {
                   8993:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8994:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8995:             my $numnew = scalar(@newitems);
                   8996:             for (my $i=0; $i<$numnew; $i++) {
                   8997:                 my $newkey = $newitems[$i];
                   8998:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8999:                 if ($newkey =~ /^\d+:/) { 
                   9000:                     $newkey =~ s/^(\d+)/$newid/;
                   9001:                     $translation{$1} = $newid;
                   9002:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9003:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9004:                     $translation{$1} = $newid;
                   9005:                 }
1.749     raeburn  9006:                 $new_values{$file_name."\0".$newkey} = 
                   9007:                                           $$changes{'activate'}{$newitems[$i]};
                   9008:                 $new_control{$newkey} = $now;
                   9009:             }
                   9010:         }
                   9011:     }
                   9012:     my %todelete;
                   9013:     my %changed_items;
                   9014:     foreach my $action ('delete','update') {
                   9015:         if (exists($$changes{$action})) {
                   9016:             if (ref($$changes{$action}) eq 'HASH') {
                   9017:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9018:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9019:                     if ($action eq 'delete') { 
                   9020:                         $todelete{$itemnum} = 1;
                   9021:                     } else {
                   9022:                         $changed_items{$itemnum} = $key;
                   9023:                     }
                   9024:                 }
1.745     raeburn  9025:             }
                   9026:         }
1.749     raeburn  9027:     }
                   9028:     # get lock on access controls for file.
                   9029:     my $lockhash = {
                   9030:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9031:                                                        ':'.$env{'user.domain'},
                   9032:                    }; 
                   9033:     my $tries = 0;
                   9034:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9035:    
                   9036:     while (($gotlock ne 'ok') && $tries <3) {
                   9037:         $tries ++;
                   9038:         sleep 1;
                   9039:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9040:     }
                   9041:     if ($gotlock eq 'ok') {
                   9042:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9043:         my ($tmp)=keys(%curr_permissions);
                   9044:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9045:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9046:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9047:             if (ref($curr_controls) eq 'HASH') {
                   9048:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9049:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9050:                     if (defined($todelete{$itemnum})) {
                   9051:                         push(@deletions,$file_name."\0".$control_item);
                   9052:                     } else {
                   9053:                         if (defined($changed_items{$itemnum})) {
                   9054:                             $new_control{$changed_items{$itemnum}} = $now;
                   9055:                             push(@deletions,$file_name."\0".$control_item);
                   9056:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9057:                         } else {
                   9058:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9059:                         }
                   9060:                     }
1.745     raeburn  9061:                 }
                   9062:             }
                   9063:         }
1.970     raeburn  9064:         my ($group);
                   9065:         if (&is_course($domain,$user)) {
                   9066:             ($group,my $file) = split(/\//,$file_name,2);
                   9067:         }
1.749     raeburn  9068:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9069:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9070:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9071:         #  remove lock
                   9072:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9073:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9074:         my $sqlresult =
1.970     raeburn  9075:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9076:                                     $group);
1.749     raeburn  9077:     } else {
                   9078:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9079:     }
1.749     raeburn  9080:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9081: }
                   9082: 
1.827     raeburn  9083: sub make_public_indefinitely {
                   9084:     my ($requrl) = @_;
                   9085:     my $now = time;
                   9086:     my $action = 'activate';
                   9087:     my $aclnum = 0;
                   9088:     if (&is_portfolio_url($requrl)) {
                   9089:         my (undef,$udom,$unum,$file_name,$group) =
                   9090:             &parse_portfolio_url($requrl);
                   9091:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9092:         my %access_controls = &get_access_controls($current_perms,
                   9093:                                                    $group,$file_name);
                   9094:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9095:             my ($num,$scope,$end,$start) = 
                   9096:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9097:             if ($scope eq 'public') {
                   9098:                 if ($start <= $now && $end == 0) {
                   9099:                     $action = 'none';
                   9100:                 } else {
                   9101:                     $action = 'update';
                   9102:                     $aclnum = $num;
                   9103:                 }
                   9104:                 last;
                   9105:             }
                   9106:         }
                   9107:         if ($action eq 'none') {
                   9108:              return 'ok';
                   9109:         } else {
                   9110:             my %changes;
                   9111:             my $newend = 0;
                   9112:             my $newstart = $now;
                   9113:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9114:             $changes{$action}{$newkey} = {
                   9115:                 type => 'public',
                   9116:                 time => {
                   9117:                     start => $newstart,
                   9118:                     end   => $newend,
                   9119:                 },
                   9120:             };
                   9121:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9122:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9123:             return $outcome;
                   9124:         }
                   9125:     } else {
                   9126:         return 'invalid';
                   9127:     }
                   9128: }
                   9129: 
1.745     raeburn  9130: #------------------------------------------------------Get Marked as Read Only
                   9131: 
                   9132: sub get_marked_as_readonly {
                   9133:     my ($domain,$user,$what,$group) = @_;
                   9134:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9135:     my @readonly_files;
1.629     banghart 9136:     my $cmp1=$what;
                   9137:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9138:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9139:         if (defined($group)) {
                   9140:             if ($file_name !~ m-^\Q$group\E/-) {
                   9141:                 next;
                   9142:             }
                   9143:         }
1.561     banghart 9144:         if (ref($value) eq "ARRAY"){
                   9145:             foreach my $stored_what (@{$value}) {
1.629     banghart 9146:                 my $cmp2=$stored_what;
1.759     albertel 9147:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9148:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9149:                 }
1.629     banghart 9150:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9151:                     push(@readonly_files, $file_name);
1.745     raeburn  9152:                     last;
1.563     banghart 9153:                 } elsif (!defined($what)) {
                   9154:                     push(@readonly_files, $file_name);
1.745     raeburn  9155:                     last;
1.561     banghart 9156:                 }
                   9157:             }
1.745     raeburn  9158:         }
1.561     banghart 9159:     }
                   9160:     return @readonly_files;
                   9161: }
1.577     banghart 9162: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9163: 
1.577     banghart 9164: sub get_marked_as_readonly_hash {
1.745     raeburn  9165:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9166:     my %readonly_files;
1.745     raeburn  9167:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9168:         if (defined($group)) {
                   9169:             if ($file_name !~ m-^\Q$group\E/-) {
                   9170:                 next;
                   9171:             }
                   9172:         }
1.577     banghart 9173:         if (ref($value) eq "ARRAY"){
                   9174:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9175:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9176:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9177:                         if ($lock_descriptor eq 'graded') {
                   9178:                             $readonly_files{$file_name} = 'graded';
                   9179:                         } elsif ($lock_descriptor eq 'handback') {
                   9180:                             $readonly_files{$file_name} = 'handback';
                   9181:                         } else {
                   9182:                             if (!exists($readonly_files{$file_name})) {
                   9183:                                 $readonly_files{$file_name} = 'locked';
                   9184:                             }
                   9185:                         }
1.745     raeburn  9186:                     }
1.750     banghart 9187:                 } 
1.577     banghart 9188:             }
                   9189:         } 
                   9190:     }
                   9191:     return %readonly_files;
                   9192: }
1.559     banghart 9193: # ------------------------------------------------------------ Unmark as Read Only
                   9194: 
                   9195: sub unmark_as_readonly {
1.629     banghart 9196:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9197:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9198:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9199:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9200:     my $symb_crs = $what;
                   9201:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9202:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9203:     my ($tmp)=keys(%current_permissions);
                   9204:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9205:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9206:     foreach my $file (@readonly_files) {
1.759     albertel 9207: 	my $clean_file = &declutter_portfile($file);
                   9208: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9209: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9210:         my @new_locks;
                   9211:         my @del_keys;
                   9212:         if (ref($current_locks) eq "ARRAY"){
                   9213:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9214:                 my $compare=$locker;
1.749     raeburn  9215:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9216:                     $compare=join('',@{$locker});
1.746     raeburn  9217:                     if ($compare ne $symb_crs) {
                   9218:                         push(@new_locks, $locker);
                   9219:                     }
1.563     banghart 9220:                 }
                   9221:             }
1.650     albertel 9222:             if (scalar(@new_locks) > 0) {
1.563     banghart 9223:                 $current_permissions{$file} = \@new_locks;
                   9224:             } else {
                   9225:                 push(@del_keys, $file);
1.613     albertel 9226:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9227:                 delete($current_permissions{$file});
1.563     banghart 9228:             }
                   9229:         }
1.561     banghart 9230:     }
1.613     albertel 9231:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9232:     return;
                   9233: }
1.512     banghart 9234: 
1.17      www      9235: # ------------------------------------------------------------ Directory lister
                   9236: 
                   9237: sub dirlist {
1.955     raeburn  9238:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9239:     $uri=~s/^\///;
                   9240:     $uri=~s/\/$//;
1.253     stredwic 9241:     my ($udom, $uname);
1.955     raeburn  9242:     if ($getuserdir) {
1.253     stredwic 9243:         $udom = $userdomain;
                   9244:         $uname = $username;
1.955     raeburn  9245:     } else {
                   9246:         (undef,$udom,$uname)=split(/\//,$uri);
                   9247:         if(defined($userdomain)) {
                   9248:             $udom = $userdomain;
                   9249:         }
                   9250:         if(defined($username)) {
                   9251:             $uname = $username;
                   9252:         }
1.253     stredwic 9253:     }
1.955     raeburn  9254:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9255: 
1.955     raeburn  9256:     $dirRoot = $perlvar{'lonDocRoot'};
                   9257:     if (defined($getpropath)) {
                   9258:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9259:         $dirRoot =~ s/\/$//;
1.955     raeburn  9260:     } elsif (defined($getuserdir)) {
                   9261:         my $subdir=$uname.'__';
                   9262:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9263:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9264:                    ."/$udom/$subdir/$uname";
                   9265:     } elsif (defined($alternateRoot)) {
                   9266:         $dirRoot = $alternateRoot;
1.751     banghart 9267:     }
1.253     stredwic 9268: 
                   9269:     if($udom) {
                   9270:         if($uname) {
1.1135    raeburn  9271:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9272:             if ($uhome eq 'no_host') {
                   9273:                 return ([],'no_host');
                   9274:             }
1.955     raeburn  9275:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9276:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9277:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9278:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9279:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9280:             } else {
                   9281:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9282:             }
1.605     matthew  9283:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9284:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9285:                 @listing_results = split(/:/,$listing);
                   9286:             } else {
                   9287:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9288:             }
1.1135    raeburn  9289:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9290:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9291:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9292:                 return ([],$listing);
                   9293:             } else {
                   9294:                 return (\@listing_results);
1.1135    raeburn  9295:             }
1.955     raeburn  9296:         } elsif(!$alternateRoot) {
1.1136    raeburn  9297:             my (%allusers,%listerror);
1.841     albertel 9298: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9299:  	    foreach my $tryserver (keys(%servers)) {
                   9300:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9301:                                   &escape($udom),$tryserver);
                   9302:                 if ($listing eq 'unknown_cmd') {
                   9303: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9304: 				      $udom, $tryserver);
                   9305:                 } else {
                   9306:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9307:                 }
1.841     albertel 9308: 		if ($listing eq 'unknown_cmd') {
                   9309: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9310: 				      $udom, $tryserver);
                   9311: 		    @listing_results = split(/:/,$listing);
                   9312: 		} else {
                   9313: 		    @listing_results =
                   9314: 			map { &unescape($_); } split(/:/,$listing);
                   9315: 		}
1.1136    raeburn  9316:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9317:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9318:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9319:                     $listerror{$tryserver} = $listing;
                   9320:                 } else {
1.841     albertel 9321: 		    foreach my $line (@listing_results) {
                   9322: 			my ($entry) = split(/&/,$line,2);
                   9323: 			$allusers{$entry} = 1;
                   9324: 		    }
                   9325: 		}
1.253     stredwic 9326:             }
1.1136    raeburn  9327:             my @alluserslist=();
1.800     albertel 9328:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9329:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9330:             }
1.1136    raeburn  9331:             return (\@alluserslist);
1.253     stredwic 9332:         } else {
1.1136    raeburn  9333:             return ([],'missing username');
1.253     stredwic 9334:         }
1.955     raeburn  9335:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9336:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9337:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9338:         return (\@all_domains);
1.955     raeburn  9339:     } else {
1.1136    raeburn  9340:         return ([],'missing domain');
1.275     stredwic 9341:     }
                   9342: }
                   9343: 
                   9344: # --------------------------------------------- GetFileTimestamp
                   9345: # This function utilizes dirlist and returns the date stamp for
                   9346: # when it was last modified.  It will also return an error of -1
                   9347: # if an error occurs
                   9348: 
                   9349: sub GetFileTimestamp {
1.955     raeburn  9350:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9351:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9352:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9353:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9354:                                     undef,$getuserdir);
                   9355:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9356:         return -1;
                   9357:     }
                   9358:     if (ref($fileref) eq 'ARRAY') {
                   9359:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9360:         # @stats contains first the filename, then the stat output
                   9361:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9362:     } else {
                   9363:         return -1;
1.253     stredwic 9364:     }
1.26      www      9365: }
                   9366: 
1.712     albertel 9367: sub stat_file {
                   9368:     my ($uri) = @_;
1.787     albertel 9369:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9370: 
1.955     raeburn  9371:     my ($udom,$uname,$file);
1.712     albertel 9372:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9373: 	($udom,$uname,$file) =
1.811     albertel 9374: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9375: 	$file = 'userfiles/'.$file;
                   9376:     }
                   9377:     if ($uri =~ m-^/res/-) {
                   9378: 	($udom,$uname) = 
1.807     albertel 9379: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9380: 	$file = $uri;
                   9381:     }
                   9382: 
                   9383:     if (!$udom || !$uname || !$file) {
                   9384: 	# unable to handle the uri
                   9385: 	return ();
                   9386:     }
1.956     raeburn  9387:     my $getpropath;
                   9388:     if ($file =~ /^userfiles\//) {
                   9389:         $getpropath = 1;
                   9390:     }
1.1136    raeburn  9391:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9392:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9393:         return ();
                   9394:     } else {
                   9395:         if (ref($listref) eq 'ARRAY') {
                   9396:             my @stats = split('&',$listref->[0]);
                   9397: 	    shift(@stats); #filename is first
                   9398: 	    return @stats;
                   9399:         }
1.712     albertel 9400:     }
                   9401:     return ();
                   9402: }
                   9403: 
1.26      www      9404: # -------------------------------------------------------- Value of a Condition
                   9405: 
1.713     albertel 9406: # gets the value of a specific preevaluated condition
                   9407: #    stored in the string  $env{user.state.<cid>}
                   9408: # or looks up a condition reference in the bighash and if if hasn't
                   9409: # already been evaluated recurses into docondval to get the value of
                   9410: # the condition, then memoizing it to 
                   9411: #   $env{user.state.<cid>.<condition>}
1.40      www      9412: sub directcondval {
                   9413:     my $number=shift;
1.620     albertel 9414:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9415: 	&Apache::lonuserstate::evalstate();
                   9416:     }
1.713     albertel 9417:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9418: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9419:     } elsif ($number =~ /^_/) {
                   9420: 	my $sub_condition;
                   9421: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9422: 		&GDBM_READER(),0640)) {
                   9423: 	    $sub_condition=$bighash{'conditions'.$number};
                   9424: 	    untie(%bighash);
                   9425: 	}
                   9426: 	my $value = &docondval($sub_condition);
1.949     raeburn  9427: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9428: 	return $value;
                   9429:     }
1.620     albertel 9430:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9431:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9432:     } else {
                   9433:        return 2;
                   9434:     }
                   9435: }
                   9436: 
1.713     albertel 9437: # get the collection of conditions for this resource
1.26      www      9438: sub condval {
                   9439:     my $condidx=shift;
1.54      www      9440:     my $allpathcond='';
1.713     albertel 9441:     foreach my $cond (split(/\|/,$condidx)) {
                   9442: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9443: 	    $allpathcond.=
                   9444: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9445: 	}
1.191     harris41 9446:     }
1.54      www      9447:     $allpathcond=~s/\|$//;
1.713     albertel 9448:     return &docondval($allpathcond);
                   9449: }
                   9450: 
                   9451: #evaluates an expression of conditions
                   9452: sub docondval {
                   9453:     my ($allpathcond) = @_;
                   9454:     my $result=0;
                   9455:     if ($env{'request.course.id'}
                   9456: 	&& defined($allpathcond)) {
                   9457: 	my $operand='|';
                   9458: 	my @stack;
                   9459: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9460: 	    if ($chunk eq '(') {
                   9461: 		push @stack,($operand,$result);
                   9462: 	    } elsif ($chunk eq ')') {
                   9463: 		my $before=pop @stack;
                   9464: 		if (pop @stack eq '&') {
                   9465: 		    $result=$result>$before?$before:$result;
                   9466: 		} else {
                   9467: 		    $result=$result>$before?$result:$before;
                   9468: 		}
                   9469: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9470: 		$operand=$chunk;
                   9471: 	    } else {
                   9472: 		my $new=directcondval($chunk);
                   9473: 		if ($operand eq '&') {
                   9474: 		    $result=$result>$new?$new:$result;
                   9475: 		} else {
                   9476: 		    $result=$result>$new?$result:$new;
                   9477: 		}
                   9478: 	    }
                   9479: 	}
1.26      www      9480:     }
                   9481:     return $result;
1.421     albertel 9482: }
                   9483: 
                   9484: # ---------------------------------------------------- Devalidate courseresdata
                   9485: 
                   9486: sub devalidatecourseresdata {
                   9487:     my ($coursenum,$coursedomain)=@_;
                   9488:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9489:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9490: }
                   9491: 
1.763     www      9492: 
1.200     www      9493: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9494: #
                   9495: #  Parameters:
                   9496: #      $coursenum    - Number of the course.
                   9497: #      $coursedomain - Domain at which the course was created.
                   9498: #  Returns:
                   9499: #     A hash of the course parameters along (I think) with timestamps
                   9500: #     and version info.
1.877     foxr     9501: 
1.624     albertel 9502: sub get_courseresdata {
                   9503:     my ($coursenum,$coursedomain)=@_;
1.200     www      9504:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9505:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9506:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9507:     my %dumpreply;
1.417     albertel 9508:     unless (defined($cached)) {
1.624     albertel 9509: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9510: 	$result=\%dumpreply;
1.251     albertel 9511: 	my ($tmp) = keys(%dumpreply);
                   9512: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9513: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9514: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9515: 	    return $tmp;
1.416     albertel 9516: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9517: 	    $result=undef;
1.599     albertel 9518: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9519: 	}
                   9520:     }
1.624     albertel 9521:     return $result;
                   9522: }
                   9523: 
1.633     albertel 9524: sub devalidateuserresdata {
                   9525:     my ($uname,$udom)=@_;
                   9526:     my $hashid="$udom:$uname";
                   9527:     &devalidate_cache_new('userres',$hashid);
                   9528: }
                   9529: 
1.624     albertel 9530: sub get_userresdata {
                   9531:     my ($uname,$udom)=@_;
                   9532:     #most student don\'t have any data set, check if there is some data
                   9533:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9534: 
                   9535:     my $hashid="$udom:$uname";
                   9536:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9537:     if (!defined($cached)) {
                   9538: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9539: 	$result=\%resourcedata;
                   9540: 	&do_cache_new('userres',$hashid,$result,600);
                   9541:     }
                   9542:     my ($tmp)=keys(%$result);
                   9543:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9544: 	return $result;
                   9545:     }
                   9546:     #error 2 occurs when the .db doesn't exist
                   9547:     if ($tmp!~/error: 2 /) {
1.672     albertel 9548: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9549: 		 " Trying to get resource data for ".
                   9550: 		 $uname." at ".$udom.": ".
                   9551: 		 $tmp."</font>");
                   9552:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9553: 	#&EXT_cache_set($udom,$uname);
                   9554: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9555: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9556:     }
                   9557:     return $tmp;
                   9558: }
1.879     foxr     9559: #----------------------------------------------- resdata - return resource data
                   9560: #  Purpose:
                   9561: #    Return resource data for either users or for a course.
                   9562: #  Parameters:
                   9563: #     $name      - Course/user name.
                   9564: #     $domain    - Name of the domain the user/course is registered on.
                   9565: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9566: #     @which     - Array of names of resources desired.
                   9567: #  Returns:
                   9568: #     The value of the first reasource in @which that is found in the
                   9569: #     resource hash.
                   9570: #  Exceptional Conditions:
                   9571: #     If the $type passed in is not valid (not the string 'course' or 
                   9572: #     'user', an undefined  reference is returned.
                   9573: #     If none of the resources are found, an undef is returned
1.624     albertel 9574: sub resdata {
                   9575:     my ($name,$domain,$type,@which)=@_;
                   9576:     my $result;
                   9577:     if ($type eq 'course') {
                   9578: 	$result=&get_courseresdata($name,$domain);
                   9579:     } elsif ($type eq 'user') {
                   9580: 	$result=&get_userresdata($name,$domain);
                   9581:     }
                   9582:     if (!ref($result)) { return $result; }    
1.251     albertel 9583:     foreach my $item (@which) {
1.927     albertel 9584: 	if (defined($result->{$item->[0]})) {
                   9585: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9586: 	}
1.250     albertel 9587:     }
1.291     albertel 9588:     return undef;
1.200     www      9589: }
                   9590: 
1.379     matthew  9591: #
                   9592: # EXT resource caching routines
                   9593: #
                   9594: 
                   9595: sub clear_EXT_cache_status {
1.383     albertel 9596:     &delenv('cache.EXT.');
1.379     matthew  9597: }
                   9598: 
                   9599: sub EXT_cache_status {
                   9600:     my ($target_domain,$target_user) = @_;
1.383     albertel 9601:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9602:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9603:         # We know already the user has no data
                   9604:         return 1;
                   9605:     } else {
                   9606:         return 0;
                   9607:     }
                   9608: }
                   9609: 
                   9610: sub EXT_cache_set {
                   9611:     my ($target_domain,$target_user) = @_;
1.383     albertel 9612:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9613:     #&appenv({$cachename => time});
1.379     matthew  9614: }
                   9615: 
1.28      www      9616: # --------------------------------------------------------- Value of a Variable
1.58      www      9617: sub EXT {
1.715     albertel 9618: 
1.395     albertel 9619:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9620:     unless ($varname) { return ''; }
1.218     albertel 9621:     #get real user name/domain, courseid and symb
                   9622:     my $courseid;
1.359     albertel 9623:     my $publicuser;
1.427     www      9624:     if ($symbparm) {
                   9625: 	$symbparm=&get_symb_from_alias($symbparm);
                   9626:     }
1.218     albertel 9627:     if (!($uname && $udom)) {
1.790     albertel 9628:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9629:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9630:     } else {
1.620     albertel 9631: 	$courseid=$env{'request.course.id'};
1.218     albertel 9632:     }
1.48      www      9633:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9634:     my $rest;
1.320     albertel 9635:     if (defined($therest[0])) {
1.48      www      9636:        $rest=join('.',@therest);
                   9637:     } else {
                   9638:        $rest='';
                   9639:     }
1.320     albertel 9640: 
1.57      www      9641:     my $qualifierrest=$qualifier;
                   9642:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9643:     my $spacequalifierrest=$space;
                   9644:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9645:     if ($realm eq 'user') {
1.48      www      9646: # --------------------------------------------------------------- user.resource
                   9647: 	if ($space eq 'resource') {
1.651     albertel 9648: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9649: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9650: 		 &&
1.744     albertel 9651: 		 ($symbparm eq &symbread()) ) {	
                   9652: 		# if we are in the middle of processing the resource the
                   9653: 		# get the value we are planning on committing
                   9654:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9655:                     return $Apache::lonhomework::results{$qualifierrest};
                   9656:                 } else {
                   9657:                     return $Apache::lonhomework::history{$qualifierrest};
                   9658:                 }
1.335     albertel 9659: 	    } else {
1.359     albertel 9660: 		my %restored;
1.620     albertel 9661: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9662: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9663: 		} else {
                   9664: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9665: 		}
1.335     albertel 9666: 		return $restored{$qualifierrest};
                   9667: 	    }
1.48      www      9668: # ----------------------------------------------------------------- user.access
                   9669:         } elsif ($space eq 'access') {
1.218     albertel 9670: 	    # FIXME - not supporting calls for a specific user
1.48      www      9671:             return &allowed($qualifier,$rest);
                   9672: # ------------------------------------------ user.preferences, user.environment
                   9673:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9674: 	    if (($uname eq $env{'user.name'}) &&
                   9675: 		($udom eq $env{'user.domain'})) {
                   9676: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9677: 	    } else {
1.359     albertel 9678: 		my %returnhash;
                   9679: 		if (!$publicuser) {
                   9680: 		    %returnhash=&userenvironment($udom,$uname,
                   9681: 						 $qualifierrest);
                   9682: 		}
1.218     albertel 9683: 		return $returnhash{$qualifierrest};
                   9684: 	    }
1.48      www      9685: # ----------------------------------------------------------------- user.course
                   9686:         } elsif ($space eq 'course') {
1.218     albertel 9687: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9688:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9689: # ------------------------------------------------------------------- user.role
                   9690:         } elsif ($space eq 'role') {
1.218     albertel 9691: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9692:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9693:             if ($qualifier eq 'value') {
                   9694: 		return $role;
                   9695:             } elsif ($qualifier eq 'extent') {
                   9696:                 return $where;
                   9697:             }
                   9698: # ----------------------------------------------------------------- user.domain
                   9699:         } elsif ($space eq 'domain') {
1.218     albertel 9700:             return $udom;
1.48      www      9701: # ------------------------------------------------------------------- user.name
                   9702:         } elsif ($space eq 'name') {
1.218     albertel 9703:             return $uname;
1.48      www      9704: # ---------------------------------------------------- Any other user namespace
1.29      www      9705:         } else {
1.359     albertel 9706: 	    my %reply;
                   9707: 	    if (!$publicuser) {
                   9708: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9709: 	    }
                   9710: 	    return $reply{$qualifierrest};
1.48      www      9711:         }
1.236     www      9712:     } elsif ($realm eq 'query') {
                   9713: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9714:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9715: 						[$spacequalifierrest]);
1.620     albertel 9716: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9717:    } elsif ($realm eq 'request') {
1.48      www      9718: # ------------------------------------------------------------- request.browser
                   9719:         if ($space eq 'browser') {
1.1145    bisitz   9720:             return $env{'browser.'.$qualifier};
1.57      www      9721: # ------------------------------------------------------------ request.filename
                   9722:         } else {
1.620     albertel 9723:             return $env{'request.'.$spacequalifierrest};
1.29      www      9724:         }
1.28      www      9725:     } elsif ($realm eq 'course') {
1.48      www      9726: # ---------------------------------------------------------- course.description
1.620     albertel 9727:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9728:     } elsif ($realm eq 'resource') {
1.165     www      9729: 
1.620     albertel 9730: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9731: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9732: 	}
1.693     albertel 9733: 
                   9734: 	if ($space eq 'title') {
                   9735: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9736: 	    return &gettitle($symbparm);
                   9737: 	}
                   9738: 	
                   9739: 	if ($space eq 'map') {
                   9740: 	    my ($map) = &decode_symb($symbparm);
                   9741: 	    return &symbread($map);
                   9742: 	}
1.905     albertel 9743: 	if ($space eq 'filename') {
                   9744: 	    if ($symbparm) {
                   9745: 		return &clutter((&decode_symb($symbparm))[2]);
                   9746: 	    }
                   9747: 	    return &hreflocation('',$env{'request.filename'});
                   9748: 	}
1.693     albertel 9749: 
                   9750: 	my ($section, $group, @groups);
1.593     albertel 9751: 	my ($courselevelm,$courselevel);
1.539     albertel 9752: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9753: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9754: 
1.218     albertel 9755: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9756: 
1.60      www      9757: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9758: 	    my $symbp=$symbparm;
1.735     albertel 9759: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9760: 
                   9761: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9762: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9763: 
1.620     albertel 9764: 	    if (($env{'user.name'} eq $uname) &&
                   9765: 		($env{'user.domain'} eq $udom)) {
                   9766: 		$section=$env{'request.course.sec'};
1.733     raeburn  9767:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9768:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9769: 	    } else {
1.539     albertel 9770: 		if (! defined($usection)) {
1.551     albertel 9771: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9772: 		} else {
                   9773: 		    $section = $usection;
                   9774: 		}
1.733     raeburn  9775:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9776: 	    }
                   9777: 
                   9778: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9779: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9780: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9781: 
1.593     albertel 9782: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9783: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9784: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9785: 
1.60      www      9786: # ----------------------------------------------------------- first, check user
1.624     albertel 9787: 
                   9788: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9789: 				       ([$courselevelr,'resource'],
                   9790: 					[$courselevelm,'map'     ],
                   9791: 					[$courselevel, 'course'  ]));
1.931     albertel 9792: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9793: 
1.594     albertel 9794: # ------------------------------------------------ second, check some of course
1.684     raeburn  9795:             my $coursereply;
1.691     raeburn  9796:             if (@groups > 0) {
                   9797:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9798:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9799:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9800:             }
1.96      www      9801: 
1.684     raeburn  9802: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9803: 				  $env{'course.'.$courseid.'.domain'},
                   9804: 				  'course',
                   9805: 				  ([$seclevelr,   'resource'],
                   9806: 				   [$seclevelm,   'map'     ],
                   9807: 				   [$seclevel,    'course'  ],
                   9808: 				   [$courselevelr,'resource']));
                   9809: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9810: 
1.60      www      9811: # ------------------------------------------------------ third, check map parms
1.218     albertel 9812: 	    my %parmhash=();
                   9813: 	    my $thisparm='';
                   9814: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9815: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9816: 		    &GDBM_READER(),0640)) {
1.218     albertel 9817: 		$thisparm=$parmhash{$symbparm};
                   9818: 		untie(%parmhash);
                   9819: 	    }
1.927     albertel 9820: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9821: 	}
1.594     albertel 9822: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9823: 
1.218     albertel 9824: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9825: 	my $filename;
                   9826: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9827: 	if ($symbparm) {
1.409     www      9828: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9829: 	} else {
1.620     albertel 9830: 	    $filename=$env{'request.filename'};
1.282     albertel 9831: 	}
                   9832: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9833: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9834: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9835: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9836: 
1.927     albertel 9837: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9838: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9839: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9840: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9841: 				     $env{'course.'.$courseid.'.domain'},
                   9842: 				     'course',
1.927     albertel 9843: 				     ([$courselevelm,'map'   ],
                   9844: 				      [$courselevel, 'course']));
                   9845: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9846: 	}
1.145     www      9847: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9848: 	unless ($space eq '0') {
1.336     albertel 9849: 	    my @parts=split(/_/,$space);
                   9850: 	    my $id=pop(@parts);
                   9851: 	    my $part=join('_',@parts);
                   9852: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9853: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9854: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9855: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9856: 	}
1.395     albertel 9857: 	if ($recurse) { return undef; }
                   9858: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9859: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9860: # ---------------------------------------------------- Any other user namespace
                   9861:     } elsif ($realm eq 'environment') {
                   9862: # ----------------------------------------------------------------- environment
1.620     albertel 9863: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9864: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9865: 	} else {
1.770     albertel 9866: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9867: 		return '';
                   9868: 	    }
1.219     albertel 9869: 	    my %returnhash=&userenvironment($udom,$uname,
                   9870: 					    $spacequalifierrest);
                   9871: 	    return $returnhash{$spacequalifierrest};
                   9872: 	}
1.28      www      9873:     } elsif ($realm eq 'system') {
1.48      www      9874: # ----------------------------------------------------------------- system.time
                   9875: 	if ($space eq 'time') {
                   9876: 	    return time;
                   9877:         }
1.696     albertel 9878:     } elsif ($realm eq 'server') {
                   9879: # ----------------------------------------------------------------- system.time
                   9880: 	if ($space eq 'name') {
                   9881: 	    return $ENV{'SERVER_NAME'};
                   9882:         }
1.28      www      9883:     }
1.48      www      9884:     return '';
1.61      www      9885: }
                   9886: 
1.927     albertel 9887: sub get_reply {
                   9888:     my ($reply_value) = @_;
1.940     raeburn  9889:     if (ref($reply_value) eq 'ARRAY') {
                   9890:         if (wantarray) {
                   9891: 	    return @$reply_value;
                   9892:         }
                   9893:         return $reply_value->[0];
                   9894:     } else {
                   9895:         return $reply_value;
1.927     albertel 9896:     }
                   9897: }
                   9898: 
1.691     raeburn  9899: sub check_group_parms {
                   9900:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9901:     my @groupitems = ();
                   9902:     my $resultitem;
1.927     albertel 9903:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9904:     foreach my $group (@{$groups}) {
                   9905:         foreach my $level (@levels) {
1.927     albertel 9906:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9907:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9908:         }
                   9909:     }
                   9910:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9911:                             $env{'course.'.$courseid.'.domain'},
                   9912:                                      'course',@groupitems);
                   9913:     return $coursereply;
                   9914: }
                   9915: 
                   9916: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9917:     my ($courseid,@groups) = @_;
                   9918:     @groups = sort(@groups);
1.691     raeburn  9919:     return @groups;
                   9920: }
                   9921: 
1.395     albertel 9922: sub packages_tab_default {
                   9923:     my ($uri,$varname)=@_;
                   9924:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9925: 
                   9926:     my (@extension,@specifics,$do_default);
                   9927:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9928: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9929: 	if ($pack_type eq 'default') {
                   9930: 	    $do_default=1;
                   9931: 	} elsif ($pack_type eq 'extension') {
                   9932: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9933: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9934: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9935: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9936: 	}
                   9937:     }
                   9938:     # first look for a package that matches the requested part id
                   9939:     foreach my $package (@specifics) {
                   9940: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9941: 	next if ($pack_part ne $part);
                   9942: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9943: 	    return $packagetab{"$pack_type&$name&default"};
                   9944: 	}
                   9945:     }
                   9946:     # look for any possible matching non extension_ package
                   9947:     foreach my $package (@specifics) {
                   9948: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9949: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9950: 	    return $packagetab{"$pack_type&$name&default"};
                   9951: 	}
1.585     albertel 9952: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9953: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9954: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9955: 	}
                   9956:     }
1.738     albertel 9957:     # look for any posible extension_ match
                   9958:     foreach my $package (@extension) {
                   9959: 	my ($package,$pack_type)=@{$package};
                   9960: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9961: 	    return $packagetab{"$pack_type&$name&default"};
                   9962: 	}
                   9963: 	if (defined($packagetab{$package."&$name&default"})) {
                   9964: 	    return $packagetab{$package."&$name&default"};
                   9965: 	}
                   9966:     }
                   9967:     # look for a global default setting
                   9968:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9969: 	return $packagetab{"default&$name&default"};
                   9970:     }
1.395     albertel 9971:     return undef;
                   9972: }
                   9973: 
1.334     albertel 9974: sub add_prefix_and_part {
                   9975:     my ($prefix,$part)=@_;
                   9976:     my $keyroot;
                   9977:     if (defined($prefix) && $prefix !~ /^__/) {
                   9978: 	# prefix that has a part already
                   9979: 	$keyroot=$prefix;
                   9980:     } elsif (defined($prefix)) {
                   9981: 	# prefix that is missing a part
                   9982: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9983:     } else {
                   9984: 	# no prefix at all
                   9985: 	if (defined($part)) { $keyroot='_'.$part; }
                   9986:     }
                   9987:     return $keyroot;
                   9988: }
                   9989: 
1.71      www      9990: # ---------------------------------------------------------------- Get metadata
                   9991: 
1.599     albertel 9992: my %metaentry;
1.1070    www      9993: my %importedpartids;
1.71      www      9994: sub metadata {
1.176     www      9995:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9996:     $uri=&declutter($uri);
1.288     albertel 9997:     # if it is a non metadata possible uri return quickly
1.529     albertel 9998:     if (($uri eq '') || 
                   9999: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10000: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10001:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10002: 	return undef;
                   10003:     }
1.1140    www      10004:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10005: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10006: 	return undef;
1.288     albertel 10007:     }
1.73      www      10008:     my $filename=$uri;
                   10009:     $uri=~s/\.meta$//;
1.172     www      10010: #
                   10011: # Is the metadata already cached?
1.177     www      10012: # Look at timestamp of caching
1.172     www      10013: # Everything is cached by the main uri, libraries are never directly cached
                   10014: #
1.428     albertel 10015:     if (!defined($liburi)) {
1.599     albertel 10016: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10017: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10018:     }
                   10019:     {
1.1069    www      10020: # Imported parts would go here
1.1070    www      10021:         my %importedids=();
                   10022:         my @origfileimportpartids=();
1.1069    www      10023:         my $importedparts=0;
1.172     www      10024: #
                   10025: # Is this a recursive call for a library?
                   10026: #
1.599     albertel 10027: #	if (! exists($metacache{$uri})) {
                   10028: #	    $metacache{$uri}={};
                   10029: #	}
1.924     albertel 10030: 	my $cachetime = 60*60;
1.171     www      10031:         if ($liburi) {
                   10032: 	    $liburi=&declutter($liburi);
                   10033:             $filename=$liburi;
1.401     bowersj2 10034:         } else {
1.599     albertel 10035: 	    &devalidate_cache_new('meta',$uri);
                   10036: 	    undef(%metaentry);
1.401     bowersj2 10037: 	}
1.140     www      10038:         my %metathesekeys=();
1.73      www      10039:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10040: 	my $metastring;
1.1140    www      10041: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10042: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10043: 	    $metastring = 
1.929     albertel 10044: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10045: 					  ('grade_target' => 'meta'));
                   10046: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10047: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10048:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10049: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10050: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10051: 	    $metastring=&getfile($file);
1.489     albertel 10052: 	}
1.208     albertel 10053:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10054:         my $token;
1.140     www      10055:         undef %metathesekeys;
1.71      www      10056:         while ($token=$parser->get_token) {
1.339     albertel 10057: 	    if ($token->[0] eq 'S') {
                   10058: 		if (defined($token->[2]->{'package'})) {
1.172     www      10059: #
                   10060: # This is a package - get package info
                   10061: #
1.339     albertel 10062: 		    my $package=$token->[2]->{'package'};
                   10063: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10064: 		    if (defined($token->[2]->{'id'})) { 
                   10065: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10066: 		    }
1.599     albertel 10067: 		    if ($metaentry{':packages'}) {
                   10068: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10069: 		    } else {
1.599     albertel 10070: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10071: 		    }
1.736     albertel 10072: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10073: 			my $part=$keyroot;
                   10074: 			$part=~s/^\_//;
1.736     albertel 10075: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10076: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10077: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10078: 			    # ignore package.tab specified default values
                   10079:                             # here &package_tab_default() will fetch those
                   10080: 			    if ($subp eq 'default') { next; }
1.736     albertel 10081: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10082: 			    my $unikey;
                   10083: 			    if ($pack =~ /_0$/) {
                   10084: 				$unikey='parameter_0_'.$name;
                   10085: 				$part=0;
                   10086: 			    } else {
                   10087: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10088: 			    }
1.339     albertel 10089: 			    if ($subp eq 'display') {
                   10090: 				$value.=' [Part: '.$part.']';
                   10091: 			    }
1.599     albertel 10092: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10093: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10094: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10095: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10096: 			    }
1.599     albertel 10097: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10098: 				$metaentry{':'.$unikey}=
                   10099: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10100: 			    }
1.339     albertel 10101: 			}
                   10102: 		    }
                   10103: 		} else {
1.172     www      10104: #
                   10105: # This is not a package - some other kind of start tag
1.339     albertel 10106: #
                   10107: 		    my $entry=$token->[1];
1.1068    www      10108: 		    my $unikey='';
1.175     www      10109: 
1.339     albertel 10110: 		    if ($entry eq 'import') {
1.175     www      10111: #
                   10112: # Importing a library here
1.339     albertel 10113: #
1.1067    www      10114:                         my $location=$parser->get_text('/import');
                   10115:                         my $dir=$filename;
                   10116:                         $dir=~s|[^/]*$||;
                   10117:                         $location=&filelocation($dir,$location);
1.1069    www      10118:                        
1.1068    www      10119:                         my $importmode=$token->[2]->{'importmode'};
                   10120:                         if ($importmode eq 'problem') {
1.1069    www      10121: # Import as problem/response
1.1068    www      10122:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10123:                         } elsif ($importmode eq 'part') {
                   10124: # Import as part(s)
1.1069    www      10125:                            $importedparts=1;
                   10126: # We need to get the original file and the imported file to get the part order correct
                   10127: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10128: # Load and inspect original file
1.1070    www      10129:                            if ($#origfileimportpartids<0) {
                   10130:                               undef(%importedpartids);
                   10131:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10132:                               my $origfile=&getfile($origfilelocation);
                   10133:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10134:                            }
                   10135: 
1.1069    www      10136: # Load and inspect imported file
                   10137:                            my $impfile=&getfile($location);
                   10138:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10139:                            if ($#impfilepartids>=0) {
                   10140: # This problem had parts
1.1070    www      10141:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10142:                            } else {
                   10143: # Importing by turning a single problem into a problem part
                   10144: # It gets the import-tags ID as part-ID
                   10145:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10146:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10147:                            }
1.1068    www      10148:                         } else {
                   10149: # Normal import
                   10150:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10151:                            if (defined($token->[2]->{'id'})) {
                   10152:                               $unikey.='_'.$token->[2]->{'id'};
                   10153:                            }
1.1067    www      10154:                         }
                   10155: 
1.339     albertel 10156: 			if ($depthcount<20) {
1.736     albertel 10157: 			    my $metadata = 
                   10158: 				&metadata($uri,'keys', $location,$unikey,
                   10159: 					  $depthcount+1);
                   10160: 			    foreach my $meta (split(',',$metadata)) {
                   10161: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10162: 				$metathesekeys{$meta}=1;
1.339     albertel 10163: 			    }
1.1068    www      10164: 			
                   10165:                         }
1.1067    www      10166: 		    } else {
                   10167: #
                   10168: # Not importing, some other kind of non-package, non-library start tag
                   10169: # 
                   10170:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10171:                         if (defined($token->[2]->{'id'})) {
                   10172:                             $unikey.='_'.$token->[2]->{'id'};
                   10173:                         }
1.339     albertel 10174: 			if (defined($token->[2]->{'name'})) { 
                   10175: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10176: 			}
                   10177: 			$metathesekeys{$unikey}=1;
1.736     albertel 10178: 			foreach my $param (@{$token->[3]}) {
                   10179: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10180: 				$token->[2]->{$param};
1.339     albertel 10181: 			}
                   10182: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10183: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10184: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10185: 		 # only ws inside the tag, and not in default, so use default
                   10186: 		 # as value
1.599     albertel 10187: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10188: 			} elsif ( $internaltext =~ /\S/ ) {
                   10189: 		  # something interesting inside the tag
                   10190: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10191: 			} else {
1.908     albertel 10192: 		  # no interesting values, don't set a default
1.339     albertel 10193: 			}
1.172     www      10194: # end of not-a-package not-a-library import
1.339     albertel 10195: 		    }
1.172     www      10196: # end of not-a-package start tag
1.339     albertel 10197: 		}
1.172     www      10198: # the next is the end of "start tag"
1.339     albertel 10199: 	    }
                   10200: 	}
1.483     albertel 10201: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10202: 	$extension = lc($extension);
                   10203: 	if ($extension eq 'htm') { $extension='html'; }
                   10204: 
1.737     albertel 10205: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10206: 	    #no specific packages #how's our extension
                   10207: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10208: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10209: 					 \%metathesekeys);
                   10210: 	}
1.883     albertel 10211: 
                   10212: 	if (!exists($metaentry{':packages'})
                   10213: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10214: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10215: 		#no specific packages well let's get default then
                   10216: 		if ($key!~/^default&/) { next; }
1.488     albertel 10217: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10218: 					     \%metathesekeys);
                   10219: 	    }
                   10220: 	}
1.338     www      10221: # are there custom rights to evaluate
1.599     albertel 10222: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10223: 
1.338     www      10224:     #
                   10225:     # Importing a rights file here
1.339     albertel 10226:     #
                   10227: 	    unless ($depthcount) {
1.599     albertel 10228: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10229: 		my $dir=$filename;
                   10230: 		$dir=~s|[^/]*$||;
                   10231: 		$location=&filelocation($dir,$location);
1.736     albertel 10232: 		my $rights_metadata =
                   10233: 		    &metadata($uri,'keys',$location,'_rights',
                   10234: 			      $depthcount+1);
                   10235: 		foreach my $rights (split(',',$rights_metadata)) {
                   10236: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10237: 		    $metathesekeys{$rights}=1;
1.339     albertel 10238: 		}
                   10239: 	    }
                   10240: 	}
1.737     albertel 10241: 	# uniqifiy package listing
                   10242: 	my %seen;
                   10243: 	my @uniq_packages =
                   10244: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10245: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10246: 
1.1070    www      10247:         if ($importedparts) {
                   10248: # We had imported parts and need to rebuild partorder
                   10249:            $metaentry{':partorder'}='';
                   10250:            $metathesekeys{'partorder'}=1;
                   10251:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10252:                if ($origfileimportpartids[$index] eq 'part') {
                   10253: # original part, part of the problem
                   10254:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10255:                } else {
                   10256: # we have imported parts at this position
                   10257:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10258:                }
                   10259:            }
                   10260:            $metaentry{':partorder'}=~s/^\,//;
                   10261:         }
                   10262: 
1.737     albertel 10263: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10264: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10265: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10266: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10267: # this is the end of "was not already recently cached
1.71      www      10268:     }
1.599     albertel 10269:     return $metaentry{':'.$what};
1.261     albertel 10270: }
                   10271: 
1.488     albertel 10272: sub metadata_create_package_def {
1.483     albertel 10273:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10274:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10275:     if ($subp eq 'default') { next; }
                   10276:     
1.599     albertel 10277:     if (defined($metaentry{':packages'})) {
                   10278: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10279:     } else {
1.599     albertel 10280: 	$metaentry{':packages'}=$package;
1.483     albertel 10281:     }
                   10282:     my $value=$packagetab{$key};
                   10283:     my $unikey;
                   10284:     $unikey='parameter_0_'.$name;
1.599     albertel 10285:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10286:     $$metathesekeys{$unikey}=1;
1.599     albertel 10287:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10288: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10289:     }
1.599     albertel 10290:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10291: 	$metaentry{':'.$unikey}=
                   10292: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10293:     }
                   10294: }
                   10295: 
1.261     albertel 10296: sub metadata_generate_part0 {
                   10297:     my ($metadata,$metacache,$uri) = @_;
                   10298:     my %allnames;
1.737     albertel 10299:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10300: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10301: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10302: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10303: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10304: 	    $allnames{$name}=$part;
                   10305: 	  }
                   10306: 	}
                   10307:     }
                   10308:     foreach my $name (keys(%allnames)) {
                   10309:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10310:       my $key=":parameter_0_$name";
1.261     albertel 10311:       $$metacache{"$key.part"}='0';
                   10312:       $$metacache{"$key.name"}=$name;
1.428     albertel 10313:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10314: 					   $allnames{$name}.'_'.$name.
                   10315: 					   '.type'};
1.428     albertel 10316:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10317: 			     '.display'};
1.644     www      10318:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10319:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10320:       $$metacache{"$key.display"}=$olddis;
                   10321:     }
1.71      www      10322: }
                   10323: 
1.764     albertel 10324: # ------------------------------------------------------ Devalidate title cache
                   10325: 
                   10326: sub devalidate_title_cache {
                   10327:     my ($url)=@_;
                   10328:     if (!$env{'request.course.id'}) { return; }
                   10329:     my $symb=&symbread($url);
                   10330:     if (!$symb) { return; }
                   10331:     my $key=$env{'request.course.id'}."\0".$symb;
                   10332:     &devalidate_cache_new('title',$key);
                   10333: }
                   10334: 
1.1014    droeschl 10335: # ------------------------------------------------- Get the title of a course
                   10336: 
                   10337: sub current_course_title {
                   10338:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10339: }
1.301     www      10340: # ------------------------------------------------- Get the title of a resource
                   10341: 
                   10342: sub gettitle {
                   10343:     my $urlsymb=shift;
                   10344:     my $symb=&symbread($urlsymb);
1.534     albertel 10345:     if ($symb) {
1.620     albertel 10346: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10347: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10348: 	if (defined($cached)) { 
                   10349: 	    return $result;
                   10350: 	}
1.534     albertel 10351: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10352: 	my $title='';
1.907     albertel 10353: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10354: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10355: 	} else {
                   10356: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10357: 		    &GDBM_READER(),0640)) {
                   10358: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10359: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10360: 		untie(%bighash);
                   10361: 	    }
1.534     albertel 10362: 	}
                   10363: 	$title=~s/\&colon\;/\:/gs;
                   10364: 	if ($title) {
1.1159    www      10365: # Remember both $symb and $title for dynamic metadata
                   10366:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10367:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10368: # Cache this title and then return it
1.599     albertel 10369: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10370: 	}
                   10371: 	$urlsymb=$url;
                   10372:     }
                   10373:     my $title=&metadata($urlsymb,'title');
                   10374:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10375:     return $title;
1.301     www      10376: }
1.613     albertel 10377: 
1.1199    raeburn  10378: sub getdocspath {
                   10379:     my ($symb) = @_;
                   10380:     my $path;
                   10381:     if ($symb) {
                   10382:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10383:         if ($resurl=~/\.(sequence|page)$/) {
                   10384:             $mapurl=$resurl;
                   10385:         } elsif ($resurl eq 'adm/navmaps') {
                   10386:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10387:         }
                   10388:         my $mapresobj;
                   10389:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10390:         if (ref($navmap)) {
                   10391:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10392:         }
                   10393:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10394:         my $type=$2;
                   10395:         if (ref($mapresobj)) {
                   10396:             my $pcslist = $mapresobj->map_hierarchy();
                   10397:             if ($pcslist ne '') {
                   10398:                 foreach my $pc (split(/,/,$pcslist)) {
                   10399:                     next if ($pc <= 1);
                   10400:                     my $res = $navmap->getByMapPc($pc);
                   10401:                     if (ref($res)) {
                   10402:                         my $thisurl = $res->src();
                   10403:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10404:                         my $thistitle = $res->title();
                   10405:                         $path .= '&'.
                   10406:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10407:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10408:                                  ':'.$res->randompick().
                   10409:                                  ':'.$res->randomout().
                   10410:                                  ':'.$res->encrypted().
1.1205    raeburn  10411:                                  ':'.$res->randomorder().
                   10412:                                  ':'.$res->is_page();
1.1199    raeburn  10413:                     }
                   10414:                 }
                   10415:             }
                   10416:             $path =~ s/^\&//;
                   10417:             my $maptitle = $mapresobj->title();
                   10418:             if ($mapurl eq 'default') {
                   10419:                 $maptitle = 'Main Course Documents';
                   10420:             }
                   10421:             $path .= ($path ne '')? '&' : ''.
                   10422:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10423:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10424:                     ':'.$mapresobj->randompick().
                   10425:                     ':'.$mapresobj->randomout().
                   10426:                     ':'.$mapresobj->encrypted().
1.1205    raeburn  10427:                     ':'.$mapresobj->randomorder().
                   10428:                     ':'.$mapresobj->is_page();
1.1199    raeburn  10429:         } else {
                   10430:             my $maptitle = &gettitle($mapurl);
1.1205    raeburn  10431:             my $ispage;
                   10432:             if ($mapurl =~ /\.page$/) {
                   10433:                 $ispage = 1;
                   10434:             }
1.1199    raeburn  10435:             if ($mapurl eq 'default') {
                   10436:                 $maptitle = 'Main Course Documents';
                   10437:             }
                   10438:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1205    raeburn  10439:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
1.1199    raeburn  10440:         }
                   10441:         unless ($mapurl eq 'default') {
                   10442:             $path = 'default&'.
                   10443:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
1.1205    raeburn  10444:                     ':::::&'.$path;
1.1199    raeburn  10445:         }
                   10446:     }
                   10447:     return $path;
                   10448: }
                   10449: 
1.614     albertel 10450: sub get_slot {
                   10451:     my ($which,$cnum,$cdom)=@_;
                   10452:     if (!$cnum || !$cdom) {
1.790     albertel 10453: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10454: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10455: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10456:     }
1.703     albertel 10457:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10458:     my %slotinfo;
                   10459:     if (exists($remembered{$key})) {
                   10460: 	$slotinfo{$which} = $remembered{$key};
                   10461:     } else {
                   10462: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10463: 	&Apache::lonhomework::showhash(%slotinfo);
                   10464: 	my ($tmp)=keys(%slotinfo);
                   10465: 	if ($tmp=~/^error:/) { return (); }
                   10466: 	$remembered{$key} = $slotinfo{$which};
                   10467:     }
1.616     albertel 10468:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10469: 	return %{$slotinfo{$which}};
                   10470:     }
                   10471:     return $slotinfo{$which};
1.614     albertel 10472: }
1.1150    raeburn  10473: 
                   10474: sub get_reservable_slots {
                   10475:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10476:     my $now = time;
                   10477:     my $reservable_info;
                   10478:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10479:     if (exists($remembered{$key})) {
                   10480:         $reservable_info = $remembered{$key};
                   10481:     } else {
                   10482:         my %resv;
                   10483:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10484:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10485:         $reservable_info = \%resv;
                   10486:         $remembered{$key} = $reservable_info;
                   10487:     }
                   10488:     return $reservable_info;
                   10489: }
                   10490: 
                   10491: sub get_course_slots {
                   10492:     my ($cnum,$cdom) = @_;
                   10493:     my $hashid=$cnum.':'.$cdom;
                   10494:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10495:     if (defined($cached)) {
                   10496:         if (ref($result) eq 'HASH') {
                   10497:             return %{$result};
                   10498:         }
                   10499:     } else {
                   10500:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10501:         my ($tmp) = keys(%slots);
                   10502:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10503:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10504:             return %slots;
                   10505:         }
                   10506:     }
                   10507:     return;
                   10508: }
                   10509: 
                   10510: sub devalidate_slots_cache {
                   10511:     my ($cnum,$cdom)=@_;
                   10512:     my $hashid=$cnum.':'.$cdom;
                   10513:     &devalidate_cache_new('allslots',$hashid);
                   10514: }
                   10515: 
1.1181    raeburn  10516: sub get_coursechange {
                   10517:     my ($cdom,$cnum) = @_;
                   10518:     if ($cdom eq '' || $cnum eq '') {
                   10519:         return unless ($env{'request.course.id'});
                   10520:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10521:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10522:     }
                   10523:     my $hashid=$cdom.'_'.$cnum;
                   10524:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10525:     if ((defined($cached)) && ($change ne '')) {
                   10526:         return $change;
                   10527:     } else {
                   10528:         my %crshash;
                   10529:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10530:         if ($crshash{'internal.contentchange'} eq '') {
                   10531:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10532:             if ($change eq '') {
                   10533:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10534:                 $change = $crshash{'internal.created'};
                   10535:             }
                   10536:         } else {
                   10537:             $change = $crshash{'internal.contentchange'};
                   10538:         }
                   10539:         my $cachetime = 600;
                   10540:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10541:     }
                   10542:     return $change;
                   10543: }
                   10544: 
                   10545: sub devalidate_coursechange_cache {
                   10546:     my ($cnum,$cdom)=@_;
                   10547:     my $hashid=$cnum.':'.$cdom;
                   10548:     &devalidate_cache_new('crschange',$hashid);
                   10549: }
                   10550: 
1.31      www      10551: # ------------------------------------------------- Update symbolic store links
                   10552: 
                   10553: sub symblist {
                   10554:     my ($mapname,%newhash)=@_;
1.438     www      10555:     $mapname=&deversion(&declutter($mapname));
1.31      www      10556:     my %hash;
1.620     albertel 10557:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10558:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10559:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10560: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10561: 		next if ($url eq 'last_known'
                   10562: 			 && $env{'form.no_update_last_known'});
                   10563: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10564: 						    $newhash{$url}->[1],
                   10565: 						    $newhash{$url}->[0]);
1.191     harris41 10566:             }
1.31      www      10567:             if (untie(%hash)) {
                   10568: 		return 'ok';
                   10569:             }
                   10570:         }
                   10571:     }
                   10572:     return 'error';
1.212     www      10573: }
                   10574: 
                   10575: # --------------------------------------------------------------- Verify a symb
                   10576: 
                   10577: sub symbverify {
1.1190    raeburn  10578:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10579:     my $thisfn=$thisurl;
1.439     www      10580:     $thisfn=&declutter($thisfn);
1.215     www      10581: # direct jump to resource in page or to a sequence - will construct own symbs
                   10582:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10583: # check URL part
1.409     www      10584:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10585: 
1.431     www      10586:     unless ($url eq $thisfn) { return 0; }
1.213     www      10587: 
1.216     www      10588:     $symb=&symbclean($symb);
1.510     www      10589:     $thisurl=&deversion($thisurl);
1.439     www      10590:     $thisfn=&deversion($thisfn);
1.213     www      10591: 
                   10592:     my %bighash;
                   10593:     my $okay=0;
1.431     www      10594: 
1.620     albertel 10595:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10596:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10597:         my $noclutter;
1.1032    raeburn  10598:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10599:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10600:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10601:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10602:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10603:                 $noclutter = 1;
                   10604:             }
                   10605:         }
                   10606:         my $ids;
                   10607:         if ($noclutter) {
                   10608:             $ids=$bighash{'ids_'.$thisurl};
                   10609:         } else {
                   10610:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10611:         }
1.1102    raeburn  10612:         unless ($ids) {
                   10613:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10614:             $ids=$bighash{$idkey};
1.216     www      10615:         }
                   10616:         if ($ids) {
                   10617: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10618:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10619:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10620:             }
1.800     albertel 10621: 	    foreach my $id (split(/\,/,$ids)) {
                   10622: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10623:                if (
                   10624:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10625:    eq $symb) {
                   10626:                    if (ref($encstate)) {
                   10627:                        $$encstate = $bighash{'encrypted_'.$id};
                   10628:                    }
1.620     albertel 10629: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10630: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10631:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10632: 		       $okay=1;
1.1202    raeburn  10633:                        last;
1.582     albertel 10634: 		   }
                   10635: 	       }
1.216     www      10636: 	   }
                   10637:         }
1.213     www      10638: 	untie(%bighash);
                   10639:     }
                   10640:     return $okay;
1.31      www      10641: }
                   10642: 
1.210     www      10643: # --------------------------------------------------------------- Clean-up symb
                   10644: 
                   10645: sub symbclean {
                   10646:     my $symb=shift;
1.568     albertel 10647:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10648: # remove version from map
                   10649:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10650: 
1.210     www      10651: # remove version from URL
                   10652:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10653: 
1.507     www      10654: # remove wrapper
                   10655: 
1.510     www      10656:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10657:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10658:     return $symb;
1.409     www      10659: }
                   10660: 
                   10661: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10662: 
                   10663: sub encode_symb {
                   10664:     my ($map,$resid,$url)=@_;
                   10665:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10666: }
1.409     www      10667: 
                   10668: sub decode_symb {
1.568     albertel 10669:     my $symb=shift;
                   10670:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10671:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10672:     return (&fixversion($map),$resid,&fixversion($url));
                   10673: }
                   10674: 
                   10675: sub fixversion {
                   10676:     my $fn=shift;
1.609     banghart 10677:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10678:     my %bighash;
                   10679:     my $uri=&clutter($fn);
1.620     albertel 10680:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10681: # is this cached?
1.599     albertel 10682:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10683:     if (defined($cached)) { return $result; }
                   10684: # unfortunately not cached, or expired
1.620     albertel 10685:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10686: 	    &GDBM_READER(),0640)) {
                   10687:  	if ($bighash{'version_'.$uri}) {
                   10688:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10689:  	    unless (($version eq 'mostrecent') || 
                   10690: 		    ($version==&getversion($uri))) {
1.440     www      10691:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10692:  	    }
                   10693:  	}
                   10694:  	untie %bighash;
1.413     www      10695:     }
1.599     albertel 10696:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10697: }
                   10698: 
                   10699: sub deversion {
                   10700:     my $url=shift;
                   10701:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10702:     return $url;
1.210     www      10703: }
                   10704: 
1.31      www      10705: # ------------------------------------------------------ Return symb list entry
                   10706: 
                   10707: sub symbread {
1.249     www      10708:     my ($thisfn,$donotrecurse)=@_;
1.1206    raeburn  10709:     my $cache_str;
                   10710:     if ($thisfn ne '') {
                   10711:         $cache_str='request.symbread.cached.'.$thisfn;
                   10712:         if ($env{$cache_str} ne '') {
1.1179    raeburn  10713:             return $env{$cache_str};
                   10714:         }
1.1206    raeburn  10715:     } else {
1.242     www      10716: # no filename provided? try from environment
1.620     albertel 10717:         if ($env{'request.symb'}) {
                   10718: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10719: 	}
1.620     albertel 10720: 	$thisfn=$env{'request.filename'};
1.44      www      10721:     }
1.569     albertel 10722:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10723: # is that filename actually a symb? Verify, clean, and return
                   10724:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10725: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10726: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10727: 	}
1.242     www      10728:     }
1.44      www      10729:     $thisfn=declutter($thisfn);
1.31      www      10730:     my %hash;
1.37      www      10731:     my %bighash;
                   10732:     my $syval='';
1.620     albertel 10733:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10734:         my $targetfn = $thisfn;
1.609     banghart 10735:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10736:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10737:         }
1.687     albertel 10738: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10739: 	    $targetfn=$1;
                   10740: 	}
1.620     albertel 10741:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10742:                       &GDBM_READER(),0640)) {
1.481     raeburn  10743: 	    $syval=$hash{$targetfn};
1.37      www      10744:             untie(%hash);
                   10745:         }
                   10746: # ---------------------------------------------------------- There was an entry
                   10747:         if ($syval) {
1.601     albertel 10748: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10749: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10750: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10751: 		    #return $env{$cache_str}='';
1.601     albertel 10752: 		#}    
                   10753: 		#$syval.=$1;
                   10754: 	    #}
1.37      www      10755:         } else {
                   10756: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10757:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10758:                             &GDBM_READER(),0640)) {
1.37      www      10759: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10760:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10761:               unless ($ids) { 
                   10762:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10763:               }
                   10764:               unless ($ids) {
                   10765: # alias?
                   10766: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10767:               }
1.37      www      10768:               if ($ids) {
                   10769: # ------------------------------------------------------------------- Has ID(s)
                   10770:                  my @possibilities=split(/\,/,$ids);
1.39      www      10771:                  if ($#possibilities==0) {
                   10772: # ----------------------------------------------- There is only one possibility
1.37      www      10773: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10774: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10775: 						    $resid,$thisfn);
1.249     www      10776:                  } elsif (!$donotrecurse) {
1.39      www      10777: # ------------------------------------------ There is more than one possibility
                   10778:                      my $realpossible=0;
1.800     albertel 10779:                      foreach my $id (@possibilities) {
                   10780: 			 my $file=$bighash{'src_'.$id};
1.39      www      10781:                          if (&allowed('bre',$file)) {
1.800     albertel 10782:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10783:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10784: 				$realpossible++;
1.626     albertel 10785:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10786: 						    $resid,$thisfn);
1.39      www      10787:                             }
                   10788: 			 }
1.191     harris41 10789:                      }
1.39      www      10790: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10791:                  } else {
                   10792:                      $syval='';
1.37      www      10793:                  }
                   10794: 	      }
                   10795:               untie(%bighash)
1.481     raeburn  10796:            }
1.31      www      10797:         }
1.62      www      10798:         if ($syval) {
1.620     albertel 10799: 	    return $env{$cache_str}=$syval;
1.62      www      10800:         }
1.31      www      10801:     }
1.949     raeburn  10802:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10803:     return $env{$cache_str}='';
1.31      www      10804: }
                   10805: 
                   10806: # ---------------------------------------------------------- Return random seed
                   10807: 
1.32      www      10808: sub numval {
                   10809:     my $txt=shift;
                   10810:     $txt=~tr/A-J/0-9/;
                   10811:     $txt=~tr/a-j/0-9/;
                   10812:     $txt=~tr/K-T/0-9/;
                   10813:     $txt=~tr/k-t/0-9/;
                   10814:     $txt=~tr/U-Z/0-5/;
                   10815:     $txt=~tr/u-z/0-5/;
                   10816:     $txt=~s/\D//g;
1.564     albertel 10817:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10818:     return int($txt);
1.368     albertel 10819: }
                   10820: 
1.484     albertel 10821: sub numval2 {
                   10822:     my $txt=shift;
                   10823:     $txt=~tr/A-J/0-9/;
                   10824:     $txt=~tr/a-j/0-9/;
                   10825:     $txt=~tr/K-T/0-9/;
                   10826:     $txt=~tr/k-t/0-9/;
                   10827:     $txt=~tr/U-Z/0-5/;
                   10828:     $txt=~tr/u-z/0-5/;
                   10829:     $txt=~s/\D//g;
                   10830:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10831:     my $total;
                   10832:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10833:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10834:     return int($total);
                   10835: }
                   10836: 
1.575     albertel 10837: sub numval3 {
                   10838:     use integer;
                   10839:     my $txt=shift;
                   10840:     $txt=~tr/A-J/0-9/;
                   10841:     $txt=~tr/a-j/0-9/;
                   10842:     $txt=~tr/K-T/0-9/;
                   10843:     $txt=~tr/k-t/0-9/;
                   10844:     $txt=~tr/U-Z/0-5/;
                   10845:     $txt=~tr/u-z/0-5/;
                   10846:     $txt=~s/\D//g;
                   10847:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10848:     my $total;
                   10849:     foreach my $val (@txts) { $total+=$val; }
                   10850:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10851:     return $total;
                   10852: }
                   10853: 
1.675     albertel 10854: sub digest {
                   10855:     my ($data)=@_;
                   10856:     my $digest=&Digest::MD5::md5($data);
                   10857:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10858:     my ($e,$f);
                   10859:     {
                   10860:         use integer;
                   10861:         $e=($a+$b);
                   10862:         $f=($c+$d);
                   10863:         if ($_64bit) {
                   10864:             $e=(($e<<32)>>32);
                   10865:             $f=(($f<<32)>>32);
                   10866:         }
                   10867:     }
                   10868:     if (wantarray) {
                   10869: 	return ($e,$f);
                   10870:     } else {
                   10871: 	my $g;
                   10872: 	{
                   10873: 	    use integer;
                   10874: 	    $g=($e+$f);
                   10875: 	    if ($_64bit) {
                   10876: 		$g=(($g<<32)>>32);
                   10877: 	    }
                   10878: 	}
                   10879: 	return $g;
                   10880:     }
                   10881: }
                   10882: 
1.368     albertel 10883: sub latest_rnd_algorithm_id {
1.675     albertel 10884:     return '64bit5';
1.366     albertel 10885: }
1.32      www      10886: 
1.503     albertel 10887: sub get_rand_alg {
                   10888:     my ($courseid)=@_;
1.790     albertel 10889:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10890:     if ($courseid) {
1.620     albertel 10891: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10892:     }
                   10893:     return &latest_rnd_algorithm_id();
                   10894: }
                   10895: 
1.562     albertel 10896: sub validCODE {
                   10897:     my ($CODE)=@_;
                   10898:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10899:     return 0;
                   10900: }
                   10901: 
1.491     albertel 10902: sub getCODE {
1.620     albertel 10903:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10904:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10905: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10906: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10907: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10908:     }
                   10909:     return undef;
                   10910: }
1.1133    foxr     10911: #
                   10912: #  Determines the random seed for a specific context:
                   10913: #
                   10914: # parameters:
                   10915: #   symb      - in course context the symb for the seed.
                   10916: #   course_id - The course id of the form domain_coursenum.
                   10917: #   domain    - Domain for the user.
                   10918: #   course    - Course for the user.
                   10919: #   cenv      - environment of the course.
                   10920: #
                   10921: # NOTE:
                   10922: #   All parameters are picked out of the environment if missing
                   10923: #   or not defined.
                   10924: #   If a symb cannot be determined the current time is used instead.
                   10925: #
                   10926: #  For a given well defined symb, courside, domain, username,
                   10927: #  and course environment, the seed is reproducible.
                   10928: #
1.31      www      10929: sub rndseed {
1.1133    foxr     10930:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10931:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10932:     if (!defined($symb)) {
1.366     albertel 10933: 	unless ($symb=$wsymb) { return time; }
                   10934:     }
1.1146    foxr     10935:     if (!defined $courseid) { 
                   10936: 	$courseid=$wcourseid; 
                   10937:     }
                   10938:     if (!defined $domain) { $domain=$wdomain; }
                   10939:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10940: 
                   10941:     my $which;
                   10942:     if (defined($cenv->{'rndseed'})) {
                   10943: 	$which = $cenv->{'rndseed'};
                   10944:     } else {
                   10945: 	$which =&get_rand_alg($courseid);
                   10946:     }
1.491     albertel 10947:     if (defined(&getCODE())) {
1.1133    foxr     10948: 
1.675     albertel 10949: 	if ($which eq '64bit5') {
                   10950: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10951: 	} elsif ($which eq '64bit4') {
1.575     albertel 10952: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10953: 	} else {
                   10954: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10955: 	}
1.675     albertel 10956:     } elsif ($which eq '64bit5') {
                   10957: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10958:     } elsif ($which eq '64bit4') {
                   10959: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10960:     } elsif ($which eq '64bit3') {
                   10961: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10962:     } elsif ($which eq '64bit2') {
                   10963: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10964:     } elsif ($which eq '64bit') {
                   10965: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10966:     }
                   10967:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10968: }
                   10969: 
                   10970: sub rndseed_32bit {
                   10971:     my ($symb,$courseid,$domain,$username)=@_;
                   10972:     {
                   10973: 	use integer;
                   10974: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10975: 	my $symbseed=numval($symb) << 22;
                   10976: 	my $namechck=unpack("%32C*",$username) << 17;
                   10977: 	my $nameseed=numval($username) << 12;
                   10978: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10979: 	my $courseseed=unpack("%32C*",$courseid);
                   10980: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10981: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10982: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10983: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10984: 	return $num;
                   10985:     }
                   10986: }
                   10987: 
                   10988: sub rndseed_64bit {
                   10989:     my ($symb,$courseid,$domain,$username)=@_;
                   10990:     {
                   10991: 	use integer;
                   10992: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10993: 	my $symbseed=numval($symb) << 10;
                   10994: 	my $namechck=unpack("%32S*",$username);
                   10995: 	
                   10996: 	my $nameseed=numval($username) << 21;
                   10997: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10998: 	my $courseseed=unpack("%32S*",$courseid);
                   10999: 	
                   11000: 	my $num1=$symbchck+$symbseed+$namechck;
                   11001: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11002: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11003: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11004: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11005: 	return "$num1,$num2";
1.155     albertel 11006:     }
1.366     albertel 11007: }
                   11008: 
1.443     albertel 11009: sub rndseed_64bit2 {
                   11010:     my ($symb,$courseid,$domain,$username)=@_;
                   11011:     {
                   11012: 	use integer;
                   11013: 	# strings need to be an even # of cahracters long, it it is odd the
                   11014:         # last characters gets thrown away
                   11015: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11016: 	my $symbseed=numval($symb) << 10;
                   11017: 	my $namechck=unpack("%32S*",$username.' ');
                   11018: 	
                   11019: 	my $nameseed=numval($username) << 21;
1.501     albertel 11020: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11021: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11022: 	
                   11023: 	my $num1=$symbchck+$symbseed+$namechck;
                   11024: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11025: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11026: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11027: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11028: 	return "$num1,$num2";
                   11029:     }
                   11030: }
                   11031: 
                   11032: sub rndseed_64bit3 {
                   11033:     my ($symb,$courseid,$domain,$username)=@_;
                   11034:     {
                   11035: 	use integer;
                   11036: 	# strings need to be an even # of cahracters long, it it is odd the
                   11037:         # last characters gets thrown away
                   11038: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11039: 	my $symbseed=numval2($symb) << 10;
                   11040: 	my $namechck=unpack("%32S*",$username.' ');
                   11041: 	
                   11042: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11043: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11044: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11045: 	
                   11046: 	my $num1=$symbchck+$symbseed+$namechck;
                   11047: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11048: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11049: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11050: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11051: 	
1.503     albertel 11052: 	return "$num1:$num2";
1.443     albertel 11053:     }
                   11054: }
                   11055: 
1.575     albertel 11056: sub rndseed_64bit4 {
                   11057:     my ($symb,$courseid,$domain,$username)=@_;
                   11058:     {
                   11059: 	use integer;
                   11060: 	# strings need to be an even # of cahracters long, it it is odd the
                   11061:         # last characters gets thrown away
                   11062: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11063: 	my $symbseed=numval3($symb) << 10;
                   11064: 	my $namechck=unpack("%32S*",$username.' ');
                   11065: 	
                   11066: 	my $nameseed=numval3($username) << 21;
                   11067: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11068: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11069: 	
                   11070: 	my $num1=$symbchck+$symbseed+$namechck;
                   11071: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11072: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11073: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11074: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11075: 	
1.575     albertel 11076: 	return "$num1:$num2";
                   11077:     }
                   11078: }
                   11079: 
1.675     albertel 11080: sub rndseed_64bit5 {
                   11081:     my ($symb,$courseid,$domain,$username)=@_;
                   11082:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11083:     return "$num1:$num2";
                   11084: }
                   11085: 
1.366     albertel 11086: sub rndseed_CODE_64bit {
                   11087:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11088:     {
1.366     albertel 11089: 	use integer;
1.443     albertel 11090: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11091: 	my $symbseed=numval2($symb);
1.491     albertel 11092: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11093: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11094: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11095: 	my $num1=$symbseed+$CODEchck;
                   11096: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11097: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11098: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11099: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11100: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11101: 	return "$num1:$num2";
1.366     albertel 11102:     }
                   11103: }
                   11104: 
1.575     albertel 11105: sub rndseed_CODE_64bit4 {
                   11106:     my ($symb,$courseid,$domain,$username)=@_;
                   11107:     {
                   11108: 	use integer;
                   11109: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11110: 	my $symbseed=numval3($symb);
                   11111: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11112: 	my $CODEseed=numval3(&getCODE());
                   11113: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11114: 	my $num1=$symbseed+$CODEchck;
                   11115: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11116: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11117: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11118: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11119: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11120: 	return "$num1:$num2";
                   11121:     }
                   11122: }
                   11123: 
1.675     albertel 11124: sub rndseed_CODE_64bit5 {
                   11125:     my ($symb,$courseid,$domain,$username)=@_;
                   11126:     my $code = &getCODE();
                   11127:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11128:     return "$num1:$num2";
                   11129: }
                   11130: 
1.366     albertel 11131: sub setup_random_from_rndseed {
                   11132:     my ($rndseed)=@_;
1.503     albertel 11133:     if ($rndseed =~/([,:])/) {
                   11134: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11135: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11136:     } else {
                   11137: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11138:     }
1.36      albertel 11139: }
                   11140: 
1.474     albertel 11141: sub latest_receipt_algorithm_id {
1.835     albertel 11142:     return 'receipt3';
1.474     albertel 11143: }
                   11144: 
1.480     www      11145: sub recunique {
                   11146:     my $fucourseid=shift;
                   11147:     my $unique;
1.835     albertel 11148:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11149: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11150: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11151:     } else {
                   11152: 	$unique=$perlvar{'lonReceipt'};
                   11153:     }
                   11154:     return unpack("%32C*",$unique);
                   11155: }
                   11156: 
                   11157: sub recprefix {
                   11158:     my $fucourseid=shift;
                   11159:     my $prefix;
1.835     albertel 11160:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11161: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11162: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11163:     } else {
                   11164: 	$prefix=$perlvar{'lonHostID'};
                   11165:     }
                   11166:     return unpack("%32C*",$prefix);
                   11167: }
                   11168: 
1.76      www      11169: sub ireceipt {
1.474     albertel 11170:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11171: 
                   11172:     my $return =&recprefix($fucourseid).'-';
                   11173: 
                   11174:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11175: 	$env{'request.state'} eq 'construct') {
                   11176: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11177: 	return $return;
                   11178:     }
                   11179: 
1.76      www      11180:     my $cuname=unpack("%32C*",$funame);
                   11181:     my $cudom=unpack("%32C*",$fudom);
                   11182:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11183:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11184:     my $cunique=&recunique($fucourseid);
1.474     albertel 11185:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11186:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11187: 
1.790     albertel 11188: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11189: 			       
                   11190: 	$return.= ($cunique%$cuname+
                   11191: 		   $cunique%$cudom+
                   11192: 		   $cusymb%$cuname+
                   11193: 		   $cusymb%$cudom+
                   11194: 		   $cucourseid%$cuname+
                   11195: 		   $cucourseid%$cudom+
                   11196: 		   $cpart%$cuname+
                   11197: 		   $cpart%$cudom);
                   11198:     } else {
                   11199: 	$return.= ($cunique%$cuname+
                   11200: 		   $cunique%$cudom+
                   11201: 		   $cusymb%$cuname+
                   11202: 		   $cusymb%$cudom+
                   11203: 		   $cucourseid%$cuname+
                   11204: 		   $cucourseid%$cudom);
                   11205:     }
                   11206:     return $return;
1.76      www      11207: }
                   11208: 
                   11209: sub receipt {
1.474     albertel 11210:     my ($part)=@_;
1.790     albertel 11211:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11212:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11213: }
1.260     ng       11214: 
1.790     albertel 11215: sub whichuser {
                   11216:     my ($passedsymb)=@_;
                   11217:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11218:     if (defined($env{'form.grade_symb'})) {
                   11219: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11220: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11221: 	if (!$allowed &&
                   11222: 	    exists($env{'request.course.sec'}) &&
                   11223: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11224: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11225: 			      '/'.$env{'request.course.sec'});
                   11226: 	}
                   11227: 	if ($allowed) {
                   11228: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11229: 	    $courseid=$tmp_courseid;
                   11230: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11231: 	    ($name)=&get_env_multiple('form.grade_username');
                   11232: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11233: 	}
                   11234:     }
                   11235:     if (!$passedsymb) {
                   11236: 	$symb=&symbread();
                   11237:     } else {
                   11238: 	$symb=$passedsymb;
                   11239:     }
                   11240:     $courseid=$env{'request.course.id'};
                   11241:     $domain=$env{'user.domain'};
                   11242:     $name=$env{'user.name'};
                   11243:     if ($name eq 'public' && $domain eq 'public') {
                   11244: 	if (!defined($env{'form.username'})) {
                   11245: 	    $env{'form.username'}.=time.rand(10000000);
                   11246: 	}
                   11247: 	$name.=$env{'form.username'};
                   11248:     }
                   11249:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11250: 
                   11251: }
                   11252: 
1.36      albertel 11253: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11254: # returns either the contents of the file or 
                   11255: # -1 if the file doesn't exist
1.481     raeburn  11256: #
                   11257: # if the target is a file that was uploaded via DOCS, 
                   11258: # a check will be made to see if a current copy exists on the local server,
                   11259: # if it does this will be served, otherwise a copy will be retrieved from
                   11260: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11261: # the local server.   
1.472     albertel 11262: 
1.36      albertel 11263: sub getfile {
1.538     albertel 11264:     my ($file) = @_;
1.609     banghart 11265:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11266:     &repcopy($file);
                   11267:     return &readfile($file);
                   11268: }
                   11269: 
                   11270: sub repcopy_userfile {
                   11271:     my ($file)=@_;
1.1142    raeburn  11272:     my $londocroot = $perlvar{'lonDocRoot'};
                   11273:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11274:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11275:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11276: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11277:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11278:     if (-e "$file") {
1.828     www      11279: # we already have a local copy, check it out
1.538     albertel 11280: 	my @fileinfo = stat($file);
1.828     www      11281: 	my $rtncode;
                   11282: 	my $info;
1.538     albertel 11283: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11284: 	if ($lwpresp ne 'ok') {
1.828     www      11285: # there is no such file anymore, even though we had a local copy
1.482     albertel 11286: 	    if ($rtncode eq '404') {
1.538     albertel 11287: 		unlink($file);
1.482     albertel 11288: 	    }
                   11289: 	    return -1;
                   11290: 	}
                   11291: 	if ($info < $fileinfo[9]) {
1.828     www      11292: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11293: 	    return 'ok';
1.828     www      11294: 	} else {
                   11295: # the file is outdated, get rid of it
                   11296: 	    unlink($file);
1.482     albertel 11297: 	}
1.828     www      11298:     }
                   11299: # one way or the other, at this point, we don't have the file
                   11300: # construct the correct path for the file
                   11301:     my @parts = ($cdom,$cnum); 
                   11302:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11303: 	push @parts, split(/\//,$1);
                   11304:     }
                   11305:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11306:     foreach my $part (@parts) {
                   11307: 	$path .= '/'.$part;
                   11308: 	if (!-e $path) {
                   11309: 	    mkdir($path,0770);
1.482     albertel 11310: 	}
                   11311:     }
1.828     www      11312: # now the path exists for sure
                   11313: # get a user agent
                   11314:     my $ua=new LWP::UserAgent;
                   11315:     my $transferfile=$file.'.in.transfer';
                   11316: # FIXME: this should flock
                   11317:     if (-e $transferfile) { return 'ok'; }
                   11318:     my $request;
                   11319:     $uri=~s/^\///;
1.980     raeburn  11320:     my $homeserver = &homeserver($cnum,$cdom);
                   11321:     my $protocol = $protocol{$homeserver};
                   11322:     $protocol = 'http' if ($protocol ne 'https');
                   11323:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11324:     my $response=$ua->request($request,$transferfile);
                   11325: # did it work?
                   11326:     if ($response->is_error()) {
                   11327: 	unlink($transferfile);
                   11328: 	&logthis("Userfile repcopy failed for $uri");
                   11329: 	return -1;
                   11330:     }
                   11331: # worked, rename the transfer file
                   11332:     rename($transferfile,$file);
1.607     raeburn  11333:     return 'ok';
1.481     raeburn  11334: }
                   11335: 
1.517     albertel 11336: sub tokenwrapper {
                   11337:     my $uri=shift;
1.980     raeburn  11338:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11339:     $uri=~s|^/||;
1.620     albertel 11340:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11341:     my $token=$1;
1.552     albertel 11342:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11343:     if ($udom && $uname && $file) {
                   11344: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11345:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11346:         my $homeserver = &homeserver($uname,$udom);
                   11347:         my $protocol = $protocol{$homeserver};
                   11348:         $protocol = 'http' if ($protocol ne 'https');
                   11349:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11350:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11351:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11352:     } else {
                   11353:         return '/adm/notfound.html';
                   11354:     }
                   11355: }
                   11356: 
1.828     www      11357: # call with reqtype HEAD: get last modification time
                   11358: # call with reqtype GET: get the file contents
                   11359: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11360: #
1.481     raeburn  11361: sub getuploaded {
                   11362:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11363:     $uri=~s/^\///;
1.980     raeburn  11364:     my $homeserver = &homeserver($cnum,$cdom);
                   11365:     my $protocol = $protocol{$homeserver};
                   11366:     $protocol = 'http' if ($protocol ne 'https');
                   11367:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11368:     my $ua=new LWP::UserAgent;
                   11369:     my $request=new HTTP::Request($reqtype,$uri);
                   11370:     my $response=$ua->request($request);
                   11371:     $$rtncode = $response->code;
1.482     albertel 11372:     if (! $response->is_success()) {
                   11373: 	return 'failed';
                   11374:     }      
                   11375:     if ($reqtype eq 'HEAD') {
1.486     www      11376: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11377:     } elsif ($reqtype eq 'GET') {
                   11378: 	$$info = $response->content;
1.472     albertel 11379:     }
1.482     albertel 11380:     return 'ok';
1.36      albertel 11381: }
                   11382: 
1.481     raeburn  11383: sub readfile {
                   11384:     my $file = shift;
                   11385:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11386:     my $fh;
                   11387:     open($fh,"<$file");
                   11388:     my $a='';
1.800     albertel 11389:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11390:     return $a;
                   11391: }
                   11392: 
1.36      albertel 11393: sub filelocation {
1.590     banghart 11394:     my ($dir,$file) = @_;
                   11395:     my $location;
                   11396:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11397: 
                   11398:     if ($file =~ m-^/adm/-) {
                   11399: 	$file=~s-^/adm/wrapper/-/-;
                   11400: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11401:     }
1.882     albertel 11402: 
1.1139    www      11403:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11404:         $location = $file;
1.609     banghart 11405:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11406:         my ($udom,$uname,$filename)=
1.811     albertel 11407:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11408:         my $home=&homeserver($uname,$udom);
                   11409:         my $is_me=0;
                   11410:         my @ids=&current_machine_ids();
                   11411:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11412:         if ($is_me) {
1.1117    foxr     11413:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11414:         } else {
                   11415:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11416:   	      $udom.'/'.$uname.'/'.$filename;
                   11417:         }
1.882     albertel 11418:     } elsif ($file =~ m-^/adm/-) {
                   11419: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11420:     } else {
                   11421:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11422:         $file=~s:^/(res|priv)/:/:;
                   11423:         my $space=$1;
1.590     banghart 11424:         if ( !( $file =~ m:^/:) ) {
                   11425:             $location = $dir. '/'.$file;
                   11426:         } else {
1.1142    raeburn  11427:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11428:         }
1.59      albertel 11429:     }
1.590     banghart 11430:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11431:     while ($location=~m{/\.\./}) {
                   11432: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11433: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11434: 	} else {
                   11435: 	    $location=~ s{/\.\./}{/}g;
                   11436: 	}
                   11437:     } #remove dir/..
1.590     banghart 11438:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11439:     return $location;
1.46      www      11440: }
1.36      albertel 11441: 
1.46      www      11442: sub hreflocation {
                   11443:     my ($dir,$file)=@_;
1.980     raeburn  11444:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11445: 	$file=filelocation($dir,$file);
1.700     albertel 11446:     } elsif ($file=~m-^/adm/-) {
                   11447: 	$file=~s-^/adm/wrapper/-/-;
                   11448: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11449:     }
                   11450:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11451: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11452:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11453: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11454: 	        {/uploaded/$1/$2/}x;
1.46      www      11455:     }
1.913     albertel 11456:     if ($file=~ m{^/userfiles/}) {
                   11457: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11458:     }
1.462     albertel 11459:     return $file;
1.465     albertel 11460: }
                   11461: 
1.1139    www      11462: 
                   11463: 
                   11464: 
                   11465: 
1.465     albertel 11466: sub current_machine_domains {
1.853     albertel 11467:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11468: }
                   11469: 
                   11470: sub machine_domains {
                   11471:     my ($hostname) = @_;
1.465     albertel 11472:     my @domains;
1.838     albertel 11473:     my %hostname = &all_hostnames();
1.465     albertel 11474:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11475: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11476: 	if ($hostname eq $name) {
1.844     albertel 11477: 	    push(@domains,&host_domain($id));
1.465     albertel 11478: 	}
                   11479:     }
                   11480:     return @domains;
                   11481: }
                   11482: 
                   11483: sub current_machine_ids {
1.853     albertel 11484:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11485: }
                   11486: 
                   11487: sub machine_ids {
                   11488:     my ($hostname) = @_;
                   11489:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11490:     my @ids;
1.888     albertel 11491:     my %name_to_host = &all_names();
1.889     albertel 11492:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11493: 	return @{ $name_to_host{$hostname} };
                   11494:     }
                   11495:     return;
1.31      www      11496: }
                   11497: 
1.824     raeburn  11498: sub additional_machine_domains {
                   11499:     my @domains;
                   11500:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11501:     while( my $line = <$fh>) {
                   11502:         $line =~ s/\s//g;
                   11503:         push(@domains,$line);
                   11504:     }
                   11505:     return @domains;
                   11506: }
                   11507: 
                   11508: sub default_login_domain {
                   11509:     my $domain = $perlvar{'lonDefDomain'};
                   11510:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11511:     foreach my $posdom (&current_machine_domains(),
                   11512:                         &additional_machine_domains()) {
                   11513:         if (lc($posdom) eq lc($testdomain)) {
                   11514:             $domain=$posdom;
                   11515:             last;
                   11516:         }
                   11517:     }
                   11518:     return $domain;
                   11519: }
                   11520: 
1.31      www      11521: # ------------------------------------------------------------- Declutters URLs
                   11522: 
                   11523: sub declutter {
                   11524:     my $thisfn=shift;
1.569     albertel 11525:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11526:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11527:     $thisfn=~s/^\///;
1.697     albertel 11528:     $thisfn=~s|^adm/wrapper/||;
                   11529:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11530:     $thisfn=~s/^res\///;
1.1172    bisitz   11531:     $thisfn=~s/^priv\///;
1.1032    raeburn  11532:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11533:         $thisfn=~s/\?.+$//;
                   11534:     }
1.268     www      11535:     return $thisfn;
                   11536: }
                   11537: 
                   11538: # ------------------------------------------------------------- Clutter up URLs
                   11539: 
                   11540: sub clutter {
                   11541:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11542:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11543: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11544:        $thisfn='/res'.$thisfn; 
                   11545:     }
1.1031    raeburn  11546:     if ($thisfn !~m|^/adm|) {
                   11547: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11548: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11549: 	} else {
                   11550: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11551: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11552: 	    if ($embstyle eq 'ssi'
                   11553: 		|| ($embstyle eq 'hdn')
                   11554: 		|| ($embstyle eq 'rat')
                   11555: 		|| ($embstyle eq 'prv')
                   11556: 		|| ($embstyle eq 'ign')) {
                   11557: 		#do nothing with these
                   11558: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11559: 		|| ($embstyle eq 'emb')
                   11560: 		|| ($embstyle eq 'wrp')) {
                   11561: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11562: 	    } elsif ($embstyle eq 'unk'
                   11563: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11564: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11565: 	    } else {
1.718     www      11566: #		&logthis("Got a blank emb style");
1.695     albertel 11567: 	    }
1.694     albertel 11568: 	}
                   11569:     }
1.31      www      11570:     return $thisfn;
1.12      www      11571: }
                   11572: 
1.787     albertel 11573: sub clutter_with_no_wrapper {
                   11574:     my $uri = &clutter(shift);
                   11575:     if ($uri =~ m-^/adm/-) {
                   11576: 	$uri =~ s-^/adm/wrapper/-/-;
                   11577: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11578:     }
                   11579:     return $uri;
                   11580: }
                   11581: 
1.557     albertel 11582: sub freeze_escape {
                   11583:     my ($value)=@_;
                   11584:     if (ref($value)) {
                   11585: 	$value=&nfreeze($value);
                   11586: 	return '__FROZEN__'.&escape($value);
                   11587:     }
                   11588:     return &escape($value);
                   11589: }
                   11590: 
1.11      www      11591: 
1.557     albertel 11592: sub thaw_unescape {
                   11593:     my ($value)=@_;
                   11594:     if ($value =~ /^__FROZEN__/) {
                   11595: 	substr($value,0,10,undef);
                   11596: 	$value=&unescape($value);
                   11597: 	return &thaw($value);
                   11598:     }
                   11599:     return &unescape($value);
                   11600: }
                   11601: 
1.436     albertel 11602: sub correct_line_ends {
                   11603:     my ($result)=@_;
                   11604:     $$result =~s/\r\n/\n/mg;
                   11605:     $$result =~s/\r/\n/mg;
1.415     albertel 11606: }
1.1       albertel 11607: # ================================================================ Main Program
                   11608: 
1.184     www      11609: sub goodbye {
1.204     albertel 11610:    &logthis("Starting Shut down");
1.443     albertel 11611: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11612:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11613: #converted
1.599     albertel 11614: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11615:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11616: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11617: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11618: #1.1 only
1.870     albertel 11619: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11620: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11621: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11622: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11623:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11624:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11625:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11626:    &flushcourselogs();
                   11627:    &logthis("Shutting down");
                   11628: }
                   11629: 
1.852     albertel 11630: sub get_dns {
1.1210    raeburn  11631:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11632:     if (!$ignore_cache) {
                   11633: 	my ($content,$cached)=
                   11634: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11635: 	if ($cached) {
1.1210    raeburn  11636: 	    &$func($content,$hashref);
1.869     albertel 11637: 	    return;
                   11638: 	}
                   11639:     }
                   11640: 
                   11641:     my %alldns;
1.852     albertel 11642:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11643:     foreach my $dns (<$config>) {
                   11644: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11645:         my $line = $1;
                   11646:         my ($host,$protocol) = split(/:/,$line);
                   11647:         if ($protocol ne 'https') {
                   11648:             $protocol = 'http';
                   11649:         }
                   11650: 	$alldns{$host} = $protocol;
1.869     albertel 11651:     }
                   11652:     while (%alldns) {
                   11653: 	my ($dns) = keys(%alldns);
1.852     albertel 11654: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11655:         $ua->timeout(30);
1.979     raeburn  11656: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11657: 	my $response=$ua->request($request);
1.979     raeburn  11658:         delete($alldns{$dns});
1.852     albertel 11659: 	next if ($response->is_error());
                   11660: 	my @content = split("\n",$response->content);
1.1210    raeburn  11661: 	unless ($nocache) {
1.1219    raeburn  11662: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  11663: 	}
                   11664: 	&$func(\@content,$hashref);
1.869     albertel 11665: 	return;
1.852     albertel 11666:     }
                   11667:     close($config);
1.871     albertel 11668:     my $which = (split('/',$url))[3];
                   11669:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11670:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11671:     my @content = <$config>;
1.1210    raeburn  11672:     &$func(\@content,$hashref);
                   11673:     return;
                   11674: }
                   11675: 
                   11676: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11677: sub parse_dns_checksums_tab {
1.1210    raeburn  11678:     my ($lines,$hashref) = @_;
                   11679:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11680:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11681:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11682:     my (%chksum,%revnum);
                   11683:     if (ref($lines) eq 'ARRAY') {
                   11684:         chomp(@{$lines});
                   11685:         my $versions = shift(@{$lines});
                   11686:         my %supported;
                   11687:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11688:             my $releaseslist = $1;
                   11689:             if ($releaseslist =~ /,/) {
                   11690:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11691:             } elsif ($releaseslist) {
                   11692:                 $supported{$releaseslist} = 1;
                   11693:             }
                   11694:         }
                   11695:         if ($supported{$release}) {  
                   11696:             my $matchthis = 0;
                   11697:             foreach my $line (@{$lines}) {
                   11698:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11699:                     if ($matchthis) {
                   11700:                         last;
                   11701:                     } elsif ($1 eq $release) {
                   11702:                         $matchthis = 1;
                   11703:                     }
                   11704:                 } elsif ($matchthis) {
                   11705:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11706:                     $chksum{$file} = $shasum;
                   11707:                     $revnum{$file} = $version;
                   11708:                 }
                   11709:             }
                   11710:             if (ref($hashref) eq 'HASH') {
                   11711:                 %{$hashref} = (
                   11712:                                 sums     => \%chksum,
                   11713:                                 versions => \%revnum,
                   11714:                               );
                   11715:             }
                   11716:         }
                   11717:     }
1.869     albertel 11718:     return;
1.852     albertel 11719: }
1.1210    raeburn  11720: 
                   11721: sub fetch_dns_checksums {
                   11722:     my %checksums; 
1.1211    raeburn  11723:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11724:              \%checksums);
1.1210    raeburn  11725:     return \%checksums;
                   11726: }
                   11727: 
1.327     albertel 11728: # ------------------------------------------------------------ Read domain file
                   11729: {
1.852     albertel 11730:     my $loaded;
1.846     albertel 11731:     my %domain;
                   11732: 
1.852     albertel 11733:     sub parse_domain_tab {
                   11734: 	my ($lines) = @_;
                   11735: 	foreach my $line (@$lines) {
                   11736: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11737: 
1.846     albertel 11738: 	    chomp($line);
1.852     albertel 11739: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11740: 	    my %this_domain;
                   11741: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11742: 			       'lang_def', 'city', 'longi', 'lati',
                   11743: 			       'primary') {
                   11744: 		$this_domain{$field} = shift(@elements);
                   11745: 	    }
                   11746: 	    $domain{$name} = \%this_domain;
1.852     albertel 11747: 	}
                   11748:     }
1.864     albertel 11749: 
                   11750:     sub reset_domain_info {
                   11751: 	undef($loaded);
                   11752: 	undef(%domain);
                   11753:     }
                   11754: 
1.852     albertel 11755:     sub load_domain_tab {
1.869     albertel 11756: 	my ($ignore_cache) = @_;
                   11757: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11758: 	my $fh;
                   11759: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11760: 	    my @lines = <$fh>;
                   11761: 	    &parse_domain_tab(\@lines);
1.448     albertel 11762: 	}
1.852     albertel 11763: 	close($fh);
                   11764: 	$loaded = 1;
1.327     albertel 11765:     }
1.846     albertel 11766: 
                   11767:     sub domain {
1.852     albertel 11768: 	&load_domain_tab() if (!$loaded);
                   11769: 
1.846     albertel 11770: 	my ($name,$what) = @_;
                   11771: 	return if ( !exists($domain{$name}) );
                   11772: 
                   11773: 	if (!$what) {
                   11774: 	    return $domain{$name}{'description'};
                   11775: 	}
                   11776: 	return $domain{$name}{$what};
                   11777:     }
1.974     raeburn  11778: 
                   11779:     sub domain_info {
                   11780:         &load_domain_tab() if (!$loaded);
                   11781:         return %domain;
                   11782:     }
                   11783: 
1.327     albertel 11784: }
                   11785: 
                   11786: 
1.1       albertel 11787: # ------------------------------------------------------------- Read hosts file
                   11788: {
1.838     albertel 11789:     my %hostname;
1.844     albertel 11790:     my %hostdom;
1.845     albertel 11791:     my %libserv;
1.852     albertel 11792:     my $loaded;
1.888     albertel 11793:     my %name_to_host;
1.1074    raeburn  11794:     my %internetdom;
1.1107    raeburn  11795:     my %LC_dns_serv;
1.852     albertel 11796: 
                   11797:     sub parse_hosts_tab {
                   11798: 	my ($file) = @_;
                   11799: 	foreach my $configline (@$file) {
                   11800: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11801:             chomp($configline);
                   11802: 	    if ($configline =~ /^\^/) {
                   11803:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11804:                     $LC_dns_serv{$1} = 1;
                   11805:                 }
                   11806:                 next;
                   11807:             }
1.1074    raeburn  11808: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11809: 	    $name=~s/\s//g;
                   11810: 	    if ($id && $domain && $role && $name) {
                   11811: 		$hostname{$id}=$name;
1.888     albertel 11812: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11813: 		$hostdom{$id}=$domain;
                   11814: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11815:                 if (defined($protocol)) {
                   11816:                     if ($protocol eq 'https') {
                   11817:                         $protocol{$id} = $protocol;
                   11818:                     } else {
                   11819:                         $protocol{$id} = 'http'; 
                   11820:                     }
1.968     raeburn  11821:                 } else {
1.969     raeburn  11822:                     $protocol{$id} = 'http';
1.968     raeburn  11823:                 }
1.1074    raeburn  11824:                 if (defined($intdom)) {
                   11825:                     $internetdom{$id} = $intdom;
                   11826:                 }
1.852     albertel 11827: 	    }
                   11828: 	}
                   11829:     }
1.864     albertel 11830:     
                   11831:     sub reset_hosts_info {
1.897     albertel 11832: 	&purge_remembered();
1.864     albertel 11833: 	&reset_domain_info();
                   11834: 	&reset_hosts_ip_info();
1.892     albertel 11835: 	undef(%name_to_host);
1.864     albertel 11836: 	undef(%hostname);
                   11837: 	undef(%hostdom);
                   11838: 	undef(%libserv);
                   11839: 	undef($loaded);
                   11840:     }
1.1       albertel 11841: 
1.852     albertel 11842:     sub load_hosts_tab {
1.869     albertel 11843: 	my ($ignore_cache) = @_;
                   11844: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11845: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11846: 	my @config = <$config>;
                   11847: 	&parse_hosts_tab(\@config);
                   11848: 	close($config);
                   11849: 	$loaded=1;
1.1       albertel 11850:     }
1.852     albertel 11851: 
1.838     albertel 11852:     sub hostname {
1.852     albertel 11853: 	&load_hosts_tab() if (!$loaded);
                   11854: 
1.838     albertel 11855: 	my ($lonid) = @_;
                   11856: 	return $hostname{$lonid};
                   11857:     }
1.845     albertel 11858: 
1.838     albertel 11859:     sub all_hostnames {
1.852     albertel 11860: 	&load_hosts_tab() if (!$loaded);
                   11861: 
1.838     albertel 11862: 	return %hostname;
                   11863:     }
1.845     albertel 11864: 
1.888     albertel 11865:     sub all_names {
                   11866: 	&load_hosts_tab() if (!$loaded);
                   11867: 
                   11868: 	return %name_to_host;
                   11869:     }
                   11870: 
1.974     raeburn  11871:     sub all_host_domain {
                   11872:         &load_hosts_tab() if (!$loaded);
                   11873:         return %hostdom;
                   11874:     }
                   11875: 
1.845     albertel 11876:     sub is_library {
1.852     albertel 11877: 	&load_hosts_tab() if (!$loaded);
                   11878: 
1.845     albertel 11879: 	return exists($libserv{$_[0]});
                   11880:     }
                   11881: 
                   11882:     sub all_library {
1.852     albertel 11883: 	&load_hosts_tab() if (!$loaded);
                   11884: 
1.845     albertel 11885: 	return %libserv;
                   11886:     }
                   11887: 
1.1062    droeschl 11888:     sub unique_library {
                   11889: 	#2x reverse removes all hostnames that appear more than once
                   11890:         my %unique = reverse &all_library();
                   11891:         return reverse %unique;
                   11892:     }
                   11893: 
1.841     albertel 11894:     sub get_servers {
1.852     albertel 11895: 	&load_hosts_tab() if (!$loaded);
                   11896: 
1.841     albertel 11897: 	my ($domain,$type) = @_;
                   11898: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11899: 	                                          : %hostname;
                   11900: 	my %result;
1.842     albertel 11901: 	if (ref($domain) eq 'ARRAY') {
                   11902: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11903: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11904: 		    $result{$host} = $hostname;
                   11905: 		}
                   11906: 	    }
                   11907: 	} else {
                   11908: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11909: 		if ($hostdom{$host} eq $domain) {
                   11910: 		    $result{$host} = $hostname;
                   11911: 		}
1.841     albertel 11912: 	    }
                   11913: 	}
                   11914: 	return %result;
                   11915:     }
1.845     albertel 11916: 
1.1062    droeschl 11917:     sub get_unique_servers {
                   11918:         my %unique = reverse &get_servers(@_);
                   11919: 	return reverse %unique;
                   11920:     }
                   11921: 
1.844     albertel 11922:     sub host_domain {
1.852     albertel 11923: 	&load_hosts_tab() if (!$loaded);
                   11924: 
1.844     albertel 11925: 	my ($lonid) = @_;
                   11926: 	return $hostdom{$lonid};
                   11927:     }
                   11928: 
1.841     albertel 11929:     sub all_domains {
1.852     albertel 11930: 	&load_hosts_tab() if (!$loaded);
                   11931: 
1.841     albertel 11932: 	my %seen;
                   11933: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11934: 	return @uniq;
                   11935:     }
1.1074    raeburn  11936: 
                   11937:     sub internet_dom {
                   11938:         &load_hosts_tab() if (!$loaded);
                   11939: 
                   11940:         my ($lonid) = @_;
                   11941:         return $internetdom{$lonid};
                   11942:     }
1.1107    raeburn  11943: 
                   11944:     sub is_LC_dns {
                   11945:         &load_hosts_tab() if (!$loaded);
                   11946: 
                   11947:         my ($hostname) = @_;
                   11948:         return exists($LC_dns_serv{$hostname});
                   11949:     }
                   11950: 
1.1       albertel 11951: }
                   11952: 
1.847     albertel 11953: { 
                   11954:     my %iphost;
1.856     albertel 11955:     my %name_to_ip;
                   11956:     my %lonid_to_ip;
1.869     albertel 11957: 
1.847     albertel 11958:     sub get_hosts_from_ip {
                   11959: 	my ($ip) = @_;
                   11960: 	my %iphosts = &get_iphost();
                   11961: 	if (ref($iphosts{$ip})) {
                   11962: 	    return @{$iphosts{$ip}};
                   11963: 	}
                   11964: 	return;
1.839     albertel 11965:     }
1.864     albertel 11966:     
                   11967:     sub reset_hosts_ip_info {
                   11968: 	undef(%iphost);
                   11969: 	undef(%name_to_ip);
                   11970: 	undef(%lonid_to_ip);
                   11971:     }
1.856     albertel 11972: 
                   11973:     sub get_host_ip {
                   11974: 	my ($lonid) = @_;
                   11975: 	if (exists($lonid_to_ip{$lonid})) {
                   11976: 	    return $lonid_to_ip{$lonid};
                   11977: 	}
                   11978: 	my $name=&hostname($lonid);
                   11979:    	my $ip = gethostbyname($name);
                   11980: 	return if (!$ip || length($ip) ne 4);
                   11981: 	$ip=inet_ntoa($ip);
                   11982: 	$name_to_ip{$name}   = $ip;
                   11983: 	$lonid_to_ip{$lonid} = $ip;
                   11984: 	return $ip;
                   11985:     }
1.847     albertel 11986:     
                   11987:     sub get_iphost {
1.869     albertel 11988: 	my ($ignore_cache) = @_;
1.894     albertel 11989: 
1.869     albertel 11990: 	if (!$ignore_cache) {
                   11991: 	    if (%iphost) {
                   11992: 		return %iphost;
                   11993: 	    }
                   11994: 	    my ($ip_info,$cached)=
                   11995: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11996: 	    if ($cached) {
                   11997: 		%iphost      = %{$ip_info->[0]};
                   11998: 		%name_to_ip  = %{$ip_info->[1]};
                   11999: 		%lonid_to_ip = %{$ip_info->[2]};
                   12000: 		return %iphost;
                   12001: 	    }
                   12002: 	}
1.894     albertel 12003: 
                   12004: 	# get yesterday's info for fallback
                   12005: 	my %old_name_to_ip;
                   12006: 	my ($ip_info,$cached)=
                   12007: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12008: 	if ($cached) {
                   12009: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12010: 	}
                   12011: 
1.888     albertel 12012: 	my %name_to_host = &all_names();
                   12013: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12014: 	    my $ip;
                   12015: 	    if (!exists($name_to_ip{$name})) {
                   12016: 		$ip = gethostbyname($name);
                   12017: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12018: 		    if (defined($old_name_to_ip{$name})) {
                   12019: 			$ip = $old_name_to_ip{$name};
                   12020: 			&logthis("Can't find $name defaulting to old $ip");
                   12021: 		    } else {
                   12022: 			&logthis("Name $name no IP found");
                   12023: 			next;
                   12024: 		    }
                   12025: 		} else {
                   12026: 		    $ip=inet_ntoa($ip);
1.847     albertel 12027: 		}
                   12028: 		$name_to_ip{$name} = $ip;
                   12029: 	    } else {
                   12030: 		$ip = $name_to_ip{$name};
1.653     albertel 12031: 	    }
1.888     albertel 12032: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12033: 		$lonid_to_ip{$id} = $ip;
                   12034: 	    }
                   12035: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12036: 	}
1.1219    raeburn  12037: 	&do_cache_new('iphost','iphost',
                   12038: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12039: 		      48*60*60);
1.869     albertel 12040: 
1.847     albertel 12041: 	return %iphost;
1.598     albertel 12042:     }
                   12043: 
1.992     raeburn  12044:     #
                   12045:     #  Given a DNS returns the loncapa host name for that DNS 
                   12046:     # 
                   12047:     sub host_from_dns {
                   12048:         my ($dns) = @_;
                   12049:         my @hosts;
                   12050:         my $ip;
                   12051: 
1.993     raeburn  12052:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12053:             $ip = $name_to_ip{$dns};
                   12054:         }
                   12055:         if (!$ip) {
                   12056:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12057:             if (length($ip) == 4) { 
                   12058: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12059:             }
                   12060:         }
                   12061:         if ($ip) {
                   12062: 	    @hosts = get_hosts_from_ip($ip);
                   12063: 	    return $hosts[0];
                   12064:         }
                   12065:         return undef;
1.986     foxr     12066:     }
1.992     raeburn  12067: 
1.1074    raeburn  12068:     sub get_internet_names {
                   12069:         my ($lonid) = @_;
                   12070:         return if ($lonid eq '');
                   12071:         my ($idnref,$cached)=
                   12072:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12073:         if ($cached) {
                   12074:             return $idnref;
                   12075:         }
                   12076:         my $ip = &get_host_ip($lonid);
                   12077:         my @hosts = &get_hosts_from_ip($ip);
                   12078:         my %iphost = &get_iphost();
                   12079:         my (@idns,%seen);
                   12080:         foreach my $id (@hosts) {
                   12081:             my $dom = &host_domain($id);
                   12082:             my $prim_id = &domain($dom,'primary');
                   12083:             my $prim_ip = &get_host_ip($prim_id);
                   12084:             next if ($seen{$prim_ip});
                   12085:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12086:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12087:                     my $intdom = &internet_dom($id);
                   12088:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12089:                         push(@idns,$intdom);
                   12090:                     }
                   12091:                 }
                   12092:             }
                   12093:             $seen{$prim_ip} = 1;
                   12094:         }
1.1219    raeburn  12095:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12096:     }
                   12097: 
1.986     foxr     12098: }
                   12099: 
1.1079    raeburn  12100: sub all_loncaparevs {
                   12101:     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);
                   12102: }
                   12103: 
1.862     albertel 12104: BEGIN {
                   12105: 
                   12106: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12107:     unless ($readit) {
                   12108: {
                   12109:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12110:     %perlvar = (%perlvar,%{$configvars});
                   12111: }
                   12112: 
                   12113: 
1.1       albertel 12114: # ------------------------------------------------------ Read spare server file
                   12115: {
1.448     albertel 12116:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12117: 
                   12118:     while (my $configline=<$config>) {
                   12119:        chomp($configline);
1.284     matthew  12120:        if ($configline) {
1.784     albertel 12121: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12122: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12123: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12124:        }
                   12125:     }
1.448     albertel 12126:     close($config);
1.1       albertel 12127: }
1.11      www      12128: # ------------------------------------------------------------ Read permissions
                   12129: {
1.448     albertel 12130:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12131: 
                   12132:     while (my $configline=<$config>) {
1.448     albertel 12133: 	chomp($configline);
                   12134: 	if ($configline) {
                   12135: 	    my ($role,$perm)=split(/ /,$configline);
                   12136: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12137: 	}
1.11      www      12138:     }
1.448     albertel 12139:     close($config);
1.11      www      12140: }
                   12141: 
                   12142: # -------------------------------------------- Read plain texts for permissions
                   12143: {
1.448     albertel 12144:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12145: 
                   12146:     while (my $configline=<$config>) {
1.448     albertel 12147: 	chomp($configline);
                   12148: 	if ($configline) {
1.742     raeburn  12149: 	    my ($short,@plain)=split(/:/,$configline);
                   12150:             %{$prp{$short}} = ();
                   12151: 	    if (@plain > 0) {
                   12152:                 $prp{$short}{'std'} = $plain[0];
                   12153:                 for (my $i=1; $i<@plain; $i++) {
                   12154:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12155:                 }
                   12156:             }
1.448     albertel 12157: 	}
1.135     www      12158:     }
1.448     albertel 12159:     close($config);
1.135     www      12160: }
                   12161: 
                   12162: # ---------------------------------------------------------- Read package table
                   12163: {
1.448     albertel 12164:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12165: 
                   12166:     while (my $configline=<$config>) {
1.483     albertel 12167: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12168: 	chomp($configline);
                   12169: 	my ($short,$plain)=split(/:/,$configline);
                   12170: 	my ($pack,$name)=split(/\&/,$short);
                   12171: 	if ($plain ne '') {
                   12172: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12173: 	    $packagetab{$short}=$plain; 
                   12174: 	}
1.11      www      12175:     }
1.448     albertel 12176:     close($config);
1.329     matthew  12177: }
                   12178: 
1.1073    raeburn  12179: # ---------------------------------------------------------- Read loncaparev table
                   12180: {
                   12181:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12182:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12183:             while (my $configline=<$config>) {
                   12184:                 chomp($configline);
                   12185:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12186:                 $loncaparevs{$hostid}=$loncaparev;
                   12187:             }
                   12188:             close($config);
                   12189:         }
                   12190:     }
                   12191: }
                   12192: 
1.1074    raeburn  12193: # ---------------------------------------------------------- Read serverhostID table
                   12194: {
                   12195:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12196:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12197:             while (my $configline=<$config>) {
                   12198:                 chomp($configline);
                   12199:                 my ($name,$id)=split(/:/,$configline);
                   12200:                 $serverhomeIDs{$name}=$id;
                   12201:             }
                   12202:             close($config);
                   12203:         }
                   12204:     }
                   12205: }
                   12206: 
1.1079    raeburn  12207: {
                   12208:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12209:     if (-e $file) {
                   12210:         my $parser = HTML::LCParser->new($file);
                   12211:         while (my $token = $parser->get_token()) {
                   12212:             if ($token->[0] eq 'S') {
                   12213:                 my $item = $token->[1];
                   12214:                 my $name = $token->[2]{'name'};
                   12215:                 my $value = $token->[2]{'value'};
                   12216:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12217:                     my $release = $parser->get_text();
                   12218:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12219:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12220:                 }
                   12221:             }
                   12222:         }
                   12223:     }
1.1073    raeburn  12224: }
                   12225: 
1.1138    raeburn  12226: # ---------------------------------------------------------- Read managers table
                   12227: {
                   12228:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12229:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12230:             while (my $configline=<$config>) {
                   12231:                 chomp($configline);
                   12232:                 next if ($configline =~ /^\#/);
                   12233:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12234:                     $managerstab{$configline} = 1;
                   12235:                 }
                   12236:             }
                   12237:             close($config);
                   12238:         }
                   12239:     }
                   12240: }
                   12241: 
1.329     matthew  12242: # ------------- set up temporary directory
                   12243: {
1.1117    foxr     12244:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12245: 
1.11      www      12246: }
                   12247: 
1.794     albertel 12248: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12249: 				'compress_threshold'=> 20_000,
                   12250:  			        });
1.185     www      12251: 
1.281     www      12252: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12253: $dumpcount=0;
1.958     www      12254: $locknum=0;
1.22      www      12255: 
1.163     harris41 12256: &logtouch();
1.672     albertel 12257: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12258: $readit=1;
1.564     albertel 12259:     {
                   12260: 	use integer;
                   12261: 	my $test=(2**32)+1;
1.568     albertel 12262: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12263: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12264:     }
1.1214    raeburn  12265: 
                   12266:     {
                   12267:         eval {
                   12268:             ($apache) =
                   12269:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12270:         };
                   12271:         if ($@) {
                   12272:            $apache = 1.3;
1.1213    raeburn  12273:         }
                   12274:     }
1.1214    raeburn  12275: 
1.195     www      12276: }
1.1       albertel 12277: }
1.179     www      12278: 
1.1       albertel 12279: 1;
1.191     harris41 12280: __END__
                   12281: 
1.243     albertel 12282: =pod
                   12283: 
1.191     harris41 12284: =head1 NAME
                   12285: 
1.243     albertel 12286: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12287: 
                   12288: =head1 SYNOPSIS
                   12289: 
1.243     albertel 12290: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12291: 
                   12292:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12293: 
1.243     albertel 12294: Common parameters:
                   12295: 
                   12296: =over 4
                   12297: 
                   12298: =item *
                   12299: 
                   12300: $uname : an internal username (if $cname expecting a course Id specifically)
                   12301: 
                   12302: =item *
                   12303: 
                   12304: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12305: 
                   12306: =item *
                   12307: 
                   12308: $symb : a resource instance identifier
                   12309: 
                   12310: =item *
                   12311: 
                   12312: $namespace : the name of a .db file that contains the data needed or
                   12313: being set.
                   12314: 
                   12315: =back
                   12316: 
1.394     bowersj2 12317: =head1 OVERVIEW
1.191     harris41 12318: 
1.394     bowersj2 12319: lonnet provides subroutines which interact with the
                   12320: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12321: about classes, users, and resources.
1.243     albertel 12322: 
                   12323: For many of these objects you can also use this to store data about
                   12324: them or modify them in various ways.
1.191     harris41 12325: 
1.394     bowersj2 12326: =head2 Symbs
1.191     harris41 12327: 
1.394     bowersj2 12328: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12329: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12330: map, the resource number of the resource in the map, and the URL of
                   12331: the resource itself. The latter is somewhat redundant, but might help
                   12332: if maps change.
                   12333: 
                   12334: An example is
                   12335: 
                   12336:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12337: 
                   12338: The respective map entry is
                   12339: 
                   12340:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12341:   title="Problem 2">
                   12342:  </resource>
                   12343: 
                   12344: Symbs are used by the random number generator, as well as to store and
                   12345: restore data specific to a certain instance of for example a problem.
                   12346: 
                   12347: =head2 Storing And Retrieving Data
                   12348: 
                   12349: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12350: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12351: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12352: is is the non-critical message twin of cstore. These functions are for
                   12353: handlers to store a perl hash to a user's permanent data space in an
                   12354: easy manner, and to retrieve it again on another call. It is expected
                   12355: that a handler would use this once at the beginning to retrieve data,
                   12356: and then again once at the end to send only the new data back.
                   12357: 
                   12358: The data is stored in the user's data directory on the user's
                   12359: homeserver under the ID of the course.
                   12360: 
                   12361: The hash that is returned by restore will have all of the previous
                   12362: value for all of the elements of the hash.
                   12363: 
                   12364: Example:
                   12365: 
                   12366:  #creating a hash
                   12367:  my %hash;
                   12368:  $hash{'foo'}='bar';
                   12369: 
                   12370:  #storing it
                   12371:  &Apache::lonnet::cstore(\%hash);
                   12372: 
                   12373:  #changing a value
                   12374:  $hash{'foo'}='notbar';
                   12375: 
                   12376:  #adding a new value
                   12377:  $hash{'bar'}='foo';
                   12378:  &Apache::lonnet::cstore(\%hash);
                   12379: 
                   12380:  #retrieving the hash
                   12381:  my %history=&Apache::lonnet::restore();
                   12382: 
                   12383:  #print the hash
                   12384:  foreach my $key (sort(keys(%history))) {
                   12385:    print("\%history{$key} = $history{$key}");
                   12386:  }
                   12387: 
                   12388: Will print out:
1.191     harris41 12389: 
1.394     bowersj2 12390:  %history{1:foo} = bar
                   12391:  %history{1:keys} = foo:timestamp
                   12392:  %history{1:timestamp} = 990455579
                   12393:  %history{2:bar} = foo
                   12394:  %history{2:foo} = notbar
                   12395:  %history{2:keys} = foo:bar:timestamp
                   12396:  %history{2:timestamp} = 990455580
                   12397:  %history{bar} = foo
                   12398:  %history{foo} = notbar
                   12399:  %history{timestamp} = 990455580
                   12400:  %history{version} = 2
                   12401: 
                   12402: Note that the special hash entries C<keys>, C<version> and
                   12403: C<timestamp> were added to the hash. C<version> will be equal to the
                   12404: total number of versions of the data that have been stored. The
                   12405: C<timestamp> attribute will be the UNIX time the hash was
                   12406: stored. C<keys> is available in every historical section to list which
                   12407: keys were added or changed at a specific historical revision of a
                   12408: hash.
                   12409: 
                   12410: B<Warning>: do not store the hash that restore returns directly. This
                   12411: will cause a mess since it will restore the historical keys as if the
                   12412: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12413: 
1.394     bowersj2 12414: Calling convention:
1.191     harris41 12415: 
1.394     bowersj2 12416:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12417:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12418: 
1.394     bowersj2 12419: For more detailed information, see lonnet specific documentation.
1.191     harris41 12420: 
1.394     bowersj2 12421: =head1 RETURN MESSAGES
1.191     harris41 12422: 
1.394     bowersj2 12423: =over 4
1.191     harris41 12424: 
1.394     bowersj2 12425: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12426: 
1.394     bowersj2 12427: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12428: when the connection is brought back up
1.191     harris41 12429: 
1.394     bowersj2 12430: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12431: for later delivery
1.191     harris41 12432: 
1.967     bisitz   12433: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12434: 
1.394     bowersj2 12435: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12436: that was requested
1.191     harris41 12437: 
1.243     albertel 12438: =back
1.191     harris41 12439: 
1.243     albertel 12440: =head1 PUBLIC SUBROUTINES
1.191     harris41 12441: 
1.243     albertel 12442: =head2 Session Environment Functions
1.191     harris41 12443: 
1.243     albertel 12444: =over 4
1.191     harris41 12445: 
1.394     bowersj2 12446: =item * 
                   12447: X<appenv()>
1.949     raeburn  12448: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12449: the user envirnoment file, and will be restored for each access this
1.620     albertel 12450: user makes during this session, also modifies the %env for the current
1.949     raeburn  12451: process. Optional rolesarrayref - if defined contains a reference to an array
                   12452: of roles which are exempt from the restriction on modifying user.role entries 
                   12453: in the user's environment.db and in %env.    
1.191     harris41 12454: 
                   12455: =item *
1.394     bowersj2 12456: X<delenv()>
1.987     raeburn  12457: B<delenv($delthis,$regexp)>: removes all items from the session
                   12458: environment file that begin with $delthis. If the 
                   12459: optional second arg - $regexp - is true, $delthis is treated as a 
                   12460: regular expression, otherwise \Q$delthis\E is used. 
                   12461: The values are also deleted from the current processes %env.
1.191     harris41 12462: 
1.795     albertel 12463: =item * get_env_multiple($name) 
                   12464: 
                   12465: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12466: values may be defined and end up as an array ref.
                   12467: 
                   12468: returns an array of values
                   12469: 
1.243     albertel 12470: =back
                   12471: 
                   12472: =head2 User Information
1.191     harris41 12473: 
1.243     albertel 12474: =over 4
1.191     harris41 12475: 
                   12476: =item *
1.394     bowersj2 12477: X<queryauthenticate()>
                   12478: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12479: authentication scheme
                   12480: 
                   12481: =item *
1.394     bowersj2 12482: X<authenticate()>
1.1073    raeburn  12483: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12484: authenticate user from domain's lib servers (first use the current
                   12485: one). C<$upass> should be the users password.
1.1073    raeburn  12486: $checkdefauth is optional (value is 1 if a check should be made to
                   12487:    authenticate user using default authentication method, and allow
                   12488:    account creation if username does not have account in the domain).
                   12489: $clientcancheckhost is optional (value is 1 if checking whether the
                   12490:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12491: 
                   12492: =item *
1.394     bowersj2 12493: X<homeserver()>
                   12494: B<homeserver($uname,$udom)>: find the server which has
                   12495: the user's directory and files (there must be only one), this caches
                   12496: the answer, and also caches if there is a borken connection.
1.191     harris41 12497: 
                   12498: =item *
1.394     bowersj2 12499: X<idget()>
                   12500: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12501: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12502: username, and only 1 username per ID in a specific domain) (returns
                   12503: hash: id=>name,id=>name)
1.191     harris41 12504: 
                   12505: =item *
1.394     bowersj2 12506: X<idrget()>
                   12507: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12508: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12509: 
                   12510: =item *
1.394     bowersj2 12511: X<idput()>
                   12512: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12513: 
                   12514: =item *
1.394     bowersj2 12515: X<rolesinit()>
1.1169    droeschl 12516: B<rolesinit($udom,$username)>: get user privileges.
                   12517: returns user role, first access and timer interval hashes
1.243     albertel 12518: 
                   12519: =item *
1.1171    droeschl 12520: X<privileged()>
                   12521: B<privileged($username,$domain)>: returns a true if user has a
                   12522: privileged and active role (i.e. su or dc), false otherwise.
                   12523: 
                   12524: =item *
1.551     albertel 12525: X<getsection()>
                   12526: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12527: course $cname, return section name/number or '' for "not in course"
                   12528: and '-1' for "no section"
                   12529: 
                   12530: =item *
1.394     bowersj2 12531: X<userenvironment()>
                   12532: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12533: passed in @what from the requested user's environment, returns a hash
                   12534: 
1.858     raeburn  12535: =item * 
                   12536: X<userlog_query()>
1.859     albertel 12537: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12538: activity.log file. %filters defines filters applied when parsing the
                   12539: log file. These can be start or end timestamps, or the type of action
                   12540: - log to look for Login or Logout events, check for Checkin or
                   12541: Checkout, role for role selection. The response is in the form
                   12542: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12543: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12544: 
1.243     albertel 12545: =back
                   12546: 
                   12547: =head2 User Roles
                   12548: 
                   12549: =over 4
                   12550: 
                   12551: =item *
                   12552: 
1.810     raeburn  12553: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12554:  F: full access
                   12555:  U,I,K: authentication modes (cxx only)
                   12556:  '': forbidden
                   12557:  1: user needs to choose course
                   12558:  2: browse allowed
1.766     albertel 12559:  A: passphrase authentication needed
1.243     albertel 12560: 
                   12561: =item *
                   12562: 
1.1192    raeburn  12563: constructaccess($url,$setpriv) : check for access to construction space URL
                   12564: 
                   12565: See if the owner domain and name in the URL match those in the
                   12566: expected environment.  If so, return three element list
                   12567: ($ownername,$ownerdomain,$ownerhome).
                   12568: 
                   12569: Otherwise return the null string.
                   12570: 
                   12571: If second argument 'setpriv' is true, it assigns the privileges,
                   12572: and returns the same three element list, unless the owner has
                   12573: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12574: in which case the null string is returned.
                   12575: 
                   12576: =item *
                   12577: 
1.243     albertel 12578: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12579: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12580: and course level
                   12581: 
                   12582: =item *
                   12583: 
1.988     raeburn  12584: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12585: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12586: $type is Course (default) or Community.
1.988     raeburn  12587: If $forcedefault evaluates to true, text returned will be default 
                   12588: text for $type. Otherwise, if this is a course, the text returned 
                   12589: will be a custom name for the role (if defined in the course's 
                   12590: environment).  If no custom name is defined the default is returned.
                   12591:    
1.832     raeburn  12592: =item *
                   12593: 
1.1219    raeburn  12594: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12595: All arguments are optional. Returns a hash of a roles, either for
                   12596: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12597: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12598: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12599: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12600: For each key, value is set to colon-separated start and end times for
                   12601: the role.  If no username and domain are specified, will default to
1.934     raeburn  12602: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12603: of role statuses (active, future or previous), roles 
                   12604: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12605: to restrict the list of roles reported. If no array ref is 
                   12606: provided for types, will default to return only active roles.
1.834     albertel 12607: 
1.1195    raeburn  12608: =item *
                   12609: 
                   12610: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12611: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12612: 
                   12613: Additional optional arguments are: $type (if role checking is to be restricted 
                   12614: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12615: available roles) or future (roles available in the future), and
                   12616: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  12617: have active Domain Coordinator role in course's domain or in additional
                   12618: domains (specified in 'Domains to check for privileged users' in course
                   12619: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12620: 
                   12621: =item *
                   12622: 
                   12623: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12624: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12625: $possdomains and $possroles are optional array refs -- to domains to check and
                   12626: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12627: users' roles.db to check for a dc or su role in any domain. This can be
                   12628: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12629: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12630: this then allows &privileged_by_domain() to be used, which caches the identity
                   12631: of privileged users, eliminating the need for repeated calls to &dump().
                   12632: 
                   12633: =item *
                   12634: 
                   12635: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12636: where the outer hash keys are domains specified in the $possdomains array ref,
                   12637: next inner hash keys are privileged roles specified in the $roles array ref,
                   12638: and the innermost hash contains key = value pairs for username:domain = end:start
                   12639: for active or future "privileged" users with that role in that domain. To avoid
                   12640: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12641: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  12642: 
1.243     albertel 12643: =back
                   12644: 
                   12645: =head2 User Modification
                   12646: 
                   12647: =over 4
                   12648: 
                   12649: =item *
                   12650: 
1.957     raeburn  12651: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12652: user for the level given by URL.  Optional start and end dates (leave empty
                   12653: string or zero for "no date")
1.191     harris41 12654: 
                   12655: =item *
                   12656: 
1.243     albertel 12657: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12658: change a users, password, possible return values are: ok,
                   12659: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12660: refused
1.191     harris41 12661: 
                   12662: =item *
                   12663: 
1.243     albertel 12664: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12665: 
                   12666: =item *
                   12667: 
1.1058    raeburn  12668: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12669:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12670: 
                   12671: will update user information (firstname,middlename,lastname,generation,
                   12672: permanentemail), and if forceid is true, student/employee ID also.
                   12673: A user's institutional affiliation(s) can also be updated.
                   12674: User information fields will not be overwritten with empty entries 
                   12675: unless the field is included in the $candelete array reference.
                   12676: This array is included when a single user is modified via "Manage Users",
                   12677: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12678: 
                   12679: =item *
                   12680: 
1.286     matthew  12681: modifystudent
                   12682: 
1.957     raeburn  12683: modify a student's enrollment and identification information.
1.286     matthew  12684: The course id is resolved based on the current users environment.  
                   12685: This means the envoking user must be a course coordinator or otherwise
                   12686: associated with a course.
                   12687: 
1.297     matthew  12688: This call is essentially a wrapper for lonnet::modifyuser and
                   12689: lonnet::modify_student_enrollment
1.286     matthew  12690: 
                   12691: Inputs: 
                   12692: 
                   12693: =over 4
                   12694: 
1.957     raeburn  12695: =item B<$udom> Student's loncapa domain
1.286     matthew  12696: 
1.957     raeburn  12697: =item B<$uname> Student's loncapa login name
1.286     matthew  12698: 
1.964     bisitz   12699: =item B<$uid> Student/Employee ID
1.286     matthew  12700: 
1.957     raeburn  12701: =item B<$umode> Student's authentication mode
1.286     matthew  12702: 
1.957     raeburn  12703: =item B<$upass> Student's password
1.286     matthew  12704: 
1.957     raeburn  12705: =item B<$first> Student's first name
1.286     matthew  12706: 
1.957     raeburn  12707: =item B<$middle> Student's middle name
1.286     matthew  12708: 
1.957     raeburn  12709: =item B<$last> Student's last name
1.286     matthew  12710: 
1.957     raeburn  12711: =item B<$gene> Student's generation
1.286     matthew  12712: 
1.957     raeburn  12713: =item B<$usec> Student's section in course
1.286     matthew  12714: 
                   12715: =item B<$end> Unix time of the roles expiration
                   12716: 
                   12717: =item B<$start> Unix time of the roles start date
                   12718: 
                   12719: =item B<$forceid> If defined, allow $uid to be changed
                   12720: 
                   12721: =item B<$desiredhome> server to use as home server for student
                   12722: 
1.957     raeburn  12723: =item B<$email> Student's permanent e-mail address
                   12724: 
                   12725: =item B<$type> Type of enrollment (auto or manual)
                   12726: 
1.963     raeburn  12727: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12728: 
                   12729: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12730: 
1.963     raeburn  12731: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12732: 
1.963     raeburn  12733: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12734: 
1.1216    raeburn  12735: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12736: 
                   12737: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  12738: 
1.286     matthew  12739: =back
1.297     matthew  12740: 
                   12741: =item *
                   12742: 
                   12743: modify_student_enrollment
                   12744: 
                   12745: Change a students enrollment status in a class.  The environment variable
                   12746: 'role.request.course' must be defined for this function to proceed.
                   12747: 
                   12748: Inputs:
                   12749: 
                   12750: =over 4
                   12751: 
                   12752: =item $udom, students domain
                   12753: 
                   12754: =item $uname, students name
                   12755: 
                   12756: =item $uid, students user id
                   12757: 
                   12758: =item $first, students first name
                   12759: 
                   12760: =item $middle
                   12761: 
                   12762: =item $last
                   12763: 
                   12764: =item $gene
                   12765: 
                   12766: =item $usec
                   12767: 
                   12768: =item $end
                   12769: 
                   12770: =item $start
                   12771: 
1.957     raeburn  12772: =item $type
                   12773: 
                   12774: =item $locktype
                   12775: 
                   12776: =item $cid
                   12777: 
                   12778: =item $selfenroll
                   12779: 
                   12780: =item $context
                   12781: 
1.1216    raeburn  12782: =item $credits, number of credits student will earn from this class
                   12783: 
1.297     matthew  12784: =back
                   12785: 
1.191     harris41 12786: 
                   12787: =item *
                   12788: 
1.243     albertel 12789: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12790: custom role; give a custom role to a user for the level given by URL.  Specify
                   12791: name and domain of role author, and role name
1.191     harris41 12792: 
                   12793: =item *
                   12794: 
1.243     albertel 12795: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12796: 
                   12797: =item *
                   12798: 
1.243     albertel 12799: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12800: 
                   12801: =back
                   12802: 
                   12803: =head2 Course Infomation
                   12804: 
                   12805: =over 4
1.191     harris41 12806: 
                   12807: =item *
                   12808: 
1.1118    foxr     12809: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12810: specified course id, including all environment settings for the
                   12811: course, the description of the course will be in the hash under the
                   12812: key 'description'
1.191     harris41 12813: 
1.1118    foxr     12814: $options is an optional parameter that if supplied is a hash reference that controls
                   12815: what how this function works.  It has the following key/values:
                   12816: 
                   12817: =over 4
                   12818: 
                   12819: =item freshen_cache
                   12820: 
                   12821: If defined, and the environment cache for the course is valid, it is 
                   12822: returned in the returned hash.
                   12823: 
                   12824: =item one_time
                   12825: 
                   12826: If defined, the last cache time is set to _now_
                   12827: 
                   12828: =item user
                   12829: 
                   12830: If defined, the supplied username is used instead of the current user.
                   12831: 
                   12832: 
                   12833: =back
                   12834: 
1.191     harris41 12835: =item *
                   12836: 
1.624     albertel 12837: resdata($name,$domain,$type,@which) : request for current parameter
                   12838: setting for a specific $type, where $type is either 'course' or 'user',
                   12839: @what should be a list of parameters to ask about. This routine caches
                   12840: answers for 5 minutes.
1.243     albertel 12841: 
1.877     foxr     12842: =item *
                   12843: 
                   12844: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12845: data base, returning a hash that is keyed by the resource name and has
                   12846: values that are the resource value.  I believe that the timestamps and
                   12847: versions are also returned.
                   12848: 
1.243     albertel 12849: =back
                   12850: 
                   12851: =head2 Course Modification
                   12852: 
                   12853: =over 4
1.191     harris41 12854: 
                   12855: =item *
                   12856: 
1.243     albertel 12857: writecoursepref($courseid,%prefs) : write preferences (environment
                   12858: database) for a course
1.191     harris41 12859: 
                   12860: =item *
                   12861: 
1.1011    raeburn  12862: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12863: 
                   12864: =item *
                   12865: 
1.1038    raeburn  12866: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12867: 
1.1167    droeschl 12868: =item *
                   12869: 
                   12870: is_course($courseid), is_course($cdom, $cnum)
                   12871: 
                   12872: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12873: two component version $cdom, $cnum. It checks if the specified course exists.
                   12874: 
                   12875: Returns:
                   12876:     undef if the course doesn't exist, otherwise
                   12877:     in scalar context the combined courseid.
                   12878:     in list context the two components of the course identifier, domain and 
                   12879:     courseid.    
                   12880: 
1.243     albertel 12881: =back
                   12882: 
                   12883: =head2 Resource Subroutines
                   12884: 
                   12885: =over 4
1.191     harris41 12886: 
                   12887: =item *
                   12888: 
1.243     albertel 12889: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12890: 
                   12891: =item *
                   12892: 
1.243     albertel 12893: repcopy($filename) : subscribes to the requested file, and attempts to
                   12894: replicate from the owning library server, Might return
1.607     raeburn  12895: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12896: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12897: resource. Expects the local filesystem pathname
                   12898: (/home/httpd/html/res/....)
                   12899: 
                   12900: =back
                   12901: 
                   12902: =head2 Resource Information
                   12903: 
                   12904: =over 4
1.191     harris41 12905: 
                   12906: =item *
                   12907: 
1.243     albertel 12908: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12909: a vairety of different possible values, $varname should be a request
                   12910: string, and the other parameters can be used to specify who and what
                   12911: one is asking about.
                   12912: 
                   12913: Possible values for $varname are environment.lastname (or other item
                   12914: from the envirnment hash), user.name (or someother aspect about the
                   12915: user), resource.0.maxtries (or some other part and parameter of a
                   12916: resource)
1.204     albertel 12917: 
                   12918: =item *
                   12919: 
1.243     albertel 12920: directcondval($number) : get current value of a condition; reads from a state
                   12921: string
1.204     albertel 12922: 
                   12923: =item *
                   12924: 
1.243     albertel 12925: condval($condidx) : value of condition index based on state
1.204     albertel 12926: 
                   12927: =item *
                   12928: 
1.243     albertel 12929: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12930: resource's metadata, $what should be either a specific key, or either
                   12931: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12932: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12933: 
                   12934: this function automatically caches all requests
1.191     harris41 12935: 
                   12936: =item *
                   12937: 
1.243     albertel 12938: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12939: network of library servers; returns file handle of where SQL and regex results
                   12940: will be stored for query
1.191     harris41 12941: 
                   12942: =item *
                   12943: 
1.243     albertel 12944: symbread($filename) : return symbolic list entry (filename argument optional);
                   12945: returns the data handle
1.191     harris41 12946: 
                   12947: =item *
                   12948: 
1.1190    raeburn  12949: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12950: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12951: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12952: on failure, user must be in a course, as it assumes the existence of
                   12953: the course initial hash, and uses $env('request.course.id'}.  The third
                   12954: arg is an optional reference to a scalar.  If this arg is passed in the 
                   12955: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12956: encrypted; otherwise it will be null.  
1.191     harris41 12957: 
                   12958: =item *
                   12959: 
1.243     albertel 12960: symbclean($symb) : removes versions numbers from a symb, returns the
                   12961: cleaned symb
1.191     harris41 12962: 
                   12963: =item *
                   12964: 
1.243     albertel 12965: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12966: course map, user must be in a course for it to work.
1.191     harris41 12967: 
                   12968: =item *
                   12969: 
1.243     albertel 12970: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12971: 
                   12972: =item *
                   12973: 
1.243     albertel 12974: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12975: a random seed, all arguments are optional, if they aren't sent it uses the
                   12976: environment to derive them. Note: if symb isn't sent and it can't get one
                   12977: from &symbread it will use the current time as its return value
1.191     harris41 12978: 
                   12979: =item *
                   12980: 
1.243     albertel 12981: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12982: unfakeable, receipt
1.191     harris41 12983: 
                   12984: =item *
                   12985: 
1.620     albertel 12986: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12987: 
                   12988: =item *
                   12989: 
1.243     albertel 12990: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12991: 
                   12992: =item *
                   12993: 
1.243     albertel 12994: 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 12995: 
                   12996: =item *
                   12997: 
1.243     albertel 12998: 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 12999: 
                   13000: =item *
                   13001: 
1.243     albertel 13002: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13003: 
                   13004: =item *
                   13005: 
1.243     albertel 13006: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13007: forcing spreadsheet to reevaluate the resource scores next time.
                   13008: 
1.1195    raeburn  13009: =item * 
                   13010: 
1.1196    raeburn  13011: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13012: when viewing in course context.
1.1195    raeburn  13013: 
1.1196    raeburn  13014:  input: six args -- filename (decluttered), course number, course domain,
                   13015:                     url, symb (if registered) and group (if this is a 
                   13016:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13017: 
1.1196    raeburn  13018:  output: array of five scalars --
1.1195    raeburn  13019:          $cfile -- url for file editing if editable on current server
                   13020:          $home -- homeserver of resource (i.e., for author if published,
                   13021:                                           or course if uploaded.).
                   13022:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13023:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13024:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13025: 
                   13026: =item *
                   13027: 
                   13028: is_course_upload($file,$cnum,$cdom)
                   13029: 
                   13030: Used in course context to determine if current file was uploaded to 
                   13031: the course (i.e., would be found in /userfiles/docs on the course's 
                   13032: homeserver.
                   13033: 
                   13034:   input: 3 args -- filename (decluttered), course number and course domain.
                   13035:   output: boolean -- 1 if file was uploaded.
                   13036: 
1.243     albertel 13037: =back
                   13038: 
                   13039: =head2 Storing/Retreiving Data
                   13040: 
                   13041: =over 4
1.191     harris41 13042: 
                   13043: =item *
                   13044: 
1.243     albertel 13045: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13046: for this url; hashref needs to be given and should be a \%hashname; the
                   13047: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13048: be derived from the env
1.191     harris41 13049: 
                   13050: =item *
                   13051: 
1.243     albertel 13052: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13053: uses critical subroutine
1.191     harris41 13054: 
                   13055: =item *
                   13056: 
1.243     albertel 13057: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13058: all args are optional
1.191     harris41 13059: 
                   13060: =item *
                   13061: 
1.717     albertel 13062: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13063: dumps the complete (or key matching regexp) namespace into a hash
                   13064: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13065: normally &store()ed into
                   13066: 
                   13067: $range should be either an integer '100' (give me the first 100
                   13068:                                            matching records)
                   13069:               or be  two integers sperated by a - with no spaces
                   13070:                  '30-50' (give me the 30th through the 50th matching
                   13071:                           records)
                   13072: 
                   13073: 
                   13074: =item *
                   13075: 
                   13076: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13077: replaces a &store() version of data with a replacement set of data
                   13078: for a particular resource in a namespace passed in the $storehash hash 
                   13079: reference
                   13080: 
                   13081: =item *
                   13082: 
1.243     albertel 13083: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13084: works very similar to store/cstore, but all data is stored in a
                   13085: temporary location and can be reset using tmpreset, $storehash should
                   13086: be a hash reference, returns nothing on success
1.191     harris41 13087: 
                   13088: =item *
                   13089: 
1.243     albertel 13090: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13091: similar to restore, but all data is stored in a temporary location and
                   13092: can be reset using tmpreset. Returns a hash of values on success,
                   13093: error string otherwise.
1.191     harris41 13094: 
                   13095: =item *
                   13096: 
1.243     albertel 13097: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13098: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13099: 
                   13100: =item *
                   13101: 
1.243     albertel 13102: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13103: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13104: 
                   13105: =item *
                   13106: 
1.243     albertel 13107: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13108: namesp ($udom and $uname are optional)
1.191     harris41 13109: 
                   13110: =item *
                   13111: 
1.702     albertel 13112: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13113: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13114: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13115: 
1.702     albertel 13116: $range should be either an integer '100' (give me the first 100
                   13117:                                            matching records)
                   13118:               or be  two integers sperated by a - with no spaces
                   13119:                  '30-50' (give me the 30th through the 50th matching
                   13120:                           records)
1.449     matthew  13121: =item *
                   13122: 
                   13123: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13124: $store can be a scalar, an array reference, or if the amount to be 
                   13125: incremented is > 1, a hash reference.
                   13126: 
                   13127: ($udom and $uname are optional)
1.191     harris41 13128: 
                   13129: =item *
                   13130: 
1.243     albertel 13131: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13132: ($udom and $uname are optional)
1.191     harris41 13133: 
                   13134: =item *
                   13135: 
1.243     albertel 13136: cput($namespace,$storehash,$udom,$uname) : critical put
                   13137: ($udom and $uname are optional)
1.191     harris41 13138: 
                   13139: =item *
                   13140: 
1.748     albertel 13141: newput($namespace,$storehash,$udom,$uname) :
                   13142: 
                   13143: Attempts to store the items in the $storehash, but only if they don't
                   13144: currently exist, if this succeeds you can be certain that you have 
                   13145: successfully created a new key value pair in the $namespace db.
                   13146: 
                   13147: 
                   13148: Args:
                   13149:  $namespace: name of database to store values to
                   13150:  $storehash: hashref to store to the db
                   13151:  $udom: (optional) domain of user containing the db
                   13152:  $uname: (optional) name of user caontaining the db
                   13153: 
                   13154: Returns:
                   13155:  'ok' -> succeeded in storing all keys of $storehash
                   13156:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13157:                         least <key> already existed in the db (other
                   13158:                         requested keys may also already exist)
1.967     bisitz   13159:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13160:  'con_lost' -> unable to contact request server
                   13161:  'refused' -> action was not allowed by remote machine
                   13162: 
                   13163: 
                   13164: =item *
                   13165: 
1.243     albertel 13166: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13167: reference filled in from namesp (encrypts the return communication)
                   13168: ($udom and $uname are optional)
1.191     harris41 13169: 
                   13170: =item *
                   13171: 
1.243     albertel 13172: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13173: critical subroutine
                   13174: 
1.806     raeburn  13175: =item *
                   13176: 
1.860     raeburn  13177: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13178: array reference filled in from namespace found in domain level on either
                   13179: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13180: 
                   13181: =item *
                   13182: 
1.860     raeburn  13183: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13184: domain level either on specified domain server ($uhome) or primary domain 
                   13185: server ($udom and $uhome are optional)
1.806     raeburn  13186: 
1.943     raeburn  13187: =item * 
                   13188: 
                   13189: get_domain_defaults($target_domain) : returns hash with defaults for
                   13190: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13191: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13192: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13193: Values are retrieved from cache (if current), or from domain's configuration.db
                   13194: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13195: or lonTabs/domain.tab. 
                   13196: 
                   13197: %domdefaults = &get_auth_defaults($target_domain);
                   13198: 
1.243     albertel 13199: =back
                   13200: 
                   13201: =head2 Network Status Functions
                   13202: 
                   13203: =over 4
1.191     harris41 13204: 
                   13205: =item *
                   13206: 
1.1137    raeburn  13207: dirlist() : return directory list based on URI (first arg).
                   13208: 
                   13209: Inputs: 1 required, 5 optional.
                   13210: 
                   13211: =over
                   13212: 
                   13213: =item 
                   13214: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13215: 
                   13216: =item
                   13217: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13218: 
                   13219: =item
                   13220: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13221: 
                   13222: =item
                   13223: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13224: 
                   13225: =item
                   13226: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13227: 
                   13228: =item 
                   13229: $alternateRoot - path to prepend in place of path from $uri.
                   13230: 
                   13231: =back
                   13232: 
                   13233: Returns: Array of up to two items.
                   13234: 
                   13235: =over
                   13236: 
                   13237: a reference to an array of files/subdirectories
                   13238: 
                   13239: =over
                   13240: 
                   13241: Each element in the array of files/subdirectories is a & separated list of
                   13242: item name and the result of running stat on the item.  If dirlist was requested
                   13243: for a file instead of a directory, the item name will be ''. For a directory 
                   13244: listing, if the item is a metadata file, the element will end &N&M 
                   13245: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13246: default copyright set (1).  
                   13247: 
                   13248: =back
                   13249: 
                   13250: a scalar containing error condition (if encountered).
                   13251: 
                   13252: =over
                   13253: 
                   13254: =item 
                   13255: no_host (no homeserver identified for $username:$domain).
                   13256: 
                   13257: =item 
                   13258: no_such_host (server contacted for listing not identified as valid host).
                   13259: 
                   13260: =item 
                   13261: con_lost (connection to remote server failed).
                   13262: 
                   13263: =item 
                   13264: refused (invalid $username:$domain received on lond side).
                   13265: 
                   13266: =item 
                   13267: no_such_dir (directory at specified path on lond side does not exist). 
                   13268: 
                   13269: =item 
                   13270: empty (directory at specified path on lond side is empty).
                   13271: 
                   13272: =over
                   13273: 
                   13274: This is currently not encountered because the &ls3, &ls2, 
                   13275: &ls (_handler) routines on the lond side do not filter out
                   13276: . and .. from a directory listing. 
                   13277: 
                   13278: =back
                   13279: 
                   13280: =back
                   13281: 
                   13282: =back
1.191     harris41 13283: 
                   13284: =item *
                   13285: 
1.243     albertel 13286: spareserver() : find server with least workload from spare.tab
                   13287: 
1.986     foxr     13288: 
                   13289: =item *
                   13290: 
                   13291: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13292: if there is no corresponding loncapa host.
                   13293: 
1.243     albertel 13294: =back
                   13295: 
1.986     foxr     13296: 
1.243     albertel 13297: =head2 Apache Request
                   13298: 
                   13299: =over 4
1.191     harris41 13300: 
                   13301: =item *
                   13302: 
1.243     albertel 13303: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13304: localhost, posts hash
                   13305: 
                   13306: =back
                   13307: 
                   13308: =head2 Data to String to Data
                   13309: 
                   13310: =over 4
1.191     harris41 13311: 
                   13312: =item *
                   13313: 
1.243     albertel 13314: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13315: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13316: 
                   13317: =item *
                   13318: 
1.243     albertel 13319: hashref2str($hashref) : convert a hashref into a string complete with
                   13320: escaping and '=' and '&' separators, supports elements that are
                   13321: arrayrefs and hashrefs
1.191     harris41 13322: 
                   13323: =item *
                   13324: 
1.243     albertel 13325: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13326: with escaping and '&' separators, supports elements that are arrayrefs
                   13327: and hashrefs
1.191     harris41 13328: 
                   13329: =item *
                   13330: 
1.243     albertel 13331: str2hash($string) : convert string to hash using unescaping and
                   13332: splitting on '=' and '&', supports elements that are arrayrefs and
                   13333: hashrefs
1.191     harris41 13334: 
                   13335: =item *
                   13336: 
1.243     albertel 13337: str2array($string) : convert string to hash using unescaping and
                   13338: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13339: 
                   13340: =back
                   13341: 
                   13342: =head2 Logging Routines
                   13343: 
                   13344: 
                   13345: These routines allow one to make log messages in the lonnet.log and
                   13346: lonnet.perm logfiles.
1.191     harris41 13347: 
1.1119    foxr     13348: =over 4
                   13349: 
1.191     harris41 13350: =item *
                   13351: 
1.243     albertel 13352: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13353: 
                   13354: =item *
                   13355: 
1.243     albertel 13356: logthis() : append message to the normal lonnet.log file, it gets
                   13357: preiodically rolled over and deleted.
1.191     harris41 13358: 
                   13359: =item *
                   13360: 
1.243     albertel 13361: logperm() : append a permanent message to lonnet.perm.log, this log
                   13362: file never gets deleted by any automated portion of the system, only
                   13363: messages of critical importance should go in here.
                   13364: 
1.1119    foxr     13365: 
1.243     albertel 13366: =back
                   13367: 
                   13368: =head2 General File Helper Routines
                   13369: 
                   13370: =over 4
1.191     harris41 13371: 
                   13372: =item *
                   13373: 
1.481     raeburn  13374: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13375: (a) files in /uploaded
                   13376:   (i) If a local copy of the file exists - 
                   13377:       compares modification date of local copy with last-modified date for 
                   13378:       definitive version stored on home server for course. If local copy is 
                   13379:       stale, requests a new version from the home server and stores it. 
                   13380:       If the original has been removed from the home server, then local copy 
                   13381:       is unlinked.
                   13382:   (ii) If local copy does not exist -
                   13383:       requests the file from the home server and stores it. 
                   13384:   
                   13385:   If $caller is 'uploadrep':  
                   13386:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13387:     for request for files originally uploaded via DOCS. 
                   13388:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13389:   
                   13390:   Otherwise:
                   13391:      This indicates a call from the content generation phase of the request.
                   13392:      -  returns the entire contents of the file or -1.
                   13393:      
                   13394: (b) files in /res
                   13395:    - returns the entire contents of a file or -1; 
                   13396:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13397: 
1.712     albertel 13398: 
                   13399: =item *
                   13400: 
                   13401: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13402:                   reference
                   13403: 
                   13404: returns either a stat() list of data about the file or an empty list
                   13405: if the file doesn't exist or couldn't find out about it (connection
                   13406: problems or user unknown)
                   13407: 
1.191     harris41 13408: =item *
                   13409: 
1.243     albertel 13410: filelocation($dir,$file) : returns file system location of a file
                   13411: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13412: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13413: and a file of ../bob will become /a/bob)
1.191     harris41 13414: 
                   13415: =item *
                   13416: 
                   13417: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13418: filelocation except for hrefs
                   13419: 
                   13420: =item *
                   13421: 
                   13422: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13423: 
1.243     albertel 13424: =back
                   13425: 
1.608     albertel 13426: =head2 Usererfile file routines (/uploaded*)
                   13427: 
                   13428: =over 4
                   13429: 
                   13430: =item *
                   13431: 
                   13432: userfileupload(): main rotine for putting a file in a user or course's
                   13433:                   filespace, arguments are,
                   13434: 
1.620     albertel 13435:  formname - required - this is the name of the element in $env where the
1.608     albertel 13436:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13437:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13438:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13439:  context - if coursedoc, store the file in the course of the active role
                   13440:              of the current user; 
                   13441:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13442:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13443:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13444:          if undefined, it will be placed in "unknown"
                   13445: 
                   13446:  (This routine calls clean_filename() to remove any dangerous
                   13447:  characters from the filename, and then calls finuserfileupload() to
                   13448:  complete the transaction)
                   13449: 
                   13450:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13451:  and /adm/notfound.html if unsuccessful
                   13452: 
                   13453: =item *
                   13454: 
                   13455: clean_filename(): routine for cleaing a filename up for storage in
                   13456:                  userfile space, argument is:
                   13457: 
                   13458:  filename - proposed filename
                   13459: 
                   13460: returns: the new clean filename
                   13461: 
                   13462: =item *
                   13463: 
1.1090    raeburn  13464: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13465: userspace, probably shouldn't be called directly
                   13466: 
                   13467:   docuname: username or courseid of destination for the file
                   13468:   docudom: domain of user/course of destination for the file
                   13469:   formname: same as for userfileupload()
1.1090    raeburn  13470:   fname: filename (including subdirectories) for the file
                   13471:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13472:   allfiles: reference to hash used to store objects found by parser
                   13473:   codebase: reference to hash used for codebases of java objects found by parser
                   13474:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13475:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13476:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13477:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13478:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13479:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13480:   mimetype: reference to scalar to accommodate mime type determined
                   13481:             from File::MMagic if $parser = parse.
1.608     albertel 13482: 
                   13483:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13484:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13485:  was 'overwrite').
                   13486:  
1.608     albertel 13487: 
                   13488: =item *
                   13489: 
                   13490: renameuserfile(): renames an existing userfile to a new name
                   13491: 
                   13492:   Args:
                   13493:    docuname: username or courseid of destination for the file
                   13494:    docudom: domain of user/course of destination for the file
                   13495:    old: current file name (including any subdirs under userfiles)
                   13496:    new: desired file name (including any subdirs under userfiles)
                   13497: 
                   13498: =item *
                   13499: 
                   13500: mkdiruserfile(): creates a directory is a userfiles dir
                   13501: 
                   13502:   Args:
                   13503:    docuname: username or courseid of destination for the file
                   13504:    docudom: domain of user/course of destination for the file
                   13505:    dir: dir to create (including any subdirs under userfiles)
                   13506: 
                   13507: =item *
                   13508: 
                   13509: removeuserfile(): removes a file that exists in userfiles
                   13510: 
                   13511:   Args:
                   13512:    docuname: username or courseid of destination for the file
                   13513:    docudom: domain of user/course of destination for the file
                   13514:    fname: filname to delete (including any subdirs under userfiles)
                   13515: 
                   13516: =item *
                   13517: 
                   13518: removeuploadedurl(): convience function for removeuserfile()
                   13519: 
                   13520:   Args:
                   13521:    url:  a full /uploaded/... url to delete
                   13522: 
1.747     albertel 13523: =item * 
                   13524: 
                   13525: get_portfile_permissions():
                   13526:   Args:
                   13527:     domain: domain of user or course contain the portfolio files
                   13528:     user: name of user or num of course contain the portfolio files
                   13529:   Returns:
                   13530:     hashref of a dump of the proper file_permissions.db
                   13531:    
                   13532: 
                   13533: =item * 
                   13534: 
                   13535: get_access_controls():
                   13536: 
                   13537: Args:
                   13538:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13539:   group: (optional) the group you want the files associated with
                   13540:   file: (optional) the file you want access info on
                   13541: 
                   13542: Returns:
1.749     raeburn  13543:     a hash (keys are file names) of hashes containing
                   13544:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13545:         values are XML containing access control settings (see below) 
1.747     albertel 13546: 
                   13547: Internal notes:
                   13548: 
1.749     raeburn  13549:  access controls are stored in file_permissions.db as key=value pairs.
                   13550:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13551:         where scope -> public,guest,course,group,domains or users.
                   13552:               end -> UNIX time for end of access (0 -> no end date)
                   13553:               start -> UNIX time for start of access
                   13554: 
                   13555:     value -> XML description of access control
                   13556:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13557:             <start></start>
                   13558:             <end></end>
                   13559: 
                   13560:             <password></password>  for scope type = guest
                   13561: 
                   13562:             <domain></domain>     for scope type = course or group
                   13563:             <number></number>
                   13564:             <roles id="">
                   13565:              <role></role>
                   13566:              <access></access>
                   13567:              <section></section>
                   13568:              <group></group>
                   13569:             </roles>
                   13570: 
                   13571:             <dom></dom>         for scope type = domains
                   13572: 
                   13573:             <users>             for scope type = users
                   13574:              <user>
                   13575:               <uname></uname>
                   13576:               <udom></udom>
                   13577:              </user>
                   13578:             </users>
                   13579:            </scope> 
                   13580:               
                   13581:  Access data is also aggregated for each file in an additional key=value pair:
                   13582:  key -> path to file/file_name\0accesscontrol 
                   13583:  value -> reference to hash
                   13584:           hash contains key = value pairs
                   13585:           where key = uniqueID:scope_end_start
                   13586:                 value = UNIX time record was last updated
                   13587: 
                   13588:           Used to improve speed of look-ups of access controls for each file.  
                   13589:  
                   13590:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13591: 
1.1198    raeburn  13592: =item *
                   13593: 
1.749     raeburn  13594: modify_access_controls():
                   13595: 
                   13596: Modifies access controls for a portfolio file
                   13597: Args
                   13598: 1. file name
                   13599: 2. reference to hash of required changes,
                   13600: 3. domain
                   13601: 4. username
                   13602:   where domain,username are the domain of the portfolio owner 
                   13603:   (either a user or a course) 
                   13604: 
                   13605: Returns:
                   13606: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13607: 2. result of deletions ('ok' or 'error', with error message).
                   13608: 3. reference to hash of any new or updated access controls.
                   13609: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13610:    key = integer (inbound ID)
1.1198    raeburn  13611:    value = uniqueID
                   13612: 
                   13613: =item *
                   13614: 
                   13615: get_timebased_id():
                   13616: 
                   13617: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13618: course via the Course Editor (e.g., folders, composite pages, 
                   13619: group bulletin boards).
                   13620: 
                   13621: Args: (first three required; six others optional)
                   13622: 
                   13623: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13624:    docssequence, or name of group
                   13625: 
                   13626: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13627:    e.g., num, boardids
                   13628: 
                   13629: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   13630:    file will be named nohist_namespace.db
                   13631: 
                   13632: 4. cdom: domain of course; default is current course domain from %env
                   13633: 
                   13634: 5. cnum: course number; default is current course number from %env
                   13635: 
                   13636: 6. idtype: set to concat if an additional digit is to be appended to the 
                   13637:    unix timestamp to form the suffix, if the plain timestamp is already
                   13638:    in use.  Default is to not do this, but simply increment the unix 
                   13639:    timestamp by 1 until a unique key is obtained.
                   13640: 
                   13641: 7. who: holder of locking key; defaults to user:domain for user.
                   13642: 
                   13643: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   13644:    retrying); default is 3.
                   13645: 
                   13646: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   13647: 
                   13648: Returns:
                   13649: 
                   13650: 1. suffix obtained (numeric)
                   13651: 
                   13652: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13653: 
                   13654: 3. error: contains (localized) error message if an error occurred.
                   13655: 
1.747     albertel 13656: 
1.608     albertel 13657: =back
                   13658: 
1.243     albertel 13659: =head2 HTTP Helper Routines
                   13660: 
                   13661: =over 4
                   13662: 
1.191     harris41 13663: =item *
                   13664: 
                   13665: escape() : unpack non-word characters into CGI-compatible hex codes
                   13666: 
                   13667: =item *
                   13668: 
                   13669: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13670: 
1.243     albertel 13671: =back
                   13672: 
                   13673: =head1 PRIVATE SUBROUTINES
                   13674: 
                   13675: =head2 Underlying communication routines (Shouldn't call)
                   13676: 
                   13677: =over 4
                   13678: 
                   13679: =item *
                   13680: 
                   13681: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13682: 
                   13683: =item *
                   13684: 
                   13685: reply() : uses subreply to send a message to remote machine, logs all failures
                   13686: 
                   13687: =item *
                   13688: 
                   13689: critical() : passes a critical message to another server; if cannot
                   13690: get through then place message in connection buffer directory and
                   13691: returns con_delayed, if incapable of saving message, returns
                   13692: con_failed
                   13693: 
                   13694: =item *
                   13695: 
                   13696: reconlonc() : tries to reconnect lonc client processes.
                   13697: 
                   13698: =back
                   13699: 
                   13700: =head2 Resource Access Logging
                   13701: 
                   13702: =over 4
                   13703: 
                   13704: =item *
                   13705: 
                   13706: flushcourselogs() : flush (save) buffer logs and access logs
                   13707: 
                   13708: =item *
                   13709: 
                   13710: courselog($what) : save message for course in hash
                   13711: 
                   13712: =item *
                   13713: 
                   13714: courseacclog($what) : save message for course using &courselog().  Perform
                   13715: special processing for specific resource types (problems, exams, quizzes, etc).
                   13716: 
1.191     harris41 13717: =item *
                   13718: 
                   13719: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13720: as a PerlChildExitHandler
1.243     albertel 13721: 
                   13722: =back
                   13723: 
                   13724: =head2 Other
                   13725: 
                   13726: =over 4
                   13727: 
                   13728: =item *
                   13729: 
                   13730: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13731: 
                   13732: =back
                   13733: 
                   13734: =cut
1.877     foxr     13735: 

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