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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1218  ! raeburn     4: # $Id: lonnet.pm,v 1.1217 2013/03/04 01:46:31 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.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.943     raeburn  2026:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   2027:                                   $cachetime);
                   2028:     return %domdefaults;
                   2029: }
                   2030: 
1.344     www      2031: # --------------------------------------------------- Assign a key to a student
                   2032: 
                   2033: sub assign_access_key {
1.364     www      2034: #
                   2035: # a valid key looks like uname:udom#comments
                   2036: # comments are being appended
                   2037: #
1.498     www      2038:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2039:     $kdom=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2041:     $knum=
1.620     albertel 2042:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2043:     $cdom=
1.620     albertel 2044:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2045:     $cnum=
1.620     albertel 2046:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2047:     $udom=$env{'user.name'} unless (defined($udom));
                   2048:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2049:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2050:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2051:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2052:                                                   # assigned to this person
                   2053:                                                   # - this should not happen,
1.345     www      2054:                                                   # unless something went wrong
                   2055:                                                   # the first time around
                   2056: # ready to assign
1.364     www      2057:         $logentry=$1.'; '.$logentry;
1.496     www      2058:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2059:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2060: # key now belongs to user
1.346     www      2061: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2062:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2063:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2064:                 return 'ok';
                   2065:             } else {
                   2066:                 return 
                   2067:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2068: 	    }
                   2069:         } else {
                   2070:             return 'error: Could not assign key, try again later.';
                   2071:         }
1.364     www      2072:     } elsif (!$existing{$ckey}) {
1.345     www      2073: # the key does not exist
                   2074: 	return 'error: The key does not exist';
                   2075:     } else {
                   2076: # the key is somebody else's
                   2077: 	return 'error: The key is already in use';
                   2078:     }
1.344     www      2079: }
                   2080: 
1.364     www      2081: # ------------------------------------------ put an additional comment on a key
                   2082: 
                   2083: sub comment_access_key {
                   2084: #
                   2085: # a valid key looks like uname:udom#comments
                   2086: # comments are being appended
                   2087: #
                   2088:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2089:     $cdom=
1.620     albertel 2090:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2091:     $cnum=
1.620     albertel 2092:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2093:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2094:     if ($existing{$ckey}) {
                   2095:         $existing{$ckey}.='; '.$logentry;
                   2096: # ready to assign
1.367     www      2097:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2098:                                                  $cdom,$cnum) eq 'ok') {
                   2099: 	    return 'ok';
                   2100:         } else {
                   2101: 	    return 'error: Count not store comment.';
                   2102:         }
                   2103:     } else {
                   2104: # the key does not exist
                   2105: 	return 'error: The key does not exist';
                   2106:     }
                   2107: }
                   2108: 
1.344     www      2109: # ------------------------------------------------------ Generate a set of keys
                   2110: 
                   2111: sub generate_access_keys {
1.364     www      2112:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2113:     $cdom=
1.620     albertel 2114:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2115:     $cnum=
1.620     albertel 2116:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2117:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2118:     unless (($cdom) && ($cnum)) { return 0; }
                   2119:     if ($number>10000) { return 0; }
                   2120:     sleep(2); # make sure don't get same seed twice
                   2121:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2122:     my $total=0;
                   2123:     for (my $i=1;$i<=$number;$i++) {
                   2124:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2125:                   sprintf("%lx",int(100000*rand)).'-'.
                   2126:                   sprintf("%lx",int(100000*rand));
                   2127:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2128:        $newkey=~s/0/h/g; # and also 0 and O
                   2129:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2130:        if ($existing{$newkey}) {
                   2131:            $i--;
                   2132:        } else {
1.364     www      2133: 	  if (&put('accesskeys',
                   2134:               { $newkey => '# generated '.localtime().
1.620     albertel 2135:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2136:                            '; '.$logentry },
                   2137: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2138:               $total++;
                   2139: 	  }
                   2140:        }
                   2141:     }
1.620     albertel 2142:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2143:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2144:     return $total;
                   2145: }
                   2146: 
                   2147: # ------------------------------------------------------- Validate an accesskey
                   2148: 
                   2149: sub validate_access_key {
                   2150:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2151:     $cdom=
1.620     albertel 2152:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2153:     $cnum=
1.620     albertel 2154:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2155:     $udom=$env{'user.domain'} unless (defined($udom));
                   2156:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2157:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2158:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2159: }
                   2160: 
                   2161: # ------------------------------------- Find the section of student in a course
1.652     albertel 2162: sub devalidate_getsection_cache {
                   2163:     my ($udom,$unam,$courseid)=@_;
                   2164:     my $hashid="$udom:$unam:$courseid";
                   2165:     &devalidate_cache_new('getsection',$hashid);
                   2166: }
1.298     matthew  2167: 
1.815     albertel 2168: sub courseid_to_courseurl {
                   2169:     my ($courseid) = @_;
                   2170:     #already url style courseid
                   2171:     return $courseid if ($courseid =~ m{^/});
                   2172: 
                   2173:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2174: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2175: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2176: 	return "/$cdom/$cnum";
                   2177:     }
                   2178: 
                   2179:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2180:     if (exists($courseinfo{'num'})) {
                   2181: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2182:     }
                   2183: 
                   2184:     return undef;
                   2185: }
                   2186: 
1.298     matthew  2187: sub getsection {
                   2188:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2189:     my $cachetime=1800;
1.551     albertel 2190: 
                   2191:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2192:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2193:     if (defined($cached)) { return $result; }
                   2194: 
1.298     matthew  2195:     my %Pending; 
                   2196:     my %Expired;
                   2197:     #
                   2198:     # Each role can either have not started yet (pending), be active, 
                   2199:     #    or have expired.
                   2200:     #
                   2201:     # If there is an active role, we are done.
                   2202:     #
                   2203:     # If there is more than one role which has not started yet, 
                   2204:     #     choose the one which will start sooner
                   2205:     # If there is one role which has not started yet, return it.
                   2206:     #
                   2207:     # If there is more than one expired role, choose the one which ended last.
                   2208:     # If there is a role which has expired, return it.
                   2209:     #
1.815     albertel 2210:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2211:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2212:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2213:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2214:         my $section=$1;
                   2215:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2216:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2217:         my $now=time;
1.548     albertel 2218:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2219:             $Expired{$end}=$section;
                   2220:             next;
                   2221:         }
1.548     albertel 2222:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2223:             $Pending{$start}=$section;
                   2224:             next;
                   2225:         }
1.599     albertel 2226:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2227:     }
                   2228:     #
                   2229:     # Presumedly there will be few matching roles from the above
                   2230:     # loop and the sorting time will be negligible.
                   2231:     if (scalar(keys(%Pending))) {
                   2232:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2233:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2234:     } 
                   2235:     if (scalar(keys(%Expired))) {
                   2236:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2237:         my $time = pop(@sorted);
1.599     albertel 2238:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2239:     }
1.599     albertel 2240:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2241: }
1.70      www      2242: 
1.599     albertel 2243: sub save_cache {
                   2244:     &purge_remembered();
1.722     albertel 2245:     #&Apache::loncommon::validate_page();
1.620     albertel 2246:     undef(%env);
1.780     albertel 2247:     undef($env_loaded);
1.599     albertel 2248: }
1.452     albertel 2249: 
1.599     albertel 2250: my $to_remember=-1;
                   2251: my %remembered;
                   2252: my %accessed;
                   2253: my $kicks=0;
                   2254: my $hits=0;
1.849     albertel 2255: sub make_key {
                   2256:     my ($name,$id) = @_;
1.872     albertel 2257:     if (length($id) > 65 
                   2258: 	&& length(&escape($id)) > 200) {
                   2259: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2260:     }
1.849     albertel 2261:     return &escape($name.':'.$id);
                   2262: }
                   2263: 
1.599     albertel 2264: sub devalidate_cache_new {
                   2265:     my ($name,$id,$debug) = @_;
                   2266:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2267:     $id=&make_key($name,$id);
1.599     albertel 2268:     $memcache->delete($id);
                   2269:     delete($remembered{$id});
                   2270:     delete($accessed{$id});
                   2271: }
                   2272: 
                   2273: sub is_cached_new {
                   2274:     my ($name,$id,$debug) = @_;
1.849     albertel 2275:     $id=&make_key($name,$id);
1.599     albertel 2276:     if (exists($remembered{$id})) {
1.1133    foxr     2277: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2278: 	$accessed{$id}=[&gettimeofday()];
                   2279: 	$hits++;
                   2280: 	return ($remembered{$id},1);
                   2281:     }
                   2282:     my $value = $memcache->get($id);
                   2283:     if (!(defined($value))) {
                   2284: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2285: 	return (undef,undef);
1.416     albertel 2286:     }
1.599     albertel 2287:     if ($value eq '__undef__') {
                   2288: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2289: 	$value=undef;
                   2290:     }
                   2291:     &make_room($id,$value,$debug);
                   2292:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2293:     return ($value,1);
                   2294: }
                   2295: 
                   2296: sub do_cache_new {
                   2297:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2298:     $id=&make_key($name,$id);
1.599     albertel 2299:     my $setvalue=$value;
                   2300:     if (!defined($setvalue)) {
                   2301: 	$setvalue='__undef__';
                   2302:     }
1.623     albertel 2303:     if (!defined($time) ) {
                   2304: 	$time=600;
                   2305:     }
1.599     albertel 2306:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2307:     my $result = $memcache->set($id,$setvalue,$time);
                   2308:     if (! $result) {
1.872     albertel 2309: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2310: 	$memcache->disconnect_all();
1.872     albertel 2311:     }
1.600     albertel 2312:     # need to make a copy of $value
1.919     albertel 2313:     &make_room($id,$value,$debug);
1.599     albertel 2314:     return $value;
                   2315: }
                   2316: 
                   2317: sub make_room {
                   2318:     my ($id,$value,$debug)=@_;
1.919     albertel 2319: 
                   2320:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2321:                                     : $value;
1.599     albertel 2322:     if ($to_remember<0) { return; }
                   2323:     $accessed{$id}=[&gettimeofday()];
                   2324:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2325:     my $to_kick;
                   2326:     my $max_time=0;
                   2327:     foreach my $other (keys(%accessed)) {
                   2328: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2329: 	    $to_kick=$other;
                   2330: 	    $max_time=&tv_interval($accessed{$other});
                   2331: 	}
                   2332:     }
                   2333:     delete($remembered{$to_kick});
                   2334:     delete($accessed{$to_kick});
                   2335:     $kicks++;
                   2336:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2337:     return;
                   2338: }
                   2339: 
1.599     albertel 2340: sub purge_remembered {
1.604     albertel 2341:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2342:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2343:     undef(%remembered);
                   2344:     undef(%accessed);
1.428     albertel 2345: }
1.70      www      2346: # ------------------------------------- Read an entry from a user's environment
                   2347: 
                   2348: sub userenvironment {
                   2349:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2350:     my $items;
                   2351:     foreach my $item (@what) {
                   2352:         $items.=&escape($item).'&';
                   2353:     }
                   2354:     $items=~s/\&$//;
1.70      www      2355:     my %returnhash=();
1.1009    raeburn  2356:     my $uhome = &homeserver($unam,$udom);
                   2357:     unless ($uhome eq 'no_host') {
                   2358:         my @answer=split(/\&/, 
                   2359:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2360:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2361:             return %returnhash;
                   2362:         }
1.1009    raeburn  2363:         my $i;
                   2364:         for ($i=0;$i<=$#what;$i++) {
                   2365: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2366:         }
1.70      www      2367:     }
                   2368:     return %returnhash;
1.1       albertel 2369: }
                   2370: 
1.617     albertel 2371: # ---------------------------------------------------------- Get a studentphoto
                   2372: sub studentphoto {
                   2373:     my ($udom,$unam,$ext) = @_;
                   2374:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2375:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2376:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2377:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2378:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2379:             } else {
                   2380:                 my ($result,$perm_reqd)=
1.707     albertel 2381: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2382:                 if ($result eq 'ok') {
                   2383:                     if (!($perm_reqd eq 'yes')) {
                   2384:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2385:                     }
                   2386:                 }
                   2387:             }
                   2388:         }
                   2389:     } else {
                   2390:         my ($result,$perm_reqd) = 
1.707     albertel 2391: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2392:         if ($result eq 'ok') {
                   2393:             if (!($perm_reqd eq 'yes')) {
                   2394:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2395:             }
                   2396:         }
                   2397:     }
                   2398:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2399: }
                   2400: 
                   2401: sub retrievestudentphoto {
                   2402:     my ($udom,$unam,$ext,$type) = @_;
                   2403:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2404:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2405:     if ($ret eq 'ok') {
                   2406:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2407:         if ($type eq 'thumbnail') {
                   2408:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2409:         }
                   2410:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2411:         return $tokenurl;
                   2412:     } else {
                   2413:         if ($type eq 'thumbnail') {
                   2414:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2415:         } else { 
                   2416:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2417:         }
1.617     albertel 2418:     }
                   2419: }
                   2420: 
1.263     www      2421: # -------------------------------------------------------------------- New chat
                   2422: 
                   2423: sub chatsend {
1.724     raeburn  2424:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2425:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2426:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2427:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2428:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2429: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2430: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2431: }
                   2432: 
                   2433: # ------------------------------------------ Find current version of a resource
                   2434: 
                   2435: sub getversion {
                   2436:     my $fname=&clutter(shift);
1.1189    raeburn  2437:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2438:     return &currentversion(&filelocation('',$fname));
                   2439: }
                   2440: 
                   2441: sub currentversion {
                   2442:     my $fname=shift;
                   2443:     my $author=$fname;
                   2444:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2445:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2446:     my $home=&homeserver($uname,$udom);
1.292     www      2447:     if ($home eq 'no_host') { 
                   2448:         return -1; 
                   2449:     }
1.1112    www      2450:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2451:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2452: 	return -1;
                   2453:     }
1.1112    www      2454:     return $answer;
1.263     www      2455: }
                   2456: 
1.1111    www      2457: #
                   2458: # Return special version number of resource if set by override, empty otherwise
                   2459: #
                   2460: sub usedversion {
                   2461:     my $fname=shift;
                   2462:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2463:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2464:     if ($urlversion) { return $urlversion; }
                   2465:     return '';
                   2466: }
                   2467: 
1.1       albertel 2468: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2469: 
1.1       albertel 2470: sub subscribe {
                   2471:     my $fname=shift;
1.761     raeburn  2472:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2473:     $fname=~s/[\n\r]//g;
1.1       albertel 2474:     my $author=$fname;
                   2475:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2476:     my ($udom,$uname)=split(/\//,$author);
                   2477:     my $home=homeserver($uname,$udom);
1.335     albertel 2478:     if ($home eq 'no_host') {
                   2479:         return 'not_found';
1.1       albertel 2480:     }
                   2481:     my $answer=reply("sub:$fname",$home);
1.64      www      2482:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2483: 	$answer.=' by '.$home;
                   2484:     }
1.1       albertel 2485:     return $answer;
                   2486: }
                   2487:     
1.8       www      2488: # -------------------------------------------------------------- Replicate file
                   2489: 
                   2490: sub repcopy {
                   2491:     my $filename=shift;
1.23      www      2492:     $filename=~s/\/+/\//g;
1.1142    raeburn  2493:     my $londocroot = $perlvar{'lonDocRoot'};
                   2494:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2495:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2496:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2497: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2498: 	return &repcopy_userfile($filename);
                   2499:     }
1.532     albertel 2500:     $filename=~s/[\n\r]//g;
1.8       www      2501:     my $transname="$filename.in.transfer";
1.828     www      2502: # FIXME: this should flock
1.607     raeburn  2503:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2504:     my $remoteurl=subscribe($filename);
1.64      www      2505:     if ($remoteurl =~ /^con_lost by/) {
                   2506: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2507:            return 'unavailable';
1.8       www      2508:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2509: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2510: 	   return 'not_found';
1.64      www      2511:     } elsif ($remoteurl =~ /^rejected by/) {
                   2512: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2513:            return 'forbidden';
1.20      www      2514:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2515:            return 'ok';
1.8       www      2516:     } else {
1.290     www      2517:         my $author=$filename;
                   2518:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2519:         my ($udom,$uname)=split(/\//,$author);
                   2520:         my $home=homeserver($uname,$udom);
                   2521:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2522:            my @parts=split(/\//,$filename);
                   2523:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2524:            if ($path ne "$londocroot/res") {
1.8       www      2525:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2526: 	       return 'bad_request';
1.8       www      2527:            }
                   2528:            my $count;
                   2529:            for ($count=5;$count<$#parts;$count++) {
                   2530:                $path.="/$parts[$count]";
                   2531:                if ((-e $path)!=1) {
                   2532: 		   mkdir($path,0777);
                   2533:                }
                   2534:            }
                   2535:            my $ua=new LWP::UserAgent;
                   2536:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2537:            my $response=$ua->request($request,$transname);
                   2538:            if ($response->is_error()) {
                   2539: 	       unlink($transname);
                   2540:                my $message=$response->status_line;
1.672     albertel 2541:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2542:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2543:                return 'unavailable';
1.8       www      2544:            } else {
1.16      www      2545: 	       if ($remoteurl!~/\.meta$/) {
                   2546:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2547:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2548:                   if ($mresponse->is_error()) {
                   2549: 		      unlink($filename.'.meta');
                   2550:                       &logthis(
1.672     albertel 2551:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2552:                   }
                   2553: 	       }
1.8       www      2554:                rename($transname,$filename);
1.607     raeburn  2555:                return 'ok';
1.8       www      2556:            }
1.290     www      2557:        }
1.8       www      2558:     }
1.330     www      2559: }
                   2560: 
                   2561: # ------------------------------------------------ Get server side include body
                   2562: sub ssi_body {
1.381     albertel 2563:     my ($filelink,%form)=@_;
1.606     matthew  2564:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2565:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2566:     }
1.953     www      2567:     my $output='';
                   2568:     my $response;
1.980     raeburn  2569:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2570:        ($output,$response)=&externalssi($filelink);
1.953     www      2571:     } else {
1.1004    droeschl 2572:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2573:        $filelink .= 'inhibitmenu=yes';
1.953     www      2574:        ($output,$response)=&ssi($filelink,%form);
                   2575:     }
1.778     albertel 2576:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2577:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2578:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2579:     if (wantarray) {
                   2580:         return ($output, $response);
                   2581:     } else {
                   2582:         return $output;
                   2583:     }
1.8       www      2584: }
                   2585: 
1.15      www      2586: # --------------------------------------------------------- Server Side Include
                   2587: 
1.782     albertel 2588: sub absolute_url {
                   2589:     my ($host_name) = @_;
                   2590:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2591:     if ($host_name eq '') {
                   2592: 	$host_name = $ENV{'SERVER_NAME'};
                   2593:     }
                   2594:     return $protocol.$host_name;
                   2595: }
                   2596: 
1.942     foxr     2597: #
                   2598: #   Server side include.
                   2599: # Parameters:
                   2600: #  fn     Possibly encrypted resource name/id.
                   2601: #  form   Hash that describes how the rendering should be done
                   2602: #         and other things.
1.944     foxr     2603: # Returns:
1.950     raeburn  2604: #   Scalar context: The content of the response.
                   2605: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2606: #     
1.15      www      2607: sub ssi {
                   2608: 
1.944     foxr     2609:     my ($fn,%form)=@_;
1.15      www      2610:     my $ua=new LWP::UserAgent;
1.23      www      2611:     my $request;
1.711     albertel 2612: 
                   2613:     $form{'no_update_last_known'}=1;
1.895     albertel 2614:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2615:     if (%form) {
1.782     albertel 2616:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2617:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2618:     } else {
1.782     albertel 2619:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2620:     }
                   2621: 
1.15      www      2622:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2623:     my $response= $ua->request($request);
1.1182    foxr     2624:     my $content = $response->content;
                   2625: 
                   2626: 
1.944     foxr     2627:     if (wantarray) {
1.1173    foxr     2628: 	return ($content, $response);
1.944     foxr     2629:     } else {
1.1173    foxr     2630: 	return $content;
1.942     foxr     2631:     }
1.324     www      2632: }
                   2633: 
                   2634: sub externalssi {
                   2635:     my ($url)=@_;
                   2636:     my $ua=new LWP::UserAgent;
                   2637:     my $request=new HTTP::Request('GET',$url);
                   2638:     my $response=$ua->request($request);
1.954     raeburn  2639:     if (wantarray) {
                   2640:         return ($response->content, $response);
                   2641:     } else {
                   2642:         return $response->content;
                   2643:     }
1.15      www      2644: }
1.254     www      2645: 
1.492     albertel 2646: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2647: 
                   2648: sub allowuploaded {
                   2649:     my ($srcurl,$url)=@_;
                   2650:     $url=&clutter(&declutter($url));
                   2651:     my $dir=$url;
                   2652:     $dir=~s/\/[^\/]+$//;
                   2653:     my %httpref=();
                   2654:     my $httpurl=&hreflocation('',$url);
                   2655:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2656:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2657: }
1.477     raeburn  2658: 
1.1193    raeburn  2659: #
                   2660: # Determine if the current user should be able to edit a particular resource,
                   2661: # when viewing in course context.
                   2662: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2663: #     Functions.
                   2664: # (b) When displaying folder contents in course editor, used to determine if
                   2665: #     "Edit" link will be displayed alongside resource.
                   2666: #
1.1196    raeburn  2667: #  input: six args -- filename (decluttered), course number, course domain,
                   2668: #                   url, symb (if registered) and group (if this is a group
                   2669: #                   item -- e.g., bulletin board, group page etc.).
                   2670: #  output: array of five scalars -- 
1.1193    raeburn  2671: #          $cfile -- url for file editing if editable on current server
                   2672: #          $home -- homeserver of resource (i.e., for author if published,
                   2673: #                                           or course if uploaded.).
                   2674: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2675: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2676: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2677: #
                   2678: 
                   2679: sub can_edit_resource {
1.1194    raeburn  2680:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2681:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2682: #
                   2683: # For aboutme pages user can only edit his/her own.
                   2684: #
1.1199    raeburn  2685:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2686:         my ($sdom,$sname) = ($1,$2);
                   2687:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2688:             $home = $env{'user.home'};
                   2689:             $cfile = $resurl;
                   2690:             if ($env{'form.forceedit'}) {
                   2691:                 $forceview = 1;
                   2692:             } else {
                   2693:                 $forceedit = 1;
                   2694:             }
                   2695:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2696:         } else {
                   2697:             return;
                   2698:         }
                   2699:     }
                   2700: 
                   2701:     if ($env{'request.course.id'}) {
                   2702:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2703:         if ($group ne '') {
                   2704: # if this is a group homepage or group bulletin board, check group privs
                   2705:             my $allowed = 0;
1.1197    raeburn  2706:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2707:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2708:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2709:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2710:                     $allowed = 1;
                   2711:                 }
1.1197    raeburn  2712:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2713:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2714:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2715:                     $allowed = 1;
                   2716:                 }
                   2717:             }
                   2718:             if ($allowed) {
                   2719:                 $home=&homeserver($cnum,$cdom);
                   2720:                 if ($env{'form.forceedit'}) {
                   2721:                     $forceview = 1;
                   2722:                 } else {
                   2723:                     $forceedit = 1;
                   2724:                 }
                   2725:                 $cfile = $resurl;
                   2726:             } else {
                   2727:                 return;
                   2728:             }
                   2729:         } else {
1.1208    raeburn  2730:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2731:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2732:                     return;
                   2733:                 }
                   2734:             } elsif (!$crsedit) {
1.1194    raeburn  2735: #
                   2736: # No edit allowed where CC has switched to student role.
                   2737: #
                   2738:                 return;
                   2739:             }
                   2740:         }
                   2741:     }
                   2742: 
1.1193    raeburn  2743:     if ($file ne '') {
                   2744:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2745:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2746:                 $uploaded = 1;
                   2747:                 $incourse = 1;
1.1193    raeburn  2748:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2749:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2750:                     if ($env{'form.forceedit'}) {
                   2751:                         $forceview = 1;
                   2752:                     } else {
                   2753:                         $forceedit = 1;
                   2754:                     }
1.1194    raeburn  2755:                 }
                   2756:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2757:                 $incourse = 1;
                   2758:                 if ($env{'form.forceedit'}) {
                   2759:                     $forceview = 1;
                   2760:                 } else {
                   2761:                     $forceedit = 1;
                   2762:                 }
                   2763:                 $cfile = $resurl;
                   2764:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2765:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2766:                     $incourse = 1;
                   2767:                     if ($env{'form.forceedit'}) {
                   2768:                         $forceview = 1;
                   2769:                     } else {
                   2770:                         $forceedit = 1;
                   2771:                     }
                   2772:                     $cfile = $resurl;
1.1199    raeburn  2773:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2774:                     $incourse = 1;
                   2775:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2776:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2777:                     $incourse = 1;
1.1199    raeburn  2778:                     if ($env{'form.forceedit'}) {
                   2779:                         $forceview = 1;
                   2780:                     } else {
                   2781:                         $forceedit = 1;
                   2782:                     }
                   2783:                     $cfile = $resurl;
1.1208    raeburn  2784:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2785:                     $incourse = 1;
                   2786:                     if ($env{'form.forceedit'}) {
                   2787:                         $forceview = 1;
                   2788:                     } else {
                   2789:                         $forceedit = 1;
                   2790:                     }
                   2791:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2792:                 }
                   2793:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2794:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2795:                 if (&is_on_map($template)) { 
                   2796:                     $incourse = 1;
                   2797:                     $forceview = 1;
                   2798:                     $cfile = $template;
1.1193    raeburn  2799:                 }
1.1199    raeburn  2800:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2801:                     $incourse = 1;
                   2802:                     if ($env{'form.forceedit'}) {
                   2803:                         $forceview = 1;
                   2804:                     } else {
                   2805:                         $forceedit = 1;
                   2806:                     }
                   2807:                     $cfile = $resurl;
                   2808:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2809:                 $incourse = 1;
                   2810:                 $forceview = 1;
                   2811:                 if ($symb) {
                   2812:                     my ($map,$id,$res)=&decode_symb($symb);
                   2813:                     $env{'request.symb'} = $symb;
                   2814:                     $cfile = &clutter($res);
                   2815:                 } else {
                   2816:                     $cfile = $env{'form.suppurl'};
                   2817:                     $cfile =~ s{^http://}{};
                   2818:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2819:                 }
1.1193    raeburn  2820:             }
                   2821:         }
1.1194    raeburn  2822:         if ($uploaded || $incourse) {
                   2823:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2824:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2825:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2826:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2827:             # Check that the user has permission to edit this resource
                   2828:             my $setpriv = 1;
                   2829:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2830:             if (defined($cfudom)) {
                   2831:                 $home=&homeserver($cfuname,$cfudom);
                   2832:                 $cfile=$file;
                   2833:             }
                   2834:         }
1.1194    raeburn  2835:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2836:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2837:             my @ids=&current_machine_ids();
                   2838:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2839:                 $switchserver=1;
                   2840:             }
                   2841:         }
                   2842:     }
1.1194    raeburn  2843:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2844: }
                   2845: 
                   2846: sub is_course_upload {
                   2847:     my ($file,$cnum,$cdom) = @_;
                   2848:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2849:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2850:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2851:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2852:         return 1;
                   2853:     }
                   2854:     return;
                   2855: }
                   2856: 
1.1194    raeburn  2857: sub in_course {
1.1195    raeburn  2858:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2859:     if ($hideprivileged) {
                   2860:         my $skipuser;
                   2861:         if (&privileged($uname,$udom)) {
                   2862:             $skipuser = 1;
                   2863:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2864:             if ($coursehash{'nothideprivileged'}) {
                   2865:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2866:                     my $user;
                   2867:                     if ($item =~ /:/) {
                   2868:                         $user = $item;
                   2869:                     } else {
                   2870:                         $user = join(':',split(/[\@]/,$item));
                   2871:                     }
                   2872:                     if ($user eq $uname.':'.$udom) {
                   2873:                         undef($skipuser);
                   2874:                         last;
                   2875:                     }
                   2876:                 }
                   2877:             }
                   2878:             if ($skipuser) {
                   2879:                 return 0;
                   2880:             }
                   2881:         }
                   2882:     }
1.1194    raeburn  2883:     $type ||= 'any';
                   2884:     if (!defined($cdom) || !defined($cnum)) {
                   2885:         my $cid  = $env{'request.course.id'};
                   2886:         $cdom = $env{'course.'.$cid.'.domain'};
                   2887:         $cnum = $env{'course.'.$cid.'.num'};
                   2888:     }
                   2889:     my $typesref;
1.1195    raeburn  2890:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  2891:         $typesref = ['active','previous','future'];
                   2892:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2893:         $typesref = [$type];
                   2894:     }
                   2895:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2896:                               $typesref,undef,[$cdom]);
                   2897:     my ($tmp) = keys(%roles);
                   2898:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2899:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2900:     if (@course_roles > 0) {
                   2901:         return 1;
                   2902:     }
                   2903:     return 0;
                   2904: }
                   2905: 
1.478     albertel 2906: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2907: # input: action, courseID, current domain, intended
1.637     raeburn  2908: #        path to file, source of file, instruction to parse file for objects,
                   2909: #        ref to hash for embedded objects,
                   2910: #        ref to hash for codebase of java objects.
1.1095    raeburn  2911: #        reference to scalar to accommodate mime type determined
                   2912: #          from File::MMagic if $parser = parse.
1.637     raeburn  2913: #
1.485     raeburn  2914: # output: url to file (if action was uploaddoc), 
                   2915: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2916: #
1.478     albertel 2917: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2918: # course.
1.477     raeburn  2919: #
1.478     albertel 2920: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2921: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2922: #          course's home server.
1.477     raeburn  2923: #
1.478     albertel 2924: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2925: #          be copied from $source (current location) to 
                   2926: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2927: #         and will then be copied to
                   2928: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2929: #         course's home server.
1.485     raeburn  2930: #
1.481     raeburn  2931: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2932: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2933: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2934: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2935: #         in course's home server.
1.637     raeburn  2936: #
1.477     raeburn  2937: 
                   2938: sub process_coursefile {
1.1095    raeburn  2939:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2940:         $mimetype)=@_;
1.477     raeburn  2941:     my $fetchresult;
1.638     albertel 2942:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2943:     if ($action eq 'propagate') {
1.638     albertel 2944:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2945: 			     $home);
1.481     raeburn  2946:     } else {
1.477     raeburn  2947:         my $fpath = '';
                   2948:         my $fname = $file;
1.478     albertel 2949:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2950:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2951:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2952:         if ($action eq 'copy') {
                   2953:             if ($source eq '') {
                   2954:                 $fetchresult = 'no source file';
                   2955:                 return $fetchresult;
                   2956:             } else {
                   2957:                 my $destination = $filepath.'/'.$fname;
                   2958:                 rename($source,$destination);
                   2959:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2960:                                  $home);
1.481     raeburn  2961:             }
                   2962:         } elsif ($action eq 'uploaddoc') {
                   2963:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2964:             print $fh $env{'form.'.$source};
1.481     raeburn  2965:             close($fh);
1.637     raeburn  2966:             if ($parser eq 'parse') {
1.1024    raeburn  2967:                 my $mm = new File::MMagic;
1.1095    raeburn  2968:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2969:                 if ($type eq 'text/html') {
1.1024    raeburn  2970:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2971:                     unless ($parse_result eq 'ok') {
                   2972:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2973:                     }
1.637     raeburn  2974:                 }
1.1095    raeburn  2975:                 if (ref($mimetype)) {
                   2976:                     $$mimetype = $type;
                   2977:                 } 
1.637     raeburn  2978:             }
1.477     raeburn  2979:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2980:                                  $home);
1.481     raeburn  2981:             if ($fetchresult eq 'ok') {
                   2982:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2983:             } else {
                   2984:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2985:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2986:                 return '/adm/notfound.html';
                   2987:             }
1.477     raeburn  2988:         }
                   2989:     }
1.485     raeburn  2990:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2991:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2992:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2993:     }
                   2994:     return $fetchresult;
                   2995: }
                   2996: 
1.637     raeburn  2997: sub build_filepath {
                   2998:     my ($fpath) = @_;
                   2999:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3000:     unless ($fpath eq '') {
                   3001:         my @parts=split('/',$fpath);
                   3002:         foreach my $part (@parts) {
                   3003:             $filepath.= '/'.$part;
                   3004:             if ((-e $filepath)!=1) {
                   3005:                 mkdir($filepath,0777);
                   3006:             }
                   3007:         }
                   3008:     }
                   3009:     return $filepath;
                   3010: }
                   3011: 
                   3012: sub store_edited_file {
1.638     albertel 3013:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3014:     my $file = $primary_url;
                   3015:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3016:     my $fpath = '';
                   3017:     my $fname = $file;
                   3018:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3019:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3020:     my $filepath = &build_filepath($fpath);
                   3021:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3022:     print $fh $content;
                   3023:     close($fh);
1.638     albertel 3024:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3025:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3026: 			  $home);
1.637     raeburn  3027:     if ($$fetchresult eq 'ok') {
                   3028:         return '/uploaded/'.$fpath.'/'.$fname;
                   3029:     } else {
1.638     albertel 3030:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3031: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3032:         return '/adm/notfound.html';
                   3033:     }
                   3034: }
                   3035: 
1.531     albertel 3036: sub clean_filename {
1.831     albertel 3037:     my ($fname,$args)=@_;
1.315     www      3038: # Replace Windows backslashes by forward slashes
1.257     www      3039:     $fname=~s/\\/\//g;
1.831     albertel 3040:     if (!$args->{'keep_path'}) {
                   3041:         # Get rid of everything but the actual filename
                   3042: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3043:     }
1.315     www      3044: # Replace spaces by underscores
                   3045:     $fname=~s/\s+/\_/g;
                   3046: # Replace all other weird characters by nothing
1.831     albertel 3047:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3048: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3049: # numbers
                   3050:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3051:     return $fname;
                   3052: }
1.1051    raeburn  3053: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3054: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3055: # image with the same aspect ratio as the original, but with dimensions which do 
                   3056: # not exceed $resizewidth and $resizeheight.
                   3057:  
1.984     neumanie 3058: sub resizeImage {
1.1051    raeburn  3059:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3060:     my $ima = Image::Magick->new;
                   3061:     my $resized;
                   3062:     if (-e $img_path) {
                   3063:         $ima->Read($img_path);
                   3064:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3065:             my $width = $ima->Get('width');
                   3066:             my $height = $ima->Get('height');
                   3067:             if ($width > $resizewidth) {
                   3068: 	        my $factor = $width/$resizewidth;
                   3069:                 my $newheight = $height/$factor;
                   3070:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3071:                 $resized = 1;
                   3072:             }
                   3073:         }
                   3074:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3075:             my $width = $ima->Get('width');
                   3076:             my $height = $ima->Get('height');
                   3077:             if ($height > $resizeheight) {
                   3078:                 my $factor = $height/$resizeheight;
                   3079:                 my $newwidth = $width/$factor;
                   3080:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3081:                 $resized = 1;
                   3082:             }
                   3083:         }
                   3084:         if ($resized) {
                   3085:             $ima->Write($img_path);
                   3086:         }
                   3087:     }
                   3088:     return;
1.977     amueller 3089: }
                   3090: 
1.608     albertel 3091: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3092: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3093: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3094: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3095: #                                    canceloverwrite, or ''. 
                   3096: #                   if 'coursedoc': upload to the current course
                   3097: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3098: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3099: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3100: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3101: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3102: #        $allfiles - reference to hash for embedded objects
                   3103: #        $codebase - reference to hash for codebase of java objects
                   3104: #        $desuname - username for permanent storage of uploaded file
                   3105: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3106: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3107: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3108: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3109: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3110: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3111: #                    from File::MMagic.
1.858     raeburn  3112: # 
1.686     albertel 3113: # output: url of file in userspace, or error: <message> 
                   3114: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3115: 
1.531     albertel 3116: sub userfileupload {
1.1090    raeburn  3117:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3118:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3119:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3120:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3121:     $fname=&clean_filename($fname);
1.1090    raeburn  3122:     # See if there is anything left
1.257     www      3123:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3124:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3125:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3126:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3127:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3128:         my $now = time;
1.1090    raeburn  3129:         my $filepath;
1.1095    raeburn  3130:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3131:              $filepath = 'tmp/helprequests/'.$now;
                   3132:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3133:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3134:                          '_'.$env{'user.domain'}.'/pending';
                   3135:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3136:             my ($docuname,$docudom);
                   3137:             if ($destudom) {
                   3138:                 $docudom = $destudom;
                   3139:             } else {
                   3140:                 $docudom = $env{'user.domain'};
                   3141:             }
                   3142:             if ($destuname) {
                   3143:                 $docuname = $destuname;
                   3144:             } else {
                   3145:                 $docuname = $env{'user.name'};
                   3146:             }
                   3147:             if (exists($env{'form.group'})) {
                   3148:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3149:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3150:             }
                   3151:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3152:             if ($context eq 'canceloverwrite') {
                   3153:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3154:                 if (-e  $tempfile) {
                   3155:                     my @info = stat($tempfile);
                   3156:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3157:                         unlink($tempfile);
                   3158:                     }
                   3159:                 }
                   3160:                 return;
1.523     raeburn  3161:             }
                   3162:         }
1.1090    raeburn  3163:         # Create the directory if not present
1.741     raeburn  3164:         my @parts=split(/\//,$filepath);
                   3165:         my $fullpath = $perlvar{'lonDaemons'};
                   3166:         for (my $i=0;$i<@parts;$i++) {
                   3167:             $fullpath .= '/'.$parts[$i];
                   3168:             if ((-e $fullpath)!=1) {
                   3169:                 mkdir($fullpath,0777);
                   3170:             }
                   3171:         }
                   3172:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3173:         print $fh $env{'form.'.$formname};
                   3174:         close($fh);
1.1090    raeburn  3175:         if ($context eq 'existingfile') {
                   3176:             my @info = stat($fullpath.'/'.$fname);
                   3177:             return ($fullpath.'/'.$fname,$info[9]);
                   3178:         } else {
                   3179:             return $fullpath.'/'.$fname;
                   3180:         }
1.523     raeburn  3181:     }
1.995     raeburn  3182:     if ($subdir eq 'scantron') {
                   3183:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3184:     } else {
1.995     raeburn  3185:         $fname="$subdir/$fname";
                   3186:     }
1.1090    raeburn  3187:     if ($context eq 'coursedoc') {
1.638     albertel 3188: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3189: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3190:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3191:             return &finishuserfileupload($docuname,$docudom,
                   3192: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3193: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3194:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3195:         } else {
1.1218  ! raeburn  3196:             if ($env{'form.folder'}) {
        !          3197:                 $fname=$env{'form.folder'}.'/'.$fname;
        !          3198:             }
1.638     albertel 3199:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3200: 				       $fname,$formname,$parser,
1.1095    raeburn  3201: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3202:         }
1.719     banghart 3203:     } elsif (defined($destuname)) {
                   3204:         my $docuname=$destuname;
                   3205:         my $docudom=$destudom;
1.860     raeburn  3206: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3207: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3208:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3209:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3210:     } else {
1.638     albertel 3211:         my $docuname=$env{'user.name'};
                   3212:         my $docudom=$env{'user.domain'};
1.714     raeburn  3213:         if (exists($env{'form.group'})) {
                   3214:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3215:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3216:         }
1.860     raeburn  3217: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3218: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3219:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3220:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3221:     }
1.271     www      3222: }
                   3223: 
                   3224: sub finishuserfileupload {
1.860     raeburn  3225:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3226:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3227:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3228:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3229:   
1.860     raeburn  3230:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3231:     $file=$fname;
                   3232:     if ($fname=~m|/|) {
                   3233:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3234: 	$path.=$fnamepath.'/';
                   3235:     }
1.259     www      3236:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3237:     my $count;
                   3238:     for ($count=4;$count<=$#parts;$count++) {
                   3239:         $filepath.="/$parts[$count]";
                   3240:         if ((-e $filepath)!=1) {
                   3241: 	    mkdir($filepath,0777);
                   3242:         }
                   3243:     }
1.984     neumanie 3244: 
1.258     www      3245: # Save the file
                   3246:     {
1.701     albertel 3247: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3248: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3249: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3250: 	    return '/adm/notfound.html';
                   3251: 	}
1.1090    raeburn  3252:         if ($context eq 'overwrite') {
1.1117    foxr     3253:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3254:             my $target = $filepath.'/'.$file;
                   3255:             if (-e $source) {
                   3256:                 my @info = stat($source);
                   3257:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3258:                     unless (&File::Copy::move($source,$target)) {
                   3259:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3260:                         return "Moving from $source failed";
                   3261:                     }
                   3262:                 } else {
                   3263:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3264:                 }
                   3265:             } else {
                   3266:                 return "Temporary file: $source missing";
                   3267:             }
                   3268:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3269: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3270: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3271: 	    return '/adm/notfound.html';
                   3272: 	}
1.570     albertel 3273: 	close(FH);
1.1051    raeburn  3274:         if ($resizewidth && $resizeheight) {
                   3275:             my $mm = new File::MMagic;
                   3276:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3277:             if ($mime_type =~ m{^image/}) {
                   3278: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3279:             }  
1.977     amueller 3280: 	}
1.258     www      3281:     }
1.1152    raeburn  3282:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3283:         if (ref($mimetype)) {
                   3284:             if ($$mimetype eq '') {
                   3285:                 my $mm = new File::MMagic;
                   3286:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3287:                 $$mimetype = $type;
                   3288:             }
                   3289:         }
                   3290:     }
1.637     raeburn  3291:     if ($parser eq 'parse') {
1.1152    raeburn  3292:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3293:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3294:                                                        $allfiles,$codebase);
                   3295:             unless ($parse_result eq 'ok') {
                   3296:                 &logthis('Failed to parse '.$filepath.$file.
                   3297: 	   	         ' for embedded media: '.$parse_result); 
                   3298:             }
1.637     raeburn  3299:         }
                   3300:     }
1.860     raeburn  3301:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3302:         my $input = $filepath.'/'.$file;
                   3303:         my $output = $filepath.'/'.'tn-'.$file;
                   3304:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3305:         system("convert -sample $thumbsize $input $output");
                   3306:         if (-e $filepath.'/'.'tn-'.$file) {
                   3307:             $fetchthumb  = 1; 
                   3308:         }
                   3309:     }
1.858     raeburn  3310:  
1.259     www      3311: # Notify homeserver to grep it
                   3312: #
1.984     neumanie 3313:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3314:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3315:     if ($fetchresult eq 'ok') {
1.860     raeburn  3316:         if ($fetchthumb) {
                   3317:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3318:             if ($thumbresult ne 'ok') {
                   3319:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3320:                          $docuhome.': '.$thumbresult);
                   3321:             }
                   3322:         }
1.259     www      3323: #
1.258     www      3324: # Return the URL to it
1.494     albertel 3325:         return '/uploaded/'.$path.$file;
1.263     www      3326:     } else {
1.494     albertel 3327:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3328: 		 ': '.$fetchresult);
1.263     www      3329:         return '/adm/notfound.html';
1.858     raeburn  3330:     }
1.493     albertel 3331: }
                   3332: 
1.637     raeburn  3333: sub extract_embedded_items {
1.961     raeburn  3334:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3335:     my @state = ();
1.1164    raeburn  3336:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3337:     my %javafiles = (
                   3338:                       codebase => '',
                   3339:                       code => '',
                   3340:                       archive => ''
                   3341:                     );
                   3342:     my %mediafiles = (
                   3343:                       src => '',
                   3344:                       movie => '',
                   3345:                      );
1.648     raeburn  3346:     my $p;
                   3347:     if ($content) {
                   3348:         $p = HTML::LCParser->new($content);
                   3349:     } else {
1.961     raeburn  3350:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3351:     }
1.641     albertel 3352:     while (my $t=$p->get_token()) {
1.640     albertel 3353: 	if ($t->[0] eq 'S') {
                   3354: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3355: 	    push(@state, $tagname);
1.648     raeburn  3356:             if (lc($tagname) eq 'allow') {
                   3357:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3358:             }
1.640     albertel 3359: 	    if (lc($tagname) eq 'img') {
                   3360: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3361: 	    }
1.886     albertel 3362: 	    if (lc($tagname) eq 'a') {
                   3363: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3364: 	    }
1.645     raeburn  3365:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3366:                 my $src;
1.645     raeburn  3367:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3368:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3369:                 } else {
1.1164    raeburn  3370:                     if ($attr->{'src'} ne '') {
                   3371:                         $src = $attr->{'src'};
                   3372:                         &add_filetype($allfiles,$src,'src');
                   3373:                     }
                   3374:                 }
                   3375:                 my $text = $p->get_trimmed_text();
                   3376:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3377:                     my @swfargs = split(/,/,$1);
                   3378:                     foreach my $item (@swfargs) {
                   3379:                         $item =~ s/["']//g;
                   3380:                         $item =~ s/^\s+//;
                   3381:                         $item =~ s/\s+$//;
                   3382:                     }
                   3383:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3384:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3385:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3386:                         } else {
                   3387:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3388:                         }
                   3389:                     }
1.645     raeburn  3390:                 }
                   3391:             }
                   3392:             if (lc($tagname) eq 'link') {
                   3393:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3394:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3395:                 }
                   3396:             }
1.640     albertel 3397: 	    if (lc($tagname) eq 'object' ||
                   3398: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3399: 		foreach my $item (keys(%javafiles)) {
                   3400: 		    $javafiles{$item} = '';
                   3401: 		}
1.1164    raeburn  3402:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3403:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3404:                 }
1.640     albertel 3405: 	    }
                   3406: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3407: 		my $name = lc($attr->{'name'});
                   3408: 		foreach my $item (keys(%javafiles)) {
                   3409: 		    if ($name eq $item) {
                   3410: 			$javafiles{$item} = $attr->{'value'};
                   3411: 			last;
                   3412: 		    }
                   3413: 		}
1.1164    raeburn  3414:                 my $pathfrom;
1.640     albertel 3415: 		foreach my $item (keys(%mediafiles)) {
                   3416: 		    if ($name eq $item) {
1.1164    raeburn  3417:                         $pathfrom = $attr->{'value'};
                   3418:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3419: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3420: 			last;
                   3421: 		    }
                   3422: 		}
1.1164    raeburn  3423:                 if ($name eq 'flashvars') {
                   3424:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3425:                 }
                   3426:                 if ($pathfrom ne '') {
                   3427:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3428:                                          $pathfrom);
                   3429:                 }
1.640     albertel 3430: 	    }
                   3431: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3432: 		foreach my $item (keys(%javafiles)) {
                   3433: 		    if ($attr->{$item}) {
                   3434: 			$javafiles{$item} = $attr->{$item};
                   3435: 			last;
                   3436: 		    }
                   3437: 		}
                   3438: 		foreach my $item (keys(%mediafiles)) {
                   3439: 		    if ($attr->{$item}) {
                   3440: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3441: 			last;
                   3442: 		    }
                   3443: 		}
1.1164    raeburn  3444:                 if (lc($tagname) eq 'embed') {
                   3445:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3446:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3447:                                              $attr->{'src'});
                   3448:                     }
                   3449:                 }
1.640     albertel 3450: 	    }
1.1164    raeburn  3451:             if ($t->[4] =~ m{/>$}) {
                   3452:                 pop(@state);  
                   3453:             }
1.640     albertel 3454: 	} elsif ($t->[0] eq 'E') {
                   3455: 	    my ($tagname) = ($t->[1]);
                   3456: 	    if ($javafiles{'codebase'} ne '') {
                   3457: 		$javafiles{'codebase'} .= '/';
                   3458: 	    }  
                   3459: 	    if (lc($tagname) eq 'applet' ||
                   3460: 		lc($tagname) eq 'object' ||
                   3461: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3462: 		) {
                   3463: 		foreach my $item (keys(%javafiles)) {
                   3464: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3465: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3466: 			&add_filetype($allfiles,$file,$item);
                   3467: 		    }
                   3468: 		}
                   3469: 	    } 
                   3470: 	    pop @state;
                   3471: 	}
                   3472:     }
1.1164    raeburn  3473:     foreach my $id (sort(keys(%flashvars))) {
                   3474:         if ($shockwave{$id} ne '') {
                   3475:             my @pairs = split(/\&/,$flashvars{$id});
                   3476:             foreach my $pair (@pairs) {
                   3477:                 my ($key,$value) = split(/\=/,$pair);
                   3478:                 if ($key eq 'thumb') {
                   3479:                     &add_filetype($allfiles,$value,$key);
                   3480:                 } elsif ($key eq 'content') {
                   3481:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3482:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3483:                     if ($ext ne '') {
                   3484:                         &add_filetype($allfiles,$path.$value,$ext);
                   3485:                     }
                   3486:                 }
                   3487:             }
                   3488:         }
                   3489:     }
1.637     raeburn  3490:     return 'ok';
                   3491: }
                   3492: 
1.639     albertel 3493: sub add_filetype {
                   3494:     my ($allfiles,$file,$type)=@_;
                   3495:     if (exists($allfiles->{$file})) {
                   3496: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3497: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3498: 	}
                   3499:     } else {
                   3500: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3501:     }
                   3502: }
                   3503: 
1.1164    raeburn  3504: sub embedded_dependency {
                   3505:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3506:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3507:         if (($identifier ne '') &&
                   3508:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3509:             ($pathfrom ne '')) {
                   3510:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3511:             foreach my $dep (@{$related->{$identifier}}) {
                   3512:                 &add_filetype($allfiles,$path.$dep,'object');
                   3513:             }
                   3514:         }
                   3515:     }
                   3516:     return;
                   3517: }
                   3518: 
1.493     albertel 3519: sub removeuploadedurl {
1.984     neumanie 3520:     my ($url)=@_;	
                   3521:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3522:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3523: }
                   3524: 
                   3525: sub removeuserfile {
                   3526:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3527:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3528:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3529:     if ($result eq 'ok') {	
1.798     raeburn  3530:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3531:             my $metafile = $fname.'.meta';
                   3532:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3533: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3534:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3535:             my $sqlresult = 
1.823     albertel 3536:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3537:                                         'portfolio_metadata',$group,
                   3538:                                         'delete');
1.798     raeburn  3539:         }
                   3540:     }
                   3541:     return $result;
1.257     www      3542: }
1.15      www      3543: 
1.530     albertel 3544: sub mkdiruserfile {
                   3545:     my ($docuname,$docudom,$dir)=@_;
                   3546:     my $home=&homeserver($docuname,$docudom);
                   3547:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3548: }
                   3549: 
1.531     albertel 3550: sub renameuserfile {
                   3551:     my ($docuname,$docudom,$old,$new)=@_;
                   3552:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3553:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3554:                         &escape("$old").':'.&escape("$new"),$home);
                   3555:     if ($result eq 'ok') {
                   3556:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3557:             my $oldmeta = $old.'.meta';
                   3558:             my $newmeta = $new.'.meta';
                   3559:             my $metaresult = 
                   3560:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3561: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3562:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3563:             my $sqlresult = 
1.823     albertel 3564:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3565:                                         'portfolio_metadata',$group,
                   3566:                                         'delete');
1.798     raeburn  3567:         }
                   3568:     }
                   3569:     return $result;
1.531     albertel 3570: }
                   3571: 
1.14      www      3572: # ------------------------------------------------------------------------- Log
                   3573: 
                   3574: sub log {
                   3575:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3576:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3577: }
                   3578: 
                   3579: # ------------------------------------------------------------------ Course Log
1.352     www      3580: #
                   3581: # This routine flushes several buffers of non-mission-critical nature
                   3582: #
1.157     www      3583: 
                   3584: sub flushcourselogs {
1.352     www      3585:     &logthis('Flushing log buffers');
                   3586: #
                   3587: # course logs
                   3588: # This is a log of all transactions in a course, which can be used
                   3589: # for data mining purposes
                   3590: #
                   3591: # It also collects the courseid database, which lists last transaction
                   3592: # times and course titles for all courseids
                   3593: #
                   3594:     my %courseidbuffer=();
1.921     raeburn  3595:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3596:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3597: 		          &escape($courselogs{$crsid}),
                   3598: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3599: 	    delete $courselogs{$crsid};
                   3600:         } else {
                   3601:             &logthis('Failed to flush log buffer for '.$crsid);
                   3602:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3603:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3604:                         " exceeded maximum size, deleting.</font>");
                   3605:                delete $courselogs{$crsid};
                   3606:             }
1.352     www      3607:         }
1.920     raeburn  3608:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3609:             'description' => $coursedescrbuf{$crsid},
                   3610:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3611:             'type'        => $coursetypebuf{$crsid},
                   3612:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3613:         };
1.191     harris41 3614:     }
1.352     www      3615: #
                   3616: # Write course id database (reverse lookup) to homeserver of courses 
                   3617: # Is used in pickcourse
                   3618: #
1.840     albertel 3619:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3620:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3621:                                     $courseidbuffer{$crs_home},
                   3622:                                     $crs_home,'timeonly');
1.352     www      3623:     }
                   3624: #
                   3625: # File accesses
                   3626: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3627: #
1.449     matthew  3628:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3629:         if ($entry =~ /___count$/) {
                   3630:             my ($dom,$name);
1.807     albertel 3631:             ($dom,$name,undef)=
1.811     albertel 3632: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3633:             if (! defined($dom) || $dom eq '' || 
                   3634:                 ! defined($name) || $name eq '') {
1.620     albertel 3635:                 my $cid = $env{'request.course.id'};
                   3636:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3637:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3638:             }
1.450     matthew  3639:             my $value = $accesshash{$entry};
                   3640:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3641:             my %temphash=($url => $value);
1.449     matthew  3642:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3643:             if ($result eq 'ok') {
                   3644:                 delete $accesshash{$entry};
                   3645:             }
                   3646:         } else {
1.811     albertel 3647:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3648:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3649:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3650:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3651:                 delete $accesshash{$entry};
                   3652:             }
1.185     www      3653:         }
1.191     harris41 3654:     }
1.352     www      3655: #
                   3656: # Roles
                   3657: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3658: #
1.800     albertel 3659:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3660:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3661: 	    split(/\:/,$entry);
                   3662:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3663:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3664:                 $rudom,$runame) eq 'ok') {
                   3665: 	    delete $userrolehash{$entry};
                   3666:         }
                   3667:     }
1.662     raeburn  3668: #
                   3669: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3670: #
                   3671:     my %domrolebuffer = ();
1.1000    raeburn  3672:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3673:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3674:         if ($domrolebuffer{$rudom}) {
                   3675:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3676:                       '='.&escape($domainrolehash{$entry});
                   3677:         } else {
                   3678:             $domrolebuffer{$rudom}.=&escape($entry).
                   3679:                       '='.&escape($domainrolehash{$entry});
                   3680:         }
                   3681:         delete $domainrolehash{$entry};
                   3682:     }
                   3683:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3684: 	my %servers = &get_servers($dom,'library');
                   3685: 	foreach my $tryserver (keys(%servers)) {
                   3686: 	    unless (&reply('domroleput:'.$dom.':'.
                   3687: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3688: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3689: 	    }
1.662     raeburn  3690:         }
                   3691:     }
1.186     www      3692:     $dumpcount++;
1.157     www      3693: }
                   3694: 
                   3695: sub courselog {
                   3696:     my $what=shift;
1.158     www      3697:     $what=time.':'.$what;
1.620     albertel 3698:     unless ($env{'request.course.id'}) { return ''; }
                   3699:     $coursedombuf{$env{'request.course.id'}}=
                   3700:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3701:     $coursenumbuf{$env{'request.course.id'}}=
                   3702:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3703:     $coursehombuf{$env{'request.course.id'}}=
                   3704:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3705:     $coursedescrbuf{$env{'request.course.id'}}=
                   3706:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3707:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3708:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3709:     $courseownerbuf{$env{'request.course.id'}}=
                   3710:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3711:     $coursetypebuf{$env{'request.course.id'}}=
                   3712:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3713:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3714: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3715:     } else {
1.620     albertel 3716: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3717:     }
1.620     albertel 3718:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3719: 	&flushcourselogs();
                   3720:     }
1.158     www      3721: }
                   3722: 
                   3723: sub courseacclog {
                   3724:     my $fnsymb=shift;
1.620     albertel 3725:     unless ($env{'request.course.id'}) { return ''; }
                   3726:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3727:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3728:         $what.=':POST';
1.583     matthew  3729:         # FIXME: Probably ought to escape things....
1.800     albertel 3730: 	foreach my $key (keys(%env)) {
                   3731:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3732:                 my $formitem = $1;
                   3733:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3734:                     $what.=':'.$formitem.'='.$env{$key};
                   3735:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3736:                     $what.=':'.$formitem.'='.$env{$key};
                   3737:                 }
1.158     www      3738:             }
1.191     harris41 3739:         }
1.583     matthew  3740:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3741:         # FIXME: We should not be depending on a form parameter that someone
                   3742:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3743:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3744:             $what.= ':POST';
                   3745:             # FIXME: Probably ought to escape things....
                   3746:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3747:                                  'crsdiscuss') {
1.620     albertel 3748:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3749:             }
                   3750:         }
1.158     www      3751:     }
                   3752:     &courselog($what);
1.149     www      3753: }
                   3754: 
1.185     www      3755: sub countacc {
                   3756:     my $url=&declutter(shift);
1.458     matthew  3757:     return if (! defined($url) || $url eq '');
1.620     albertel 3758:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3759: #
                   3760: # Mark that this url was used in this course
                   3761: #
1.620     albertel 3762:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3763: #
                   3764: # Increase the access count for this resource in this child process
                   3765: #
1.281     www      3766:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3767:     $accesshash{$key}++;
1.185     www      3768: }
1.349     www      3769: 
1.361     www      3770: sub linklog {
                   3771:     my ($from,$to)=@_;
                   3772:     $from=&declutter($from);
                   3773:     $to=&declutter($to);
                   3774:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3775:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3776: }
1.1160    www      3777: 
                   3778: sub statslog {
                   3779:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3780:     if ($users<2) { return; }
                   3781:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3782:             'course'       => $env{'request.course.id'},
                   3783:             'sections'     => '"all"',
                   3784:             'num_students' => $users,
                   3785:             'part'         => $part,
                   3786:             'symb'         => $symb,
                   3787:             'mean_tries'   => $av_attempts,
                   3788:             'deg_of_diff'  => $degdiff});
                   3789:     foreach my $key (keys(%dynstore)) {
                   3790:         $accesshash{$key}=$dynstore{$key};
                   3791:     }
                   3792: }
1.361     www      3793:   
1.349     www      3794: sub userrolelog {
                   3795:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3796:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3797:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3798:        $userrolehash
                   3799:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3800:                     =$tend.':'.$tstart;
1.662     raeburn  3801:     }
1.1169    droeschl 3802:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3803:        $userrolehash
                   3804:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3805:                     =$tend.':'.$tstart;
                   3806:     }
1.1169    droeschl 3807:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3808:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3809:        $domainrolehash
                   3810:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3811:                     = $tend.':'.$tstart;
                   3812:     }
1.351     www      3813: }
                   3814: 
1.957     raeburn  3815: sub courserolelog {
                   3816:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3817:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3818:         my $cdom = $1;
                   3819:         my $cnum = $2;
                   3820:         my $sec = $3;
                   3821:         my $namespace = 'rolelog';
                   3822:         my %storehash = (
                   3823:                            role    => $trole,
                   3824:                            start   => $tstart,
                   3825:                            end     => $tend,
                   3826:                            selfenroll => $selfenroll,
                   3827:                            context    => $context,
                   3828:                         );
                   3829:         if ($trole eq 'gr') {
                   3830:             $namespace = 'groupslog';
                   3831:             $storehash{'group'} = $sec;
                   3832:         } else {
                   3833:             $storehash{'section'} = $sec;
                   3834:         }
1.1188    raeburn  3835:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3836:                    $domain,$cnum,$cdom);
1.1184    raeburn  3837:         if (($trole ne 'st') || ($sec ne '')) {
                   3838:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3839:         }
                   3840:     }
                   3841:     return;
                   3842: }
                   3843: 
1.1184    raeburn  3844: sub domainrolelog {
                   3845:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3846:     if ($area =~ m{^/($match_domain)/$}) {
                   3847:         my $cdom = $1;
                   3848:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3849:         my $namespace = 'rolelog';
                   3850:         my %storehash = (
                   3851:                            role    => $trole,
                   3852:                            start   => $tstart,
                   3853:                            end     => $tend,
                   3854:                            context => $context,
                   3855:                         );
1.1188    raeburn  3856:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3857:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3858:     }
                   3859:     return;
                   3860: 
                   3861: }
                   3862: 
                   3863: sub coauthorrolelog {
                   3864:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3865:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3866:         my $audom = $1;
                   3867:         my $auname = $2;
                   3868:         my $namespace = 'rolelog';
                   3869:         my %storehash = (
                   3870:                            role    => $trole,
                   3871:                            start   => $tstart,
                   3872:                            end     => $tend,
                   3873:                            context => $context,
                   3874:                         );
1.1188    raeburn  3875:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3876:                    $domain,$auname,$audom);
1.1184    raeburn  3877:     }
                   3878:     return;
                   3879: }
                   3880: 
1.351     www      3881: sub get_course_adv_roles {
1.948     raeburn  3882:     my ($cid,$codes) = @_;
1.620     albertel 3883:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3884:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3885:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3886:     my %nothide=();
1.800     albertel 3887:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3888:         if ($user !~ /:/) {
                   3889: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3890:         } else {
                   3891:             $nothide{$user}=1;
                   3892:         }
1.470     www      3893:     }
1.351     www      3894:     my %returnhash=();
                   3895:     my %dumphash=
                   3896:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3897:     my $now=time;
1.997     raeburn  3898:     my %privileged;
1.1000    raeburn  3899:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3900: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3901:         if (($tstart) && ($tstart<0)) { next; }
                   3902:         if (($tend) && ($tend<$now)) { next; }
                   3903:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3904:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3905: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3906:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3907:             my %dompersonnel =
1.998     raeburn  3908:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3909:             $privileged{$domain} = {};
                   3910:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3911:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3912:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3913:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3914:                         $privileged{$udom}{$uname} = 1;
                   3915:                     }
                   3916:                 }
                   3917:             }
                   3918:         }
                   3919:         if ((exists($privileged{$domain}{$username})) && 
                   3920:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3921: 	if ($role eq 'cr') { next; }
1.948     raeburn  3922:         if ($codes) {
                   3923:             if ($section) { $role .= ':'.$section; }
                   3924:             if ($returnhash{$role}) {
                   3925:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3926:             } else {
                   3927:                 $returnhash{$role}=$username.':'.$domain;
                   3928:             }
1.351     www      3929:         } else {
1.988     raeburn  3930:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3931:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3932:             if ($returnhash{$key}) {
                   3933: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3934:             } else {
                   3935:                 $returnhash{$key}=$username.':'.$domain;
                   3936:             }
1.351     www      3937:         }
1.948     raeburn  3938:     }
1.400     www      3939:     return %returnhash;
                   3940: }
                   3941: 
                   3942: sub get_my_roles {
1.937     raeburn  3943:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3944:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3945:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3946:     my (%dumphash,%nothide);
1.1086    raeburn  3947:     if ($context eq 'userroles') {
1.1166    raeburn  3948:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3949:     } else {
                   3950:         %dumphash=
1.400     www      3951:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3952:         if ($hidepriv) {
                   3953:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3954:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3955:                 if ($user !~ /:/) {
                   3956:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3957:                 } else {
                   3958:                     $nothide{$user} = 1;
                   3959:                 }
                   3960:             }
                   3961:         }
1.858     raeburn  3962:     }
1.400     www      3963:     my %returnhash=();
                   3964:     my $now=time;
1.999     raeburn  3965:     my %privileged;
1.800     albertel 3966:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3967:         my ($role,$tend,$tstart);
                   3968:         if ($context eq 'userroles') {
1.1149    raeburn  3969:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3970: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3971:         } else {
                   3972:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3973:         }
1.400     www      3974:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3975:         my $status = 'active';
1.939     raeburn  3976:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3977:             $status = 'previous';
                   3978:         } 
                   3979:         if (($tstart) && ($now<$tstart)) {
                   3980:             $status = 'future';
                   3981:         }
                   3982:         if (ref($types) eq 'ARRAY') {
                   3983:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3984:                 next;
                   3985:             } 
                   3986:         } else {
                   3987:             if ($status ne 'active') {
                   3988:                 next;
                   3989:             }
                   3990:         }
1.867     raeburn  3991:         my ($rolecode,$username,$domain,$section,$area);
                   3992:         if ($context eq 'userroles') {
1.1186    raeburn  3993:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3994:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3995:         } else {
                   3996:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3997:         }
1.832     raeburn  3998:         if (ref($roledoms) eq 'ARRAY') {
                   3999:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4000:                 next;
                   4001:             }
                   4002:         }
                   4003:         if (ref($roles) eq 'ARRAY') {
                   4004:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4005:                 if ($role =~ /^cr\//) {
                   4006:                     if (!grep(/^cr$/,@{$roles})) {
                   4007:                         next;
                   4008:                     }
1.1104    raeburn  4009:                 } elsif ($role =~ /^gr\//) {
                   4010:                     if (!grep(/^gr$/,@{$roles})) {
                   4011:                         next;
                   4012:                     }
1.922     raeburn  4013:                 } else {
                   4014:                     next;
                   4015:                 }
1.832     raeburn  4016:             }
1.867     raeburn  4017:         }
1.937     raeburn  4018:         if ($hidepriv) {
1.999     raeburn  4019:             if ($context eq 'userroles') {
                   4020:                 if ((&privileged($username,$domain)) &&
                   4021:                     (!$nothide{$username.':'.$domain})) {
                   4022:                     next;
                   4023:                 }
                   4024:             } else {
                   4025:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   4026:                     my %dompersonnel =
                   4027:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   4028:                     $privileged{$domain} = {};
                   4029:                     if (keys(%dompersonnel)) {
                   4030:                         foreach my $server (keys(%dompersonnel)) {
                   4031:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   4032:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   4033:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   4034:                                     $privileged{$udom}{$uname} = $trole;
                   4035:                                 }
                   4036:                             }
                   4037:                         }
                   4038:                     }
                   4039:                 }
                   4040:                 if (exists($privileged{$domain}{$username})) {
                   4041:                     if (!$nothide{$username.':'.$domain}) {
                   4042:                         next;
                   4043:                     }
                   4044:                 }
1.937     raeburn  4045:             }
                   4046:         }
1.933     raeburn  4047:         if ($withsec) {
                   4048:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4049:                 $tstart.':'.$tend;
                   4050:         } else {
                   4051:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4052:         }
1.832     raeburn  4053:     }
1.373     www      4054:     return %returnhash;
1.399     www      4055: }
                   4056: 
                   4057: # ----------------------------------------------------- Frontpage Announcements
                   4058: #
                   4059: #
                   4060: 
                   4061: sub postannounce {
                   4062:     my ($server,$text)=@_;
1.844     albertel 4063:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4064:     unless ($text=~/\w/) { $text=''; }
                   4065:     return &reply('setannounce:'.&escape($text),$server);
                   4066: }
                   4067: 
                   4068: sub getannounce {
1.448     albertel 4069: 
                   4070:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4071: 	my $announcement='';
1.800     albertel 4072: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4073: 	close($fh);
1.399     www      4074: 	if ($announcement=~/\w/) { 
                   4075: 	    return 
                   4076:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4077:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4078: 	} else {
                   4079: 	    return '';
                   4080: 	}
                   4081:     } else {
                   4082: 	return '';
                   4083:     }
1.351     www      4084: }
1.353     www      4085: 
                   4086: # ---------------------------------------------------------- Course ID routines
                   4087: # Deal with domain's nohist_courseid.db files
                   4088: #
                   4089: 
                   4090: sub courseidput {
1.921     raeburn  4091:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4092:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4093:     my $outcome;
                   4094:     if ($caller eq 'timeonly') {
                   4095:         my $cids = '';
                   4096:         foreach my $item (keys(%$storehash)) {
                   4097:             $cids.=&escape($item).'&';
                   4098:         }
                   4099:         $cids=~s/\&$//;
                   4100:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4101:                           $coursehome);       
                   4102:     } else {
                   4103:         my $items = '';
                   4104:         foreach my $item (keys(%$storehash)) {
                   4105:             $items.= &escape($item).'='.
                   4106:                      &freeze_escape($$storehash{$item}).'&';
                   4107:         }
                   4108:         $items=~s/\&$//;
                   4109:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4110:                           $coursehome);
1.918     raeburn  4111:     }
                   4112:     if ($outcome eq 'unknown_cmd') {
                   4113:         my $what;
                   4114:         foreach my $cid (keys(%$storehash)) {
                   4115:             $what .= &escape($cid).'=';
1.921     raeburn  4116:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4117:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4118:             }
                   4119:             $what =~ s/\:$/&/;
                   4120:         }
                   4121:         $what =~ s/\&$//;  
                   4122:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4123:     } else {
                   4124:         return $outcome;
                   4125:     }
1.353     www      4126: }
                   4127: 
                   4128: sub courseiddump {
1.921     raeburn  4129:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4130:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4131:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4132:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4133:     my $as_hash = 1;
                   4134:     my %returnhash;
                   4135:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4136:     my %libserv = &all_library();
                   4137:     foreach my $tryserver (keys(%libserv)) {
                   4138:         if ( (  $hostidflag == 1 
                   4139: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4140: 	     || (!defined($hostidflag)) ) {
                   4141: 
1.918     raeburn  4142: 	    if (($domfilter eq '') ||
                   4143: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4144:                 my $rep;
                   4145:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4146:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4147:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4148:                                 &escape($descfilter), &escape($instcodefilter), 
                   4149:                                 &escape($ownerfilter), &escape($coursefilter),
                   4150:                                 &escape($typefilter), &escape($regexp_ok), 
                   4151:                                 $as_hash, &escape($selfenrollonly), 
                   4152:                                 &escape($catfilter), $showhidden, $caller, 
                   4153:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4154:                                 &escape($createdbefore), &escape($createdafter), 
                   4155:                                 &escape($creationcontext), $domcloner)));
                   4156:                 } else {
                   4157:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4158:                              $sincefilter.':'.&escape($descfilter).':'.
                   4159:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4160:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4161:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4162:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4163:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4164:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4165:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4166:                              &escape($creationcontext).':'.$domcloner,
                   4167:                              $tryserver);
                   4168:                 }
                   4169:                      
1.918     raeburn  4170:                 my @pairs=split(/\&/,$rep);
                   4171:                 foreach my $item (@pairs) {
                   4172:                     my ($key,$value)=split(/\=/,$item,2);
                   4173:                     $key = &unescape($key);
                   4174:                     next if ($key =~ /^error: 2 /);
                   4175:                     my $result = &thaw_unescape($value);
                   4176:                     if (ref($result) eq 'HASH') {
                   4177:                         $returnhash{$key}=$result;
                   4178:                     } else {
1.921     raeburn  4179:                         my @responses = split(/:/,$value);
                   4180:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4181:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4182:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4183:                         }
1.1008    raeburn  4184:                     }
1.353     www      4185:                 }
                   4186:             }
                   4187:         }
                   4188:     }
                   4189:     return %returnhash;
                   4190: }
                   4191: 
1.1055    raeburn  4192: sub courselastaccess {
                   4193:     my ($cdom,$cnum,$hostidref) = @_;
                   4194:     my %returnhash;
                   4195:     if ($cdom && $cnum) {
                   4196:         my $chome = &homeserver($cnum,$cdom);
                   4197:         if ($chome ne 'no_host') {
                   4198:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4199:             &extract_lastaccess(\%returnhash,$rep);
                   4200:         }
                   4201:     } else {
                   4202:         if (!$cdom) { $cdom=''; }
                   4203:         my %libserv = &all_library();
                   4204:         foreach my $tryserver (keys(%libserv)) {
                   4205:             if (ref($hostidref) eq 'ARRAY') {
                   4206:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4207:             } 
                   4208:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4209:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4210:                 &extract_lastaccess(\%returnhash,$rep);
                   4211:             }
                   4212:         }
                   4213:     }
                   4214:     return %returnhash;
                   4215: }
                   4216: 
                   4217: sub extract_lastaccess {
                   4218:     my ($returnhash,$rep) = @_;
                   4219:     if (ref($returnhash) eq 'HASH') {
                   4220:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4221:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4222:                  $rep eq '') {
                   4223:             my @pairs=split(/\&/,$rep);
                   4224:             foreach my $item (@pairs) {
                   4225:                 my ($key,$value)=split(/\=/,$item,2);
                   4226:                 $key = &unescape($key);
                   4227:                 next if ($key =~ /^error: 2 /);
                   4228:                 $returnhash->{$key} = &thaw_unescape($value);
                   4229:             }
                   4230:         }
                   4231:     }
                   4232:     return;
                   4233: }
                   4234: 
1.658     raeburn  4235: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4236: 
                   4237: sub dcmailput {
1.685     raeburn  4238:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4239:     my $status = &Apache::lonnet::critical(
1.740     www      4240:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4241:        &escape($message),$server);
1.662     raeburn  4242:     return $status;
                   4243: }
                   4244: 
1.658     raeburn  4245: sub dcmaildump {
                   4246:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4247:     my %returnhash=();
1.846     albertel 4248: 
                   4249:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4250:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4251:                                                          &escape($enddate).':';
                   4252: 	my @esc_senders=map { &escape($_)} @$senders;
                   4253: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4254: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4255:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4256:             if (($key) && ($value)) {
                   4257:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4258:             }
                   4259:         }
                   4260:     }
                   4261:     return %returnhash;
                   4262: }
1.662     raeburn  4263: # ---------------------------------------------------------- Domain roles
                   4264: 
                   4265: sub get_domain_roles {
                   4266:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4267:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4268:         $startdate = '.';
                   4269:     }
1.1018    raeburn  4270:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4271:         $enddate = '.';
                   4272:     }
1.922     raeburn  4273:     my $rolelist;
                   4274:     if (ref($roles) eq 'ARRAY') {
                   4275:         $rolelist = join(':',@{$roles});
                   4276:     }
1.662     raeburn  4277:     my %personnel = ();
1.841     albertel 4278: 
                   4279:     my %servers = &get_servers($dom,'library');
                   4280:     foreach my $tryserver (keys(%servers)) {
                   4281: 	%{$personnel{$tryserver}}=();
                   4282: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4283: 					    &escape($startdate).':'.
                   4284: 					    &escape($enddate).':'.
                   4285: 					    &escape($rolelist), $tryserver))) {
                   4286: 	    my ($key,$value) = split(/\=/,$line,2);
                   4287: 	    if (($key) && ($value)) {
                   4288: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4289: 	    }
                   4290: 	}
1.662     raeburn  4291:     }
                   4292:     return %personnel;
                   4293: }
1.658     raeburn  4294: 
1.1057    www      4295: # ----------------------------------------------------------- Interval timing 
1.149     www      4296: 
1.1153    www      4297: {
                   4298: # Caches needed for speedup of navmaps
                   4299: # We don't want to cache this for very long at all (5 seconds at most)
                   4300: # 
                   4301: # The user for whom we cache
                   4302: my $cachedkey='';
                   4303: # The cached times for this user
                   4304: my %cachedtimes=();
                   4305: # When this was last done
                   4306: my $cachedtime=();
                   4307: 
                   4308: sub load_all_first_access {
1.1154    raeburn  4309:     my ($uname,$udom)=@_;
1.1156    www      4310:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4311:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4312:         return;
                   4313:     }
                   4314:     $cachedtime=time;
                   4315:     $cachedkey=$uname.':'.$udom;
                   4316:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4317: }
                   4318: 
1.504     albertel 4319: sub get_first_access {
1.1162    raeburn  4320:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4321:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4322:     if ($argsymb) { $symb=$argsymb; }
                   4323:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4324:     if ($argmap) { $map = $argmap; }
1.926     albertel 4325:     if ($type eq 'course') {
                   4326: 	$res='course';
                   4327:     } elsif ($type eq 'map') {
1.588     albertel 4328: 	$res=&symbread($map);
                   4329:     } else {
                   4330: 	$res=$symb;
                   4331:     }
1.1153    www      4332:     &load_all_first_access($uname,$udom);
                   4333:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4334: }
                   4335: 
                   4336: sub set_first_access {
1.1162    raeburn  4337:     my ($type,$interval)=@_;
1.790     albertel 4338:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4339:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4340:     if ($type eq 'course') {
                   4341: 	$res='course';
                   4342:     } elsif ($type eq 'map') {
1.588     albertel 4343: 	$res=&symbread($map);
                   4344:     } else {
                   4345: 	$res=$symb;
                   4346:     }
1.1153    www      4347:     $cachedkey='';
1.1162    raeburn  4348:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4349:     if (!$firstaccess) {
1.1162    raeburn  4350:         my $start = time;
                   4351: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4352:                           $udom,$uname);
                   4353:         if ($putres eq 'ok') {
                   4354:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4355:                  $udom,$uname); 
                   4356:             &appenv(
                   4357:                      {
                   4358:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4359:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4360:                      }
                   4361:                   );
                   4362:         }
                   4363:         return $putres;
1.505     albertel 4364:     }
                   4365:     return 'already_set';
1.504     albertel 4366: }
1.1153    www      4367: }
1.110     www      4368: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4369: 
                   4370: sub expirespread {
                   4371:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4372:     my $cid=$env{'request.course.id'}; 
1.110     www      4373:     if ($cid) {
                   4374:        my $now=time;
                   4375:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4376:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4377:                             $env{'course.'.$cid.'.num'}.
1.110     www      4378: 	        	    ':nohist_expirationdates:'.
                   4379:                             &escape($key).'='.$now,
1.620     albertel 4380:                             $env{'course.'.$cid.'.home'})
1.110     www      4381:     }
                   4382:     return 'ok';
1.14      www      4383: }
                   4384: 
1.109     www      4385: # ----------------------------------------------------- Devalidate Spreadsheets
                   4386: 
                   4387: sub devalidate {
1.325     www      4388:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4389:     my $cid=$env{'request.course.id'}; 
1.109     www      4390:     if ($cid) {
1.391     matthew  4391:         # delete the stored spreadsheets for
                   4392:         # - the student level sheet of this user in course's homespace
                   4393:         # - the assessment level sheet for this resource 
                   4394:         #   for this user in user's homespace
1.553     albertel 4395: 	# - current conditional state info
1.325     www      4396: 	my $key=$uname.':'.$udom.':';
1.109     www      4397:         my $status=
1.299     matthew  4398: 	    &del('nohist_calculatedsheets',
1.391     matthew  4399: 		 [$key.'studentcalc:'],
1.620     albertel 4400: 		 $env{'course.'.$cid.'.domain'},
                   4401: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4402: 		.' '.
                   4403: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4404: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4405:         unless ($status eq 'ok ok') {
                   4406:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4407:                     $uname.' at '.$udom.' for '.
1.109     www      4408: 		    $symb.': '.$status);
1.133     albertel 4409:         }
1.553     albertel 4410: 	&delenv('user.state.'.$cid);
1.109     www      4411:     }
                   4412: }
                   4413: 
1.265     albertel 4414: sub get_scalar {
                   4415:     my ($string,$end) = @_;
                   4416:     my $value;
                   4417:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4418: 	$value = $1;
                   4419:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4420: 	$value = $1;
                   4421:     }
                   4422:     return &unescape($value);
                   4423: }
                   4424: 
                   4425: sub array2str {
                   4426:   my (@array) = @_;
                   4427:   my $result=&arrayref2str(\@array);
                   4428:   $result=~s/^__ARRAY_REF__//;
                   4429:   $result=~s/__END_ARRAY_REF__$//;
                   4430:   return $result;
                   4431: }
                   4432: 
1.204     albertel 4433: sub arrayref2str {
                   4434:   my ($arrayref) = @_;
1.265     albertel 4435:   my $result='__ARRAY_REF__';
1.204     albertel 4436:   foreach my $elem (@$arrayref) {
1.265     albertel 4437:     if(ref($elem) eq 'ARRAY') {
                   4438:       $result.=&arrayref2str($elem).'&';
                   4439:     } elsif(ref($elem) eq 'HASH') {
                   4440:       $result.=&hashref2str($elem).'&';
                   4441:     } elsif(ref($elem)) {
                   4442:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4443:     } else {
                   4444:       $result.=&escape($elem).'&';
                   4445:     }
                   4446:   }
                   4447:   $result=~s/\&$//;
1.265     albertel 4448:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4449:   return $result;
                   4450: }
                   4451: 
1.168     albertel 4452: sub hash2str {
1.204     albertel 4453:   my (%hash) = @_;
                   4454:   my $result=&hashref2str(\%hash);
1.265     albertel 4455:   $result=~s/^__HASH_REF__//;
                   4456:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4457:   return $result;
                   4458: }
                   4459: 
                   4460: sub hashref2str {
                   4461:   my ($hashref)=@_;
1.265     albertel 4462:   my $result='__HASH_REF__';
1.800     albertel 4463:   foreach my $key (sort(keys(%$hashref))) {
                   4464:     if (ref($key) eq 'ARRAY') {
                   4465:       $result.=&arrayref2str($key).'=';
                   4466:     } elsif (ref($key) eq 'HASH') {
                   4467:       $result.=&hashref2str($key).'=';
                   4468:     } elsif (ref($key)) {
1.265     albertel 4469:       $result.='=';
1.800     albertel 4470:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4471:     } else {
1.1132    raeburn  4472: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4473:     }
                   4474: 
1.800     albertel 4475:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4476:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4477:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4478:       $result.=&hashref2str($hashref->{$key}).'&';
                   4479:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4480:        $result.='&';
1.800     albertel 4481:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4482:     } else {
1.800     albertel 4483:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4484:     }
                   4485:   }
1.168     albertel 4486:   $result=~s/\&$//;
1.265     albertel 4487:   $result .= '__END_HASH_REF__';
1.168     albertel 4488:   return $result;
                   4489: }
                   4490: 
                   4491: sub str2hash {
1.265     albertel 4492:     my ($string)=@_;
                   4493:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4494:     return %$hash;
                   4495: }
                   4496: 
                   4497: sub str2hashref {
1.168     albertel 4498:   my ($string) = @_;
1.265     albertel 4499: 
                   4500:   my %hash;
                   4501: 
                   4502:   if($string !~ /^__HASH_REF__/) {
                   4503:       if (! ($string eq '' || !defined($string))) {
                   4504: 	  $hash{'error'}='Not hash reference';
                   4505:       }
                   4506:       return (\%hash, $string);
                   4507:   }
                   4508: 
                   4509:   $string =~ s/^__HASH_REF__//;
                   4510: 
                   4511:   while($string !~ /^__END_HASH_REF__/) {
                   4512:       #key
                   4513:       my $key='';
                   4514:       if($string =~ /^__HASH_REF__/) {
                   4515:           ($key, $string)=&str2hashref($string);
                   4516:           if(defined($key->{'error'})) {
                   4517:               $hash{'error'}='Bad data';
                   4518:               return (\%hash, $string);
                   4519:           }
                   4520:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4521:           ($key, $string)=&str2arrayref($string);
                   4522:           if($key->[0] eq 'Array reference error') {
                   4523:               $hash{'error'}='Bad data';
                   4524:               return (\%hash, $string);
                   4525:           }
                   4526:       } else {
                   4527:           $string =~ s/^(.*?)=//;
1.267     albertel 4528: 	  $key=&unescape($1);
1.265     albertel 4529:       }
                   4530:       $string =~ s/^=//;
                   4531: 
                   4532:       #value
                   4533:       my $value='';
                   4534:       if($string =~ /^__HASH_REF__/) {
                   4535:           ($value, $string)=&str2hashref($string);
                   4536:           if(defined($value->{'error'})) {
                   4537:               $hash{'error'}='Bad data';
                   4538:               return (\%hash, $string);
                   4539:           }
                   4540:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4541:           ($value, $string)=&str2arrayref($string);
                   4542:           if($value->[0] eq 'Array reference error') {
                   4543:               $hash{'error'}='Bad data';
                   4544:               return (\%hash, $string);
                   4545:           }
                   4546:       } else {
                   4547: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4548:       }
                   4549:       $string =~ s/^&//;
                   4550: 
                   4551:       $hash{$key}=$value;
1.204     albertel 4552:   }
1.265     albertel 4553: 
                   4554:   $string =~ s/^__END_HASH_REF__//;
                   4555: 
                   4556:   return (\%hash, $string);
1.204     albertel 4557: }
                   4558: 
                   4559: sub str2array {
1.265     albertel 4560:     my ($string)=@_;
                   4561:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4562:     return @$array;
                   4563: }
                   4564: 
                   4565: sub str2arrayref {
1.204     albertel 4566:   my ($string) = @_;
1.265     albertel 4567:   my @array;
                   4568: 
                   4569:   if($string !~ /^__ARRAY_REF__/) {
                   4570:       if (! ($string eq '' || !defined($string))) {
                   4571: 	  $array[0]='Array reference error';
                   4572:       }
                   4573:       return (\@array, $string);
                   4574:   }
                   4575: 
                   4576:   $string =~ s/^__ARRAY_REF__//;
                   4577: 
                   4578:   while($string !~ /^__END_ARRAY_REF__/) {
                   4579:       my $value='';
                   4580:       if($string =~ /^__HASH_REF__/) {
                   4581:           ($value, $string)=&str2hashref($string);
                   4582:           if(defined($value->{'error'})) {
                   4583:               $array[0] ='Array reference error';
                   4584:               return (\@array, $string);
                   4585:           }
                   4586:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4587:           ($value, $string)=&str2arrayref($string);
                   4588:           if($value->[0] eq 'Array reference error') {
                   4589:               $array[0] ='Array reference error';
                   4590:               return (\@array, $string);
                   4591:           }
                   4592:       } else {
                   4593: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4594:       }
                   4595:       $string =~ s/^&//;
                   4596: 
                   4597:       push(@array, $value);
1.191     harris41 4598:   }
1.265     albertel 4599: 
                   4600:   $string =~ s/^__END_ARRAY_REF__//;
                   4601: 
                   4602:   return (\@array, $string);
1.168     albertel 4603: }
                   4604: 
1.167     albertel 4605: # -------------------------------------------------------------------Temp Store
                   4606: 
1.168     albertel 4607: sub tmpreset {
                   4608:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4609:   if (!$symb) {
                   4610:     $symb=&symbread();
1.620     albertel 4611:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4612:   }
                   4613:   $symb=escape($symb);
                   4614: 
1.620     albertel 4615:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4616:   $namespace=~s/\//\_/g;
                   4617:   $namespace=~s/\W//g;
                   4618: 
1.620     albertel 4619:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4620:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4621:   if ($domain eq 'public' && $stuname eq 'public') {
                   4622:       $stuname=$ENV{'REMOTE_ADDR'};
                   4623:   }
1.1117    foxr     4624:   my $path=LONCAPA::tempdir();
1.168     albertel 4625:   my %hash;
                   4626:   if (tie(%hash,'GDBM_File',
                   4627: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4628: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4629:     foreach my $key (keys(%hash)) {
1.180     albertel 4630:       if ($key=~ /:$symb/) {
1.168     albertel 4631: 	delete($hash{$key});
                   4632:       }
                   4633:     }
                   4634:   }
                   4635: }
                   4636: 
1.167     albertel 4637: sub tmpstore {
1.168     albertel 4638:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4639: 
                   4640:   if (!$symb) {
                   4641:     $symb=&symbread();
1.620     albertel 4642:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4643:   }
                   4644:   $symb=escape($symb);
                   4645: 
                   4646:   if (!$namespace) {
                   4647:     # I don't think we would ever want to store this for a course.
                   4648:     # it seems this will only be used if we don't have a course.
1.620     albertel 4649:     #$namespace=$env{'request.course.id'};
1.168     albertel 4650:     #if (!$namespace) {
1.620     albertel 4651:       $namespace=$env{'request.state'};
1.168     albertel 4652:     #}
                   4653:   }
                   4654:   $namespace=~s/\//\_/g;
                   4655:   $namespace=~s/\W//g;
1.620     albertel 4656:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4657:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4658:   if ($domain eq 'public' && $stuname eq 'public') {
                   4659:       $stuname=$ENV{'REMOTE_ADDR'};
                   4660:   }
1.168     albertel 4661:   my $now=time;
                   4662:   my %hash;
1.1117    foxr     4663:   my $path=LONCAPA::tempdir();
1.168     albertel 4664:   if (tie(%hash,'GDBM_File',
                   4665: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4666: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4667:     $hash{"version:$symb"}++;
                   4668:     my $version=$hash{"version:$symb"};
                   4669:     my $allkeys=''; 
                   4670:     foreach my $key (keys(%$storehash)) {
                   4671:       $allkeys.=$key.':';
1.591     albertel 4672:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4673:     }
                   4674:     $hash{"$version:$symb:timestamp"}=$now;
                   4675:     $allkeys.='timestamp';
                   4676:     $hash{"$version:keys:$symb"}=$allkeys;
                   4677:     if (untie(%hash)) {
                   4678:       return 'ok';
                   4679:     } else {
                   4680:       return "error:$!";
                   4681:     }
                   4682:   } else {
                   4683:     return "error:$!";
                   4684:   }
                   4685: }
1.167     albertel 4686: 
1.168     albertel 4687: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4688: 
1.168     albertel 4689: sub tmprestore {
                   4690:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4691: 
1.168     albertel 4692:   if (!$symb) {
                   4693:     $symb=&symbread();
1.620     albertel 4694:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4695:   }
                   4696:   $symb=escape($symb);
                   4697: 
1.620     albertel 4698:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4699: 
1.620     albertel 4700:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4701:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4702:   if ($domain eq 'public' && $stuname eq 'public') {
                   4703:       $stuname=$ENV{'REMOTE_ADDR'};
                   4704:   }
1.168     albertel 4705:   my %returnhash;
                   4706:   $namespace=~s/\//\_/g;
                   4707:   $namespace=~s/\W//g;
                   4708:   my %hash;
1.1117    foxr     4709:   my $path=LONCAPA::tempdir();
1.168     albertel 4710:   if (tie(%hash,'GDBM_File',
                   4711: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4712: 	  &GDBM_READER(),0640)) {
1.168     albertel 4713:     my $version=$hash{"version:$symb"};
                   4714:     $returnhash{'version'}=$version;
                   4715:     my $scope;
                   4716:     for ($scope=1;$scope<=$version;$scope++) {
                   4717:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4718:       my @keys=split(/:/,$vkeys);
                   4719:       my $key;
                   4720:       $returnhash{"$scope:keys"}=$vkeys;
                   4721:       foreach $key (@keys) {
1.591     albertel 4722: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4723: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4724:       }
                   4725:     }
1.168     albertel 4726:     if (!(untie(%hash))) {
                   4727:       return "error:$!";
                   4728:     }
                   4729:   } else {
                   4730:     return "error:$!";
                   4731:   }
                   4732:   return %returnhash;
1.167     albertel 4733: }
                   4734: 
1.9       www      4735: # ----------------------------------------------------------------------- Store
                   4736: 
                   4737: sub store {
1.124     www      4738:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4739:     my $home='';
                   4740: 
1.168     albertel 4741:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4742: 
1.213     www      4743:     $symb=&symbclean($symb);
1.122     albertel 4744:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4745: 
1.620     albertel 4746:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4747:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4748: 
                   4749:     &devalidate($symb,$stuname,$domain);
1.109     www      4750: 
                   4751:     $symb=escape($symb);
1.187     www      4752:     if (!$namespace) { 
1.620     albertel 4753:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4754:           return ''; 
                   4755:        } 
                   4756:     }
1.620     albertel 4757:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4758: 
                   4759:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4760:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4761: 
1.12      www      4762:     my $namevalue='';
1.800     albertel 4763:     foreach my $key (keys(%$storehash)) {
                   4764:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4765:     }
1.12      www      4766:     $namevalue=~s/\&$//;
1.187     www      4767:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4768:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4769: }
                   4770: 
1.47      www      4771: # -------------------------------------------------------------- Critical Store
                   4772: 
                   4773: sub cstore {
1.124     www      4774:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4775:     my $home='';
                   4776: 
1.168     albertel 4777:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4778: 
1.213     www      4779:     $symb=&symbclean($symb);
1.122     albertel 4780:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4781: 
1.620     albertel 4782:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4783:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4784: 
                   4785:     &devalidate($symb,$stuname,$domain);
1.109     www      4786: 
                   4787:     $symb=escape($symb);
1.187     www      4788:     if (!$namespace) { 
1.620     albertel 4789:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4790:           return ''; 
                   4791:        } 
                   4792:     }
1.620     albertel 4793:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4794: 
                   4795:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4796:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4797: 
1.47      www      4798:     my $namevalue='';
1.800     albertel 4799:     foreach my $key (keys(%$storehash)) {
                   4800:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4801:     }
1.47      www      4802:     $namevalue=~s/\&$//;
1.187     www      4803:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4804:     return critical
                   4805:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4806: }
                   4807: 
1.9       www      4808: # --------------------------------------------------------------------- Restore
                   4809: 
                   4810: sub restore {
1.124     www      4811:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4812:     my $home='';
                   4813: 
1.168     albertel 4814:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4815: 
1.122     albertel 4816:     if (!$symb) {
                   4817:       unless ($symb=escape(&symbread())) { return ''; }
                   4818:     } else {
1.213     www      4819:       $symb=&escape(&symbclean($symb));
1.122     albertel 4820:     }
1.188     www      4821:     if (!$namespace) { 
1.620     albertel 4822:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4823:           return ''; 
                   4824:        } 
                   4825:     }
1.620     albertel 4826:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4827:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4828:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4829:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4830: 
1.12      www      4831:     my %returnhash=();
1.800     albertel 4832:     foreach my $line (split(/\&/,$answer)) {
                   4833: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4834:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4835:     }
1.75      www      4836:     my $version;
                   4837:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4838:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4839:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4840:        }
1.75      www      4841:     }
1.13      www      4842:     return %returnhash;
1.34      www      4843: }
                   4844: 
                   4845: # ---------------------------------------------------------- Course Description
1.1118    foxr     4846: #
                   4847: #  
1.34      www      4848: 
                   4849: sub coursedescription {
1.731     albertel 4850:     my ($courseid,$args)=@_;
1.34      www      4851:     $courseid=~s/^\///;
1.49      www      4852:     $courseid=~s/\_/\//g;
1.34      www      4853:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4854:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4855:     my $normalid=$cdomain.'_'.$cnum;
                   4856:     # need to always cache even if we get errors otherwise we keep 
                   4857:     # trying and trying and trying to get the course description.
                   4858:     my %envhash=();
                   4859:     my %returnhash=();
1.731     albertel 4860:     
                   4861:     my $expiretime=600;
                   4862:     if ($env{'request.course.id'} eq $normalid) {
                   4863: 	$expiretime=120;
                   4864:     }
                   4865: 
                   4866:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4867:     if (!$args->{'freshen_cache'}
                   4868: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4869: 	foreach my $key (keys(%env)) {
                   4870: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4871: 	    my ($setting) = $1;
                   4872: 	    $returnhash{$setting} = $env{$key};
                   4873: 	}
                   4874: 	return %returnhash;
                   4875:     }
                   4876: 
1.1118    foxr     4877:     # get the data again
                   4878: 
1.731     albertel 4879:     if (!$args->{'one_time'}) {
                   4880: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4881:     }
1.811     albertel 4882: 
1.34      www      4883:     if ($chome ne 'no_host') {
1.302     albertel 4884:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4885:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4886: 	   my $username = $env{'user.name'}; # Defult username
                   4887: 	   if(defined $args->{'user'}) {
                   4888: 	       $username = $args->{'user'};
                   4889: 	   }
1.129     albertel 4890:            $returnhash{'home'}= $chome;
                   4891: 	   $returnhash{'domain'} = $cdomain;
                   4892: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4893:            if (!defined($returnhash{'type'})) {
                   4894:                $returnhash{'type'} = 'Course';
                   4895:            }
1.130     albertel 4896:            while (my ($name,$value) = each %returnhash) {
1.53      www      4897:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4898:            }
1.270     www      4899:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4900:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4901: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4902:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4903:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4904:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4905:        }
                   4906:     }
1.731     albertel 4907:     if (!$args->{'one_time'}) {
1.949     raeburn  4908: 	&appenv(\%envhash);
1.731     albertel 4909:     }
1.302     albertel 4910:     return %returnhash;
1.461     www      4911: }
                   4912: 
1.1080    raeburn  4913: sub update_released_required {
                   4914:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4915:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4916:         $cid = $env{'request.course.id'};
                   4917:         $cdom = $env{'course.'.$cid.'.domain'};
                   4918:         $cnum = $env{'course.'.$cid.'.num'};
                   4919:         $chome = $env{'course.'.$cid.'.home'};
                   4920:     }
                   4921:     if ($needsrelease) {
                   4922:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4923:         my $needsupdate;
                   4924:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4925:             $needsupdate = 1;
                   4926:         } else {
                   4927:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4928:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4929:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4930:                 $needsupdate = 1;
                   4931:             }
                   4932:         }
                   4933:         if ($needsupdate) {
                   4934:             my %needshash = (
                   4935:                              'internal.releaserequired' => $needsrelease,
                   4936:                             );
                   4937:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4938:             if ($putresult eq 'ok') {
                   4939:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4940:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4941:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4942:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4943:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4944:                 }
                   4945:             }
                   4946:         }
                   4947:     }
                   4948:     return;
                   4949: }
                   4950: 
1.461     www      4951: # -------------------------------------------------See if a user is privileged
                   4952: 
                   4953: sub privileged {
                   4954:     my ($username,$domain)=@_;
1.1170    droeschl 4955: 
                   4956:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4957:     my $now = time;
                   4958: 
                   4959:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4960:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4961:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4962:                 return 1 unless ($tend && $tend < $now) 
                   4963:                     or ($tstart && $tstart > $now);
                   4964:             }
1.461     www      4965: 	}
1.1170    droeschl 4966: 
1.461     www      4967:     return 0;
1.9       www      4968: }
1.1       albertel 4969: 
1.103     harris41 4970: # -------------------------------------------------------- Get user privileges
1.11      www      4971: 
                   4972: sub rolesinit {
1.1169    droeschl 4973:     my ($domain, $username) = @_;
                   4974:     my %userroles = ('user.login.time' => time);
                   4975:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4976: 
                   4977:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4978:     # also, blocking can be triggered by an activating timer
                   4979:     # it's saved in the user's %env.
                   4980:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4981:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4982:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4983:         %timerintchk, %timerintenv);
                   4984: 
1.1162    raeburn  4985:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4986:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4987:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4988:     }
1.1169    droeschl 4989: 
1.1162    raeburn  4990:     foreach my $key (keys(%timerinterval)) {
                   4991:         my ($cid,$rest) = split(/\0/,$key);
                   4992:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4993:     }
1.1169    droeschl 4994: 
1.11      www      4995:     my %allroles=();
1.1162    raeburn  4996:     my %allgroups=();
1.11      www      4997: 
1.1169    droeschl 4998:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4999:         my $role = $rolesdump{$area};
                   5000:         $area =~ s/\_\w\w$//;
                   5001: 
                   5002:         my ($trole, $tend, $tstart, $group_privs);
                   5003: 
                   5004:         if ($role =~ /^cr/) {
                   5005:         # Custom role, defined by a user 
                   5006:         # e.g., user.role.cr/msu/smith/mynewrole
                   5007:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5008:                 $trole = $1;
                   5009:                 ($tend, $tstart) = split('_', $2);
                   5010:             } else {
                   5011:                 $trole = $role;
                   5012:             }
                   5013:         } elsif ($role =~ m|^gr/|) {
                   5014:         # Role of member in a group, defined within a course/community
                   5015:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5016:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5017:             next if $tstart eq '-1';
                   5018:             ($trole, $group_privs) = split(/\//, $trole);
                   5019:             $group_privs = &unescape($group_privs);
                   5020:         } else {
                   5021:         # Just a normal role, defined in roles.tab
                   5022:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5023:         }
                   5024: 
                   5025:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5026:                  $username);
                   5027:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5028: 
                   5029:         # role expired or not available yet?
                   5030:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5031:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5032: 
                   5033:         next if $area eq '' or $trole eq '';
                   5034: 
                   5035:         my $spec = "$trole.$area";
                   5036:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5037: 
                   5038:         if ($trole =~ /^cr\//) {
                   5039:         # Custom role, defined by a user
                   5040:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5041:         } elsif ($trole eq 'gr') {
                   5042:         # Role of a member in a group, defined within a course/community
                   5043:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5044:             next;
                   5045:         } else {
                   5046:         # Normal role, defined in roles.tab
                   5047:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5048:         }
                   5049: 
                   5050:         my $cid = $tdomain.'_'.$trest;
                   5051:         unless ($firstaccchk{$cid}) {
                   5052:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5053:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5054:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5055:                         $coursetimerstarts{$cid}{$item}; 
                   5056:                 }
                   5057:             }
                   5058:             $firstaccchk{$cid} = 1;
                   5059:         }
                   5060:         unless ($timerintchk{$cid}) {
                   5061:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5062:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5063:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5064:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5065:                 }
1.12      www      5066:             }
1.1169    droeschl 5067:             $timerintchk{$cid} = 1;
1.191     harris41 5068:         }
1.11      www      5069:     }
1.1169    droeschl 5070: 
                   5071:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5072:         \%allroles, \%allgroups);
                   5073:     $env{'user.adv'} = $userroles{'user.adv'};
                   5074: 
1.1162    raeburn  5075:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5076: }
                   5077: 
1.567     raeburn  5078: sub set_arearole {
1.1215    raeburn  5079:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5080:     unless ($nolog) {
1.567     raeburn  5081: # log the associated role with the area
1.1215    raeburn  5082:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5083:     }
1.743     albertel 5084:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5085: }
                   5086: 
                   5087: sub custom_roleprivs {
                   5088:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5089:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5090:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5091:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5092:         my ($rdummy,$roledef)=
                   5093:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5094:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5095:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5096:             if (defined($syspriv)) {
1.1043    raeburn  5097:                 if ($trest =~ /^$match_community$/) {
                   5098:                     $syspriv =~ s/bre\&S//; 
                   5099:                 }
1.567     raeburn  5100:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5101:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5102:             }
                   5103:             if ($tdomain ne '') {
                   5104:                 if (defined($dompriv)) {
                   5105:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5106:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5107:                 }
                   5108:                 if (($trest ne '') && (defined($coursepriv))) {
                   5109:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5110:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5111:                 }
                   5112:             }
                   5113:         }
                   5114:     }
                   5115: }
                   5116: 
1.678     raeburn  5117: sub group_roleprivs {
                   5118:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5119:     my $access = 1;
                   5120:     my $now = time;
                   5121:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5122:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5123:     if ($access) {
1.811     albertel 5124:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5125:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5126:     }
                   5127: }
1.567     raeburn  5128: 
                   5129: sub standard_roleprivs {
                   5130:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5131:     if (defined($pr{$trole.':s'})) {
                   5132:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5133:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5134:     }
                   5135:     if ($tdomain ne '') {
                   5136:         if (defined($pr{$trole.':d'})) {
                   5137:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5138:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5139:         }
                   5140:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5141:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5142:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5143:         }
                   5144:     }
                   5145: }
                   5146: 
                   5147: sub set_userprivs {
1.1064    raeburn  5148:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5149:     my $author=0;
                   5150:     my $adv=0;
1.678     raeburn  5151:     my %grouproles = ();
                   5152:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5153:         my @groupkeys; 
1.1000    raeburn  5154:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5155:             push(@groupkeys,$role);
                   5156:         }
                   5157:         if (ref($groups_roles) eq 'HASH') {
                   5158:             foreach my $key (keys(%{$groups_roles})) {
                   5159:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5160:                     push(@groupkeys,$key);
                   5161:                 }
                   5162:             }
                   5163:         }
                   5164:         if (@groupkeys > 0) {
                   5165:             foreach my $role (@groupkeys) {
                   5166:                 my ($trole,$area,$sec,$extendedarea);
                   5167:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5168:                     $trole = $1;
                   5169:                     $area = $2;
                   5170:                     $sec = $3;
                   5171:                     $extendedarea = $area.$sec;
                   5172:                     if (exists($$allgroups{$area})) {
                   5173:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5174:                             my $spec = $trole.'.'.$extendedarea;
                   5175:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5176:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5177:                         }
1.678     raeburn  5178:                     }
                   5179:                 }
                   5180:             }
                   5181:         }
                   5182:     }
1.800     albertel 5183:     foreach my $group (keys(%grouproles)) {
                   5184:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5185:     }
1.800     albertel 5186:     foreach my $role (keys(%{$allroles})) {
                   5187:         my %thesepriv;
1.941     raeburn  5188:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5189:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5190:             if ($item ne '') {
                   5191:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5192:                 if ($restrictions eq '') {
                   5193:                     $thesepriv{$privilege}='F';
                   5194:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5195:                     $thesepriv{$privilege}.=$restrictions;
                   5196:                 }
                   5197:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5198:             }
                   5199:         }
                   5200:         my $thesestr='';
1.1104    raeburn  5201:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5202: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5203: 	}
                   5204:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5205:     }
                   5206:     return ($author,$adv);
                   5207: }
                   5208: 
1.994     raeburn  5209: sub role_status {
1.1104    raeburn  5210:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5211:     my @pwhere = ();
                   5212:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5213:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5214:         unless (!defined($$role) || $$role eq '') {
                   5215:             $$where=join('.',@pwhere);
                   5216:             $$trolecode=$$role.'.'.$$where;
                   5217:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5218:             $$tstatus='is';
1.1104    raeburn  5219:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5220:                 $$tstatus='future';
1.1034    raeburn  5221:                 if ($$tstart<$now) {
                   5222:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5223:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5224:                             my (%allroles,%allgroups,$group_privs,
                   5225:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5226:                             my %userroles = (
                   5227:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5228:                             );
1.1064    raeburn  5229:                             @rolecodes = ('cm'); 
1.1002    raeburn  5230:                             my $spec=$$role.'.'.$$where;
                   5231:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5232:                             if ($$role =~ /^cr\//) {
                   5233:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5234:                                 push(@rolecodes,'cr');
1.1002    raeburn  5235:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5236:                                 push(@rolecodes,$$role);
1.1002    raeburn  5237:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5238:                                                     $env{'user.name'});
1.1064    raeburn  5239:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5240:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5241:                                 $group_privs = &unescape($group_privs);
                   5242:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5243:                                 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  5244:                                 &get_groups_roles($tdomain,$trest,
                   5245:                                                   \%course_roles,\@rolecodes,
                   5246:                                                   \%groups_roles);
1.1002    raeburn  5247:                             } else {
1.1064    raeburn  5248:                                 push(@rolecodes,$$role);
1.1002    raeburn  5249:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5250:                             }
1.1064    raeburn  5251:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5252:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5253:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5254:                         }
                   5255:                     }
1.1034    raeburn  5256:                     $$tstatus = 'is';
1.1002    raeburn  5257:                 }
1.994     raeburn  5258:             }
                   5259:             if ($$tend) {
1.1104    raeburn  5260:                 if ($$tend<$update) {
1.994     raeburn  5261:                     $$tstatus='expired';
                   5262:                 } elsif ($$tend<$now) {
                   5263:                     $$tstatus='will_not';
                   5264:                 }
                   5265:             }
                   5266:         }
                   5267:     }
                   5268: }
                   5269: 
1.1104    raeburn  5270: sub get_groups_roles {
                   5271:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5272:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5273:                   (ref($rolecodes) eq 'ARRAY') && 
                   5274:                   (ref($groups_roles) eq 'HASH')); 
                   5275:     if (keys(%{$cdom_courseroles}) > 0) {
                   5276:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5277:         if ($cdom ne '' && $cnum ne '') {
                   5278:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5279:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5280:                     my $crsrole = $1;
                   5281:                     my $crssec = $2;
                   5282:                     if ($crsrole =~ /^cr/) {
                   5283:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5284:                             push(@{$rolecodes},'cr');
                   5285:                         }
                   5286:                     } else {
                   5287:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5288:                             push(@{$rolecodes},$crsrole);
                   5289:                         }
                   5290:                     }
                   5291:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5292:                     if ($crssec ne '') {
                   5293:                         $rolekey .= "/$crssec";
                   5294:                     }
                   5295:                     $rolekey .= './';
                   5296:                     $groups_roles->{$rolekey} = $rolecodes;
                   5297:                 }
                   5298:             }
                   5299:         }
                   5300:     }
                   5301:     return;
                   5302: }
                   5303: 
                   5304: sub delete_env_groupprivs {
                   5305:     my ($where,$courseroles,$possroles) = @_;
                   5306:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5307:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5308:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5309:         %{$courseroles->{$udom}} =
                   5310:             &get_my_roles('','','userroles',['active'],
                   5311:                           $possroles,[$udom],1);
                   5312:     }
                   5313:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5314:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5315:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5316:             my $area = '/'.$cdom.'/'.$cnum;
                   5317:             my $privkey = "user.priv.$crsrole.$area";
                   5318:             if ($crssec ne '') {
                   5319:                 $privkey .= '/'.$crssec;
                   5320:             }
                   5321:             $privkey .= ".$area/$group";
                   5322:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5323:         }
                   5324:     }
                   5325:     return;
                   5326: }
                   5327: 
1.994     raeburn  5328: sub check_adhoc_privs {
1.1104    raeburn  5329:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5330:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5331:     my $setprivs;
1.994     raeburn  5332:     if ($env{$cckey}) {
                   5333:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5334:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5335:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5336:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5337:             $setprivs = 1;
1.994     raeburn  5338:         }
                   5339:     } else {
1.1088    raeburn  5340:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5341:         $setprivs = 1;
1.994     raeburn  5342:     }
1.1185    raeburn  5343:     return $setprivs;
1.994     raeburn  5344: }
                   5345: 
                   5346: sub set_adhoc_privileges {
                   5347: # role can be cc or ca
1.1088    raeburn  5348:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5349:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5350:     my $spec = $role.'.'.$area;
                   5351:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5352:                                   $env{'user.name'},1);
1.994     raeburn  5353:     my %ccrole = ();
                   5354:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5355:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5356:     &appenv(\%userroles,[$role,'cm']);
                   5357:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5358:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5359:         &appenv( {'request.role'        => $spec,
                   5360:                   'request.role.domain' => $dcdom,
                   5361:                   'request.course.sec'  => ''
                   5362:                  }
                   5363:                );
                   5364:         my $tadv=0;
                   5365:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5366:         &appenv({'request.role.adv'    => $tadv});
                   5367:     }
1.994     raeburn  5368: }
                   5369: 
1.12      www      5370: # --------------------------------------------------------------- get interface
                   5371: 
                   5372: sub get {
1.131     albertel 5373:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5374:    my $items='';
1.800     albertel 5375:    foreach my $item (@$storearr) {
                   5376:        $items.=&escape($item).'&';
1.191     harris41 5377:    }
1.12      www      5378:    $items=~s/\&$//;
1.620     albertel 5379:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5380:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5381:    my $uhome=&homeserver($uname,$udomain);
                   5382: 
1.133     albertel 5383:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5384:    my @pairs=split(/\&/,$rep);
1.273     albertel 5385:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5386:      return @pairs;
                   5387:    }
1.15      www      5388:    my %returnhash=();
1.42      www      5389:    my $i=0;
1.800     albertel 5390:    foreach my $item (@$storearr) {
                   5391:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5392:       $i++;
1.191     harris41 5393:    }
1.15      www      5394:    return %returnhash;
1.27      www      5395: }
                   5396: 
                   5397: # --------------------------------------------------------------- del interface
                   5398: 
                   5399: sub del {
1.133     albertel 5400:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5401:    my $items='';
1.800     albertel 5402:    foreach my $item (@$storearr) {
                   5403:        $items.=&escape($item).'&';
1.191     harris41 5404:    }
1.984     neumanie 5405: 
1.27      www      5406:    $items=~s/\&$//;
1.620     albertel 5407:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5408:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5409:    my $uhome=&homeserver($uname,$udomain);
                   5410:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5411: }
                   5412: 
                   5413: # -------------------------------------------------------------- dump interface
                   5414: 
1.1180    droeschl 5415: sub unserialize {
                   5416:     my ($rep, $escapedkeys) = @_;
                   5417: 
                   5418:     return {} if $rep =~ /^error/;
                   5419: 
                   5420:     my %returnhash=();
                   5421: 	foreach my $item (split /\&/, $rep) {
                   5422: 	    my ($key, $value) = split(/=/, $item, 2);
                   5423: 	    $key = unescape($key) unless $escapedkeys;
                   5424: 	    next if $key =~ /^error: 2 /;
                   5425: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5426: 	}
                   5427:     #return %returnhash;
                   5428:     return \%returnhash;
                   5429: }        
                   5430: 
                   5431: # see Lond::dump_with_regexp
                   5432: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5433: sub dump {
1.1180    droeschl 5434:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5435:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5436:     if (!$uname) { $uname=$env{'user.name'}; }
                   5437:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5438: 
1.1180    droeschl 5439:     my $reply;
                   5440:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5441:         # user is hosted on this machine
                   5442:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
                   5443:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5444:         return %{unserialize($reply, $escapedkeys)};
                   5445:     }
1.755     albertel 5446:     if ($regexp) {
                   5447: 	$regexp=&escape($regexp);
                   5448:     } else {
                   5449: 	$regexp='.';
                   5450:     }
1.1166    raeburn  5451:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5452:     my @pairs=split(/\&/,$rep);
                   5453:     my %returnhash=();
1.1098    foxr     5454:     if (!($rep =~ /^error/ )) {
                   5455: 	foreach my $item (@pairs) {
                   5456: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5457:         $key = unescape($key) unless $escapedkeys;
                   5458:         #$key = &unescape($key);
1.1098    foxr     5459: 	    next if ($key =~ /^error: 2 /);
                   5460: 	    $returnhash{$key}=&thaw_unescape($value);
                   5461: 	}
1.755     albertel 5462:     }
                   5463:     return %returnhash;
1.407     www      5464: }
                   5465: 
1.1098    foxr     5466: 
1.717     albertel 5467: # --------------------------------------------------------- dumpstore interface
                   5468: 
                   5469: sub dumpstore {
                   5470:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5471:    # same as dump but keys must be escaped. They may contain colon separated
                   5472:    # lists of values that may themself contain colons (e.g. symbs).
                   5473:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5474: }
                   5475: 
1.407     www      5476: # -------------------------------------------------------------- keys interface
                   5477: 
                   5478: sub getkeys {
                   5479:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5480:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5481:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5482:    my $uhome=&homeserver($uname,$udomain);
                   5483:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5484:    my @keyarray=();
1.800     albertel 5485:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5486:       next if ($key =~ /^error: 2 /);
1.800     albertel 5487:       push(@keyarray,&unescape($key));
1.407     www      5488:    }
                   5489:    return @keyarray;
1.318     matthew  5490: }
                   5491: 
1.319     matthew  5492: # --------------------------------------------------------------- currentdump
                   5493: sub currentdump {
1.328     matthew  5494:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5495:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5496:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5497:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5498:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5499:    my $rep;
                   5500: 
                   5501:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5502:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5503:                    $courseid)));
                   5504:    } else {
                   5505:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5506:    }
                   5507: 
1.318     matthew  5508:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5509:    #
1.318     matthew  5510:    my %returnhash=();
1.319     matthew  5511:    #
                   5512:    if ($rep eq "unknown_cmd") { 
                   5513:        # an old lond will not know currentdump
                   5514:        # Do a dump and make it look like a currentdump
1.822     albertel 5515:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5516:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5517:        my %hash = @tmp;
                   5518:        @tmp=();
1.424     matthew  5519:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5520:    } else {
                   5521:        my @pairs=split(/\&/,$rep);
1.800     albertel 5522:        foreach my $pair (@pairs) {
                   5523:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5524:            my ($symb,$param) = split(/:/,$key);
                   5525:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5526:                                                         &thaw_unescape($value);
1.319     matthew  5527:        }
1.191     harris41 5528:    }
1.12      www      5529:    return %returnhash;
1.424     matthew  5530: }
                   5531: 
                   5532: sub convert_dump_to_currentdump{
                   5533:     my %hash = %{shift()};
                   5534:     my %returnhash;
                   5535:     # Code ripped from lond, essentially.  The only difference
                   5536:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5537:     # we might run in to problems with parameter names =~ /^v\./
                   5538:     while (my ($key,$value) = each(%hash)) {
                   5539:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5540: 	$symb  = &unescape($symb);
                   5541: 	$param = &unescape($param);
1.424     matthew  5542:         next if ($v eq 'version' || $symb eq 'keys');
                   5543:         next if (exists($returnhash{$symb}) &&
                   5544:                  exists($returnhash{$symb}->{$param}) &&
                   5545:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5546:         $returnhash{$symb}->{$param}=$value;
                   5547:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5548:     }
                   5549:     #
                   5550:     # Remove all of the keys in the hashes which keep track of
                   5551:     # the version of the parameter.
                   5552:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5553:         # use a foreach because we are going to delete from the hash.
                   5554:         foreach my $key (keys(%$param_hash)) {
                   5555:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5556:         }
                   5557:     }
                   5558:     return \%returnhash;
1.12      www      5559: }
                   5560: 
1.627     albertel 5561: # ------------------------------------------------------ critical inc interface
                   5562: 
                   5563: sub cinc {
                   5564:     return &inc(@_,'critical');
                   5565: }
                   5566: 
1.449     matthew  5567: # --------------------------------------------------------------- inc interface
                   5568: 
                   5569: sub inc {
1.627     albertel 5570:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5571:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5572:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5573:     my $uhome=&homeserver($uname,$udomain);
                   5574:     my $items='';
                   5575:     if (! ref($store)) {
                   5576:         # got a single value, so use that instead
                   5577:         $items = &escape($store).'=&';
                   5578:     } elsif (ref($store) eq 'SCALAR') {
                   5579:         $items = &escape($$store).'=&';        
                   5580:     } elsif (ref($store) eq 'ARRAY') {
                   5581:         $items = join('=&',map {&escape($_);} @{$store});
                   5582:     } elsif (ref($store) eq 'HASH') {
                   5583:         while (my($key,$value) = each(%{$store})) {
                   5584:             $items.= &escape($key).'='.&escape($value).'&';
                   5585:         }
                   5586:     }
                   5587:     $items=~s/\&$//;
1.627     albertel 5588:     if ($critical) {
                   5589: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5590:     } else {
                   5591: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5592:     }
1.449     matthew  5593: }
                   5594: 
1.12      www      5595: # --------------------------------------------------------------- put interface
                   5596: 
                   5597: sub put {
1.134     albertel 5598:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5599:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5600:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5601:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5602:    my $items='';
1.800     albertel 5603:    foreach my $item (keys(%$storehash)) {
                   5604:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5605:    }
1.12      www      5606:    $items=~s/\&$//;
1.134     albertel 5607:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5608: }
                   5609: 
1.631     albertel 5610: # ------------------------------------------------------------ newput interface
                   5611: 
                   5612: sub newput {
                   5613:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5614:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5615:    if (!$uname) { $uname=$env{'user.name'}; }
                   5616:    my $uhome=&homeserver($uname,$udomain);
                   5617:    my $items='';
                   5618:    foreach my $key (keys(%$storehash)) {
                   5619:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5620:    }
                   5621:    $items=~s/\&$//;
                   5622:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5623: }
                   5624: 
                   5625: # ---------------------------------------------------------  putstore interface
                   5626: 
1.524     raeburn  5627: sub putstore {
1.715     albertel 5628:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5629:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5630:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5631:    my $uhome=&homeserver($uname,$udomain);
                   5632:    my $items='';
1.715     albertel 5633:    foreach my $key (keys(%$storehash)) {
                   5634:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5635:    }
1.715     albertel 5636:    $items=~s/\&$//;
1.716     albertel 5637:    my $esc_symb=&escape($symb);
                   5638:    my $esc_v=&escape($version);
1.715     albertel 5639:    my $reply =
1.716     albertel 5640:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5641: 	      $uhome);
                   5642:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5643:        # gfall back to way things use to be done
1.715     albertel 5644:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5645: 			    $uname);
1.524     raeburn  5646:    }
1.715     albertel 5647:    return $reply;
                   5648: }
                   5649: 
                   5650: sub old_putstore {
1.716     albertel 5651:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5652:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5653:     if (!$uname) { $uname=$env{'user.name'}; }
                   5654:     my $uhome=&homeserver($uname,$udomain);
                   5655:     my %newstorehash;
1.800     albertel 5656:     foreach my $item (keys(%$storehash)) {
                   5657: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5658: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5659:     }
                   5660:     my $items='';
                   5661:     my %allitems = ();
1.800     albertel 5662:     foreach my $item (keys(%newstorehash)) {
                   5663: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5664: 	    my $key = $1.':keys:'.$2;
                   5665: 	    $allitems{$key} .= $3.':';
                   5666: 	}
1.800     albertel 5667: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5668:     }
1.800     albertel 5669:     foreach my $item (keys(%allitems)) {
                   5670: 	$allitems{$item} =~ s/\:$//;
                   5671: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5672:     }
                   5673:     $items=~s/\&$//;
                   5674:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5675: }
                   5676: 
1.47      www      5677: # ------------------------------------------------------ critical put interface
                   5678: 
                   5679: sub cput {
1.134     albertel 5680:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5681:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5682:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5683:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5684:    my $items='';
1.800     albertel 5685:    foreach my $item (keys(%$storehash)) {
                   5686:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5687:    }
1.47      www      5688:    $items=~s/\&$//;
1.134     albertel 5689:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5690: }
                   5691: 
                   5692: # -------------------------------------------------------------- eget interface
                   5693: 
                   5694: sub eget {
1.133     albertel 5695:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5696:    my $items='';
1.800     albertel 5697:    foreach my $item (@$storearr) {
                   5698:        $items.=&escape($item).'&';
1.191     harris41 5699:    }
1.12      www      5700:    $items=~s/\&$//;
1.620     albertel 5701:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5702:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5703:    my $uhome=&homeserver($uname,$udomain);
                   5704:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5705:    my @pairs=split(/\&/,$rep);
                   5706:    my %returnhash=();
1.42      www      5707:    my $i=0;
1.800     albertel 5708:    foreach my $item (@$storearr) {
                   5709:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5710:       $i++;
1.191     harris41 5711:    }
1.12      www      5712:    return %returnhash;
                   5713: }
                   5714: 
1.667     albertel 5715: # ------------------------------------------------------------ tmpput interface
                   5716: sub tmpput {
1.802     raeburn  5717:     my ($storehash,$server,$context)=@_;
1.667     albertel 5718:     my $items='';
1.800     albertel 5719:     foreach my $item (keys(%$storehash)) {
                   5720: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5721:     }
                   5722:     $items=~s/\&$//;
1.802     raeburn  5723:     if (defined($context)) {
                   5724:         $items .= ':'.&escape($context);
                   5725:     }
1.667     albertel 5726:     return &reply("tmpput:$items",$server);
                   5727: }
                   5728: 
                   5729: # ------------------------------------------------------------ tmpget interface
                   5730: sub tmpget {
1.688     albertel 5731:     my ($token,$server)=@_;
                   5732:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5733:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5734:     my %returnhash;
                   5735:     foreach my $item (split(/\&/,$rep)) {
                   5736: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5737:         next if ($key =~ /^error: 2 /);
1.667     albertel 5738: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5739:     }
                   5740:     return %returnhash;
                   5741: }
                   5742: 
1.1113    raeburn  5743: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5744: sub tmpdel {
                   5745:     my ($token,$server)=@_;
                   5746:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5747:     return &reply("tmpdel:$token",$server);
                   5748: }
                   5749: 
1.1198    raeburn  5750: # ------------------------------------------------------------ get_timebased_id 
                   5751: 
                   5752: sub get_timebased_id {
                   5753:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5754:         $maxtries) = @_;
                   5755:     my ($newid,$error,$dellock);
                   5756:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5757:         return ('','ok','invalid call to get suffix');
                   5758:     }
                   5759: 
                   5760: # set defaults for any optional args for which values were not supplied
                   5761:     if ($who eq '') {
                   5762:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5763:     }
                   5764:     if (!$locktries) {
                   5765:         $locktries = 3;
                   5766:     }
                   5767:     if (!$maxtries) {
                   5768:         $maxtries = 10;
                   5769:     }
                   5770:     
                   5771:     if (($cdom eq '') || ($cnum eq '')) {
                   5772:         if ($env{'request.course.id'}) {
                   5773:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5774:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5775:         }
                   5776:         if (($cdom eq '') || ($cnum eq '')) {
                   5777:             return ('','ok','call to get suffix not in course context');
                   5778:         }
                   5779:     }
                   5780: 
                   5781: # construct locking item
                   5782:     my $lockhash = {
                   5783:                       $prefix."\0".'locked_'.$keyid => $who,
                   5784:                    };
                   5785:     my $tries = 0;
                   5786: 
                   5787: # attempt to get lock on nohist_$namespace file
                   5788:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5789:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5790:         $tries ++;
                   5791:         sleep 1;
                   5792:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5793:     }
                   5794: 
                   5795: # attempt to get unique identifier, based on current timestamp
                   5796:     if ($gotlock eq 'ok') {
                   5797:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5798:         my $id = time;
                   5799:         $newid = $id;
                   5800:         my $idtries = 0;
                   5801:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5802:             if ($idtype eq 'concat') {
                   5803:                 $newid = $id.$idtries;
                   5804:             } else {
                   5805:                 $newid ++;
                   5806:             }
                   5807:             $idtries ++;
                   5808:         }
                   5809:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5810:             my %new_item =  (
                   5811:                               $prefix."\0".$newid => $who,
                   5812:                             );
                   5813:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5814:                                                  $cdom,$cnum);
                   5815:             if ($putresult ne 'ok') {
                   5816:                 undef($newid);
                   5817:                 $error = 'error saving new item: '.$putresult;
                   5818:             }
                   5819:         } else {
                   5820:              $error = ('error: no unique suffix available for the new item ');
                   5821:         }
                   5822: #  remove lock
                   5823:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5824:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5825:     } else {
                   5826:         $error = "error: could not obtain lockfile\n";
                   5827:         $dellock = 'ok';
                   5828:     }
                   5829:     return ($newid,$dellock,$error);
                   5830: }
                   5831: 
1.765     albertel 5832: # -------------------------------------------------- portfolio access checking
                   5833: 
                   5834: sub portfolio_access {
1.766     albertel 5835:     my ($requrl) = @_;
1.765     albertel 5836:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5837:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5838:     if ($result) {
                   5839:         my %setters;
                   5840:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5841:             my ($startblock,$endblock) =
                   5842:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5843:             if ($startblock && $endblock) {
                   5844:                 return 'B';
                   5845:             }
                   5846:         } else {
                   5847:             my ($startblock,$endblock) =
                   5848:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5849:             if ($startblock && $endblock) {
                   5850:                 return 'B';
                   5851:             }
                   5852:         }
                   5853:     }
1.765     albertel 5854:     if ($result eq 'ok') {
1.766     albertel 5855:        return 'F';
1.765     albertel 5856:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5857:        return 'A';
1.765     albertel 5858:     }
1.766     albertel 5859:     return '';
1.765     albertel 5860: }
                   5861: 
                   5862: sub get_portfolio_access {
1.767     albertel 5863:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5864: 
                   5865:     if (!ref($access_hash)) {
                   5866: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5867: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5868: 						   $file_name);
                   5869: 	$access_hash = $access_controls{$file_name};
                   5870:     }
                   5871: 
1.765     albertel 5872:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5873:     my $now = time;
                   5874:     if (ref($access_hash) eq 'HASH') {
                   5875:         foreach my $key (keys(%{$access_hash})) {
                   5876:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5877:             if ($start > $now) {
                   5878:                 next;
                   5879:             }
                   5880:             if ($end && $end<$now) {
                   5881:                 next;
                   5882:             }
                   5883:             if ($scope eq 'public') {
                   5884:                 $public = $key;
                   5885:                 last;
                   5886:             } elsif ($scope eq 'guest') {
                   5887:                 $guest = $key;
                   5888:             } elsif ($scope eq 'domains') {
                   5889:                 push(@domains,$key);
                   5890:             } elsif ($scope eq 'users') {
                   5891:                 push(@users,$key);
                   5892:             } elsif ($scope eq 'course') {
                   5893:                 push(@courses,$key);
                   5894:             } elsif ($scope eq 'group') {
                   5895:                 push(@groups,$key);
                   5896:             }
                   5897:         }
                   5898:         if ($public) {
                   5899:             return 'ok';
                   5900:         }
                   5901:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5902:             if ($guest) {
                   5903:                 return $guest;
                   5904:             }
                   5905:         } else {
                   5906:             if (@domains > 0) {
                   5907:                 foreach my $domkey (@domains) {
                   5908:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5909:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5910:                             return 'ok';
                   5911:                         }
                   5912:                     }
                   5913:                 }
                   5914:             }
                   5915:             if (@users > 0) {
                   5916:                 foreach my $userkey (@users) {
1.865     raeburn  5917:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5918:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5919:                             if (ref($item) eq 'HASH') {
                   5920:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5921:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5922:                                     return 'ok';
                   5923:                                 }
                   5924:                             }
                   5925:                         }
                   5926:                     } 
1.765     albertel 5927:                 }
                   5928:             }
                   5929:             my %roleshash;
                   5930:             my @courses_and_groups = @courses;
                   5931:             push(@courses_and_groups,@groups); 
                   5932:             if (@courses_and_groups > 0) {
                   5933:                 my (%allgroups,%allroles); 
                   5934:                 my ($start,$end,$role,$sec,$group);
                   5935:                 foreach my $envkey (%env) {
1.1060    raeburn  5936:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5937:                         my $cid = $2.'_'.$3; 
                   5938:                         if ($1 eq 'gr') {
                   5939:                             $group = $4;
                   5940:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5941:                         } else {
                   5942:                             if ($4 eq '') {
                   5943:                                 $sec = 'none';
                   5944:                             } else {
                   5945:                                 $sec = $4;
                   5946:                             }
                   5947:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5948:                         }
1.811     albertel 5949:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5950:                         my $cid = $2.'_'.$3;
                   5951:                         if ($4 eq '') {
                   5952:                             $sec = 'none';
                   5953:                         } else {
                   5954:                             $sec = $4;
                   5955:                         }
                   5956:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5957:                     }
                   5958:                 }
                   5959:                 if (keys(%allroles) == 0) {
                   5960:                     return;
                   5961:                 }
                   5962:                 foreach my $key (@courses_and_groups) {
                   5963:                     my %content = %{$$access_hash{$key}};
                   5964:                     my $cnum = $content{'number'};
                   5965:                     my $cdom = $content{'domain'};
                   5966:                     my $cid = $cdom.'_'.$cnum;
                   5967:                     if (!exists($allroles{$cid})) {
                   5968:                         next;
                   5969:                     }    
                   5970:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5971:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5972:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5973:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5974:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5975:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5976:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5977:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5978:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5979:                                         if (grep/^all$/,@sections) {
                   5980:                                             return 'ok';
                   5981:                                         } else {
                   5982:                                             if (grep/^$sec$/,@sections) {
                   5983:                                                 return 'ok';
                   5984:                                             }
                   5985:                                         }
                   5986:                                     }
                   5987:                                 }
                   5988:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5989:                                     if (grep/^none$/,@groups) {
                   5990:                                         return 'ok';
                   5991:                                     }
                   5992:                                 } else {
                   5993:                                     if (grep/^all$/,@groups) {
                   5994:                                         return 'ok';
                   5995:                                     } 
                   5996:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5997:                                         if (grep/^$group$/,@groups) {
                   5998:                                             return 'ok';
                   5999:                                         }
                   6000:                                     }
                   6001:                                 } 
                   6002:                             }
                   6003:                         }
                   6004:                     }
                   6005:                 }
                   6006:             }
                   6007:             if ($guest) {
                   6008:                 return $guest;
                   6009:             }
                   6010:         }
                   6011:     }
                   6012:     return;
                   6013: }
                   6014: 
                   6015: sub course_group_datechecker {
                   6016:     my ($dates,$now,$status) = @_;
                   6017:     my ($start,$end) = split(/\./,$dates);
                   6018:     if (!$start && !$end) {
                   6019:         return 'ok';
                   6020:     }
                   6021:     if (grep/^active$/,@{$status}) {
                   6022:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6023:             return 'ok';
                   6024:         }
                   6025:     }
                   6026:     if (grep/^previous$/,@{$status}) {
                   6027:         if ($end > $now ) {
                   6028:             return 'ok';
                   6029:         }
                   6030:     }
                   6031:     if (grep/^future$/,@{$status}) {
                   6032:         if ($start > $now) {
                   6033:             return 'ok';
                   6034:         }
                   6035:     }
                   6036:     return; 
                   6037: }
                   6038: 
                   6039: sub parse_portfolio_url {
                   6040:     my ($url) = @_;
                   6041: 
                   6042:     my ($type,$udom,$unum,$group,$file_name);
                   6043:     
1.823     albertel 6044:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6045: 	$type = 1;
                   6046:         $udom = $1;
                   6047:         $unum = $2;
                   6048:         $file_name = $3;
1.823     albertel 6049:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6050: 	$type = 2;
                   6051:         $udom = $1;
                   6052:         $unum = $2;
                   6053:         $group = $3;
                   6054:         $file_name = $3.'/'.$4;
                   6055:     }
                   6056:     if (wantarray) {
                   6057: 	return ($type,$udom,$unum,$file_name,$group);
                   6058:     }
                   6059:     return $type;
                   6060: }
                   6061: 
                   6062: sub is_portfolio_url {
                   6063:     my ($url) = @_;
                   6064:     return scalar(&parse_portfolio_url($url));
                   6065: }
                   6066: 
1.798     raeburn  6067: sub is_portfolio_file {
                   6068:     my ($file) = @_;
1.820     raeburn  6069:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6070:         return 1;
                   6071:     }
                   6072:     return;
                   6073: }
                   6074: 
1.976     raeburn  6075: sub usertools_access {
1.1084    raeburn  6076:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6077:     my ($access,%tools);
                   6078:     if ($context eq '') {
                   6079:         $context = 'tools';
                   6080:     }
                   6081:     if ($context eq 'requestcourses') {
                   6082:         %tools = (
                   6083:                       official   => 1,
                   6084:                       unofficial => 1,
1.1006    raeburn  6085:                       community  => 1,
1.985     raeburn  6086:                  );
1.1183    raeburn  6087:     } elsif ($context eq 'requestauthor') {
                   6088:         %tools = (
                   6089:                       requestauthor => 1,
                   6090:                  );
1.985     raeburn  6091:     } else {
                   6092:         %tools = (
                   6093:                       aboutme   => 1,
                   6094:                       blog      => 1,
1.1177    raeburn  6095:                       webdav    => 1,
1.985     raeburn  6096:                       portfolio => 1,
                   6097:                  );
                   6098:     }
1.976     raeburn  6099:     return if (!defined($tools{$tool}));
                   6100: 
                   6101:     if ((!defined($udom)) || (!defined($uname))) {
                   6102:         $udom = $env{'user.domain'};
                   6103:         $uname = $env{'user.name'};
                   6104:     }
                   6105: 
1.978     raeburn  6106:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6107:         if ($action ne 'reload') {
1.985     raeburn  6108:             if ($context eq 'requestcourses') {
                   6109:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6110:             } elsif ($context eq 'requestauthor') {
                   6111:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6112:             } else {
                   6113:                 return $env{'environment.availabletools.'.$tool};
                   6114:             }
                   6115:         }
1.976     raeburn  6116:     }
                   6117: 
1.1183    raeburn  6118:     my ($toolstatus,$inststatus,$envkey);
                   6119:     if ($context eq 'requestauthor') {
                   6120:         $envkey = $context; 
                   6121:     } else {
                   6122:         $envkey = $context.'.'.$tool;
                   6123:     }
1.976     raeburn  6124: 
1.985     raeburn  6125:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6126:          ($action ne 'reload')) {
1.1183    raeburn  6127:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6128:         $inststatus = $env{'environment.inststatus'};
                   6129:     } else {
1.1084    raeburn  6130:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6131:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6132:             $inststatus = $userenvref->{'inststatus'};
                   6133:         } else {
1.1183    raeburn  6134:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6135:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6136:             $inststatus = $userenv{'inststatus'};
                   6137:         }
1.976     raeburn  6138:     }
                   6139: 
                   6140:     if ($toolstatus ne '') {
                   6141:         if ($toolstatus) {
                   6142:             $access = 1;
                   6143:         } else {
                   6144:             $access = 0;
                   6145:         }
                   6146:         return $access;
                   6147:     }
                   6148: 
1.1084    raeburn  6149:     my ($is_adv,%domdef);
                   6150:     if (ref($is_advref) eq 'HASH') {
                   6151:         $is_adv = $is_advref->{'is_adv'};
                   6152:     } else {
                   6153:         $is_adv = &is_advanced_user($udom,$uname);
                   6154:     }
                   6155:     if (ref($domdefref) eq 'HASH') {
                   6156:         %domdef = %{$domdefref};
                   6157:     } else {
                   6158:         %domdef = &get_domain_defaults($udom);
                   6159:     }
1.976     raeburn  6160:     if (ref($domdef{$tool}) eq 'HASH') {
                   6161:         if ($is_adv) {
                   6162:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6163:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6164:                     $access = 1;
                   6165:                 } else {
                   6166:                     $access = 0;
                   6167:                 }
                   6168:                 return $access;
                   6169:             }
                   6170:         }
                   6171:         if ($inststatus ne '') {
                   6172:             my ($hasaccess,$hasnoaccess);
                   6173:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6174:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6175:                     if ($domdef{$tool}{$affiliation}) {
                   6176:                         $hasaccess = 1;
                   6177:                     } else {
                   6178:                         $hasnoaccess = 1;
                   6179:                     }
                   6180:                 }
                   6181:             }
                   6182:             if ($hasaccess || $hasnoaccess) {
                   6183:                 if ($hasaccess) {
                   6184:                     $access = 1;
                   6185:                 } elsif ($hasnoaccess) {
                   6186:                     $access = 0; 
                   6187:                 }
                   6188:                 return $access;
                   6189:             }
                   6190:         } else {
                   6191:             if ($domdef{$tool}{'default'} ne '') {
                   6192:                 if ($domdef{$tool}{'default'}) {
                   6193:                     $access = 1;
                   6194:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6195:                     $access = 0;
                   6196:                 }
                   6197:                 return $access;
                   6198:             }
                   6199:         }
                   6200:     } else {
1.1177    raeburn  6201:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6202:             $access = 1;
                   6203:         } else {
                   6204:             $access = 0;
                   6205:         }
1.976     raeburn  6206:         return $access;
                   6207:     }
                   6208: }
                   6209: 
1.1050    raeburn  6210: sub is_course_owner {
                   6211:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6212:     if (($udom eq '') || ($uname eq '')) {
                   6213:         $udom = $env{'user.domain'};
                   6214:         $uname = $env{'user.name'};
                   6215:     }
                   6216:     unless (($udom eq '') || ($uname eq '')) {
                   6217:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6218:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6219:                 return 1;
                   6220:             } else {
                   6221:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6222:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6223:                     return 1;
                   6224:                 }
                   6225:             }
                   6226:         }
                   6227:     }
                   6228:     return;
                   6229: }
                   6230: 
1.976     raeburn  6231: sub is_advanced_user {
                   6232:     my ($udom,$uname) = @_;
1.1085    raeburn  6233:     if ($udom ne '' && $uname ne '') {
                   6234:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6235:             if (wantarray) {
                   6236:                 return ($env{'user.adv'},$env{'user.author'});
                   6237:             } else {
                   6238:                 return $env{'user.adv'};
                   6239:             }
1.1085    raeburn  6240:         }
                   6241:     }
1.976     raeburn  6242:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6243:     my %allroles;
1.1128    raeburn  6244:     my ($is_adv,$is_author);
1.976     raeburn  6245:     foreach my $role (keys(%roleshash)) {
                   6246:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6247:         my $area = '/'.$tdomain.'/'.$trest;
                   6248:         if ($sec ne '') {
                   6249:             $area .= '/'.$sec;
                   6250:         }
                   6251:         if (($area ne '') && ($trole ne '')) {
                   6252:             my $spec=$trole.'.'.$area;
                   6253:             if ($trole =~ /^cr\//) {
                   6254:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6255:             } elsif ($trole ne 'gr') {
                   6256:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6257:             }
1.1128    raeburn  6258:             if ($trole eq 'au') {
                   6259:                 $is_author = 1;
                   6260:             }
1.976     raeburn  6261:         }
                   6262:     }
                   6263:     foreach my $role (keys(%allroles)) {
                   6264:         last if ($is_adv);
                   6265:         foreach my $item (split(/:/,$allroles{$role})) {
                   6266:             if ($item ne '') {
                   6267:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6268:                 if ($privilege eq 'adv') {
                   6269:                     $is_adv = 1;
                   6270:                     last;
                   6271:                 }
                   6272:             }
                   6273:         }
                   6274:     }
1.1128    raeburn  6275:     if (wantarray) {
                   6276:         return ($is_adv,$is_author);
                   6277:     }
1.976     raeburn  6278:     return $is_adv;
                   6279: }
1.798     raeburn  6280: 
1.1035    raeburn  6281: sub check_can_request {
1.1036    raeburn  6282:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6283:     my $canreq = 0;
                   6284:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6285:     my @options = ('approval','validate','autolimit');
                   6286:     my $optregex = join('|',@options);
                   6287:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6288:         foreach my $type (@{$types}) {
                   6289:             if (&usertools_access($env{'user.name'},
                   6290:                                   $env{'user.domain'},
                   6291:                                   $type,undef,'requestcourses')) {
                   6292:                 $canreq ++;
1.1036    raeburn  6293:                 if (ref($request_domains) eq 'HASH') {
                   6294:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6295:                 }
1.1035    raeburn  6296:                 if ($dom eq $env{'user.domain'}) {
                   6297:                     $can_request->{$type} = 1;
                   6298:                 }
                   6299:             }
                   6300:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6301:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6302:                 if (@curr > 0) {
1.1036    raeburn  6303:                     foreach my $item (@curr) {
                   6304:                         if (ref($request_domains) eq 'HASH') {
                   6305:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6306:                             if ($otherdom ne '') {
                   6307:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6308:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6309:                                         push(@{$request_domains->{$type}},$otherdom);
                   6310:                                     }
                   6311:                                 } else {
                   6312:                                     push(@{$request_domains->{$type}},$otherdom);
                   6313:                                 }
                   6314:                             }
                   6315:                         }
                   6316:                     }
                   6317:                     unless($dom eq $env{'user.domain'}) {
                   6318:                         $canreq ++;
1.1035    raeburn  6319:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6320:                             $can_request->{$type} = 1;
                   6321:                         }
                   6322:                     }
                   6323:                 }
                   6324:             }
                   6325:         }
                   6326:     }
                   6327:     return $canreq;
                   6328: }
                   6329: 
1.341     www      6330: # ---------------------------------------------- Custom access rule evaluation
                   6331: 
                   6332: sub customaccess {
                   6333:     my ($priv,$uri)=@_;
1.807     albertel 6334:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6335:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6336:     $udom = &LONCAPA::clean_domain($udom);
                   6337:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6338:     my $access=0;
1.800     albertel 6339:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6340: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6341: 	if ($type eq 'user') {
                   6342: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6343: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6344: 		if ($tdom) {
                   6345: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6346: 		}
1.896     albertel 6347: 		if ($tuname) {
                   6348: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6349: 		}
                   6350: 		$access=($effect eq 'allow');
                   6351: 		last;
                   6352: 	    }
                   6353: 	} else {
                   6354: 	    if ($role) {
                   6355: 		if ($role ne $urole) { next; }
                   6356: 	    }
                   6357: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6358: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6359: 		if ($tdom) {
                   6360: 		    if ($tdom ne $udom) { next; }
                   6361: 		}
                   6362: 		if ($tcrs) {
                   6363: 		    if ($tcrs ne $ucrs) { next; }
                   6364: 		}
                   6365: 		if ($tsec) {
                   6366: 		    if ($tsec ne $usec) { next; }
                   6367: 		}
                   6368: 		$access=($effect eq 'allow');
                   6369: 		last;
                   6370: 	    }
                   6371: 	    if ($realm eq '' && $role eq '') {
                   6372: 		$access=($effect eq 'allow');
                   6373: 	    }
1.402     bowersj2 6374: 	}
1.341     www      6375:     }
                   6376:     return $access;
                   6377: }
                   6378: 
1.103     harris41 6379: # ------------------------------------------------- Check for a user privilege
1.12      www      6380: 
                   6381: sub allowed {
1.810     raeburn  6382:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6383:     my $ver_orguri=$uri;
1.439     www      6384:     $uri=&deversion($uri);
1.152     www      6385:     my $orguri=$uri;
1.52      www      6386:     $uri=&declutter($uri);
1.809     raeburn  6387: 
1.810     raeburn  6388:     if ($priv eq 'evb') {
                   6389: # Evade communication block restrictions for specified role in a course
                   6390:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6391:             return $1;
                   6392:         } else {
                   6393:             return;
                   6394:         }
                   6395:     }
                   6396: 
1.620     albertel 6397:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6398: # Free bre access to adm and meta resources
1.775     albertel 6399:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6400: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6401: 	&& ($priv eq 'bre')) {
1.14      www      6402: 	return 'F';
1.159     www      6403:     }
                   6404: 
1.545     banghart 6405: # Free bre access to user's own portfolio contents
1.714     raeburn  6406:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6407:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6408: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6409:         my %setters;
                   6410:         my ($startblock,$endblock) = 
                   6411:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6412:         if ($startblock && $endblock) {
                   6413:             return 'B';
                   6414:         } else {
                   6415:             return 'F';
                   6416:         }
1.545     banghart 6417:     }
                   6418: 
1.762     raeburn  6419: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6420:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6421:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6422:         if (exists($env{'request.course.id'})) {
                   6423:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6424:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6425:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6426:                 my $courseprivid=$env{'request.course.id'};
                   6427:                 $courseprivid=~s/\_/\//;
                   6428:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6429:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6430:                     return $1; 
1.762     raeburn  6431:                 } else {
                   6432:                     if ($env{'request.course.sec'}) {
                   6433:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6434:                     }
                   6435:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6436:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6437:                         return $2;
                   6438:                     }
1.714     raeburn  6439:                 }
                   6440:             }
                   6441:         }
                   6442:     }
                   6443: 
1.159     www      6444: # Free bre to public access
                   6445: 
                   6446:     if ($priv eq 'bre') {
1.238     www      6447:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6448: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6449:            return 'F'; 
                   6450:         }
1.238     www      6451:         if ($copyright eq 'priv') {
                   6452:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6453: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6454: 		return '';
                   6455:             }
                   6456:         }
                   6457:         if ($copyright eq 'domain') {
                   6458:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6459: 	    unless (($env{'user.domain'} eq $1) ||
                   6460:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6461: 		return '';
                   6462:             }
1.262     matthew  6463:         }
1.620     albertel 6464:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6465:             # Library role, so allow browsing of resources in this domain.
                   6466:             return 'F';
1.238     www      6467:         }
1.341     www      6468:         if ($copyright eq 'custom') {
                   6469: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6470:         }
1.14      www      6471:     }
1.264     matthew  6472:     # Domain coordinator is trying to create a course
1.620     albertel 6473:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6474:         # uri is the requested domain in this case.
                   6475:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6476:         # a role of dc for the domain in question.
1.620     albertel 6477:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6478:     }
1.29      www      6479: 
1.52      www      6480:     my $thisallowed='';
                   6481:     my $statecond=0;
                   6482:     my $courseprivid='';
                   6483: 
1.1039    raeburn  6484:     my $ownaccess;
1.1043    raeburn  6485:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6486:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6487:         if ($uri eq '') {
                   6488:             $ownaccess = 1;
                   6489:         } else {
                   6490:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6491:                 my $udom = $env{'user.domain'};
                   6492:                 my $uname = $env{'user.name'};
                   6493:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6494:                     $ownaccess = 1;
1.1040    raeburn  6495:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6496:                     unless ($uri =~ m{\.\./}) {
                   6497:                         $ownaccess = 1;
                   6498:                     }
                   6499:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6500:                     my $now = time;
                   6501:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6502:                         my $adom = $1;
                   6503:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6504:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6505:                                 my ($start,$end) = split('.',$env{$key});
                   6506:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6507:                                     $ownaccess = 1;
                   6508:                                     last;
                   6509:                                 }
                   6510:                             }
                   6511:                         }
                   6512:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6513:                         my $adom = $1;
                   6514:                         my $aname = $2;
1.1042    raeburn  6515:                         foreach my $role ('ca','aa') { 
                   6516:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6517:                                 my ($start,$end) =
                   6518:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6519:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6520:                                     $ownaccess = 1;
                   6521:                                     last;
                   6522:                                 }
1.1039    raeburn  6523:                             }
                   6524:                         }
                   6525:                     }
                   6526:                 }
                   6527:             }
                   6528:         }
                   6529:     }
                   6530: 
1.52      www      6531: # Course
                   6532: 
1.620     albertel 6533:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6534:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6535:             $thisallowed.=$1;
                   6536:         }
1.52      www      6537:     }
1.29      www      6538: 
1.52      www      6539: # Domain
                   6540: 
1.620     albertel 6541:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6542:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6543:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6544:             $thisallowed.=$1;
                   6545:         }
1.12      www      6546:     }
1.52      www      6547: 
1.1141    raeburn  6548: # User who is not author or co-author might still be able to edit
                   6549: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6550:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6551:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6552:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6553:             $thisallowed.=$1;
                   6554:         }
                   6555:     }
                   6556: 
1.52      www      6557: # Course: uri itself is a course
1.66      www      6558:     my $courseuri=$uri;
                   6559:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6560:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6561: 
1.620     albertel 6562:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6563:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6564:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6565:             $thisallowed.=$1;
                   6566:         }
1.12      www      6567:     }
1.29      www      6568: 
1.665     albertel 6569: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6570: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6571:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6572: 	$thisallowed='';
1.671     raeburn  6573:         my ($match)=&is_on_map($uri);
                   6574:         if ($match) {
                   6575:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6576:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6577:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6578:                 if (@blockers > 0) {
                   6579:                     $thisallowed = 'B';
                   6580:                 } else {
                   6581:                     $thisallowed.=$1;
                   6582:                 }
1.671     raeburn  6583:             }
                   6584:         } else {
1.705     albertel 6585:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6586:             if ($refuri) {
                   6587:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6588:                     $thisallowed='F';
1.671     raeburn  6589:                 } else {
                   6590:                     $refuri=&declutter($refuri);
                   6591:                     my ($match) = &is_on_map($refuri);
                   6592:                     if ($match) {
1.1162    raeburn  6593:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6594:                         if (@blockers > 0) {
                   6595:                             $thisallowed = 'B';
                   6596:                         } else {
                   6597:                             $thisallowed='F';
                   6598:                         }
1.671     raeburn  6599:                     }
1.669     raeburn  6600:                 }
1.671     raeburn  6601:             }
                   6602:         }
1.314     www      6603:     }
1.492     albertel 6604: 
1.766     albertel 6605:     if ($priv eq 'bre'
                   6606: 	&& $thisallowed ne 'F' 
                   6607: 	&& $thisallowed ne '2'
                   6608: 	&& &is_portfolio_url($uri)) {
                   6609: 	$thisallowed = &portfolio_access($uri);
                   6610:     }
                   6611:     
1.52      www      6612: # Full access at system, domain or course-wide level? Exit.
1.29      www      6613:     if ($thisallowed=~/F/) {
                   6614: 	return 'F';
                   6615:     }
                   6616: 
1.52      www      6617: # If this is generating or modifying users, exit with special codes
1.29      www      6618: 
1.643     www      6619:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6620: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6621: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6622: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6623: 	    unless ($auname) { return $thisallowed; }
                   6624: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6625: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6626: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6627: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6628: 	}
1.52      www      6629: 	return $thisallowed;
                   6630:     }
                   6631: #
1.103     harris41 6632: # Gathered so far: system, domain and course wide privileges
1.52      www      6633: #
                   6634: # Course: See if uri or referer is an individual resource that is part of 
                   6635: # the course
                   6636: 
1.620     albertel 6637:     if ($env{'request.course.id'}) {
1.232     www      6638: 
1.620     albertel 6639:        $courseprivid=$env{'request.course.id'};
                   6640:        if ($env{'request.course.sec'}) {
                   6641:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6642:        }
                   6643:        $courseprivid=~s/\_/\//;
                   6644:        my $checkreferer=1;
1.232     www      6645:        my ($match,$cond)=&is_on_map($uri);
                   6646:        if ($match) {
                   6647:            $statecond=$cond;
1.620     albertel 6648:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6649:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6650:                my $value = $1;
                   6651:                if ($priv eq 'bre') {
                   6652:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6653:                    if (@blockers > 0) {
                   6654:                        $thisallowed = 'B';
                   6655:                    } else {
                   6656:                        $thisallowed.=$value;
                   6657:                    }
                   6658:                } else {
                   6659:                    $thisallowed.=$value;
                   6660:                }
1.52      www      6661:                $checkreferer=0;
                   6662:            }
1.29      www      6663:        }
1.83      www      6664:        
1.148     www      6665:        if ($checkreferer) {
1.620     albertel 6666: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6667:             unless ($refuri) {
1.800     albertel 6668:                 foreach my $key (keys(%env)) {
                   6669: 		    if ($key=~/^httpref\..*\*/) {
                   6670: 			my $pattern=$key;
1.156     www      6671:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6672:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6673:                         $pattern=~s/\//\\\//g;
1.152     www      6674:                         if ($orguri=~/$pattern/) {
1.800     albertel 6675: 			    $refuri=$env{$key};
1.148     www      6676:                         }
                   6677:                     }
1.191     harris41 6678:                 }
1.148     www      6679:             }
1.232     www      6680: 
1.148     www      6681:          if ($refuri) { 
1.152     www      6682: 	  $refuri=&declutter($refuri);
1.232     www      6683:           my ($match,$cond)=&is_on_map($refuri);
                   6684:             if ($match) {
                   6685:               my $refstatecond=$cond;
1.620     albertel 6686:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6687:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6688:                   my $value = $1;
                   6689:                   if ($priv eq 'bre') {
                   6690:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6691:                       if (@blockers > 0) {
                   6692:                           $thisallowed = 'B';
                   6693:                       } else {
                   6694:                           $thisallowed.=$value;
                   6695:                       }
                   6696:                   } else {
                   6697:                       $thisallowed.=$value;
                   6698:                   }
1.53      www      6699:                   $uri=$refuri;
                   6700:                   $statecond=$refstatecond;
1.52      www      6701:               }
                   6702:           }
1.148     www      6703:         }
1.29      www      6704:        }
1.52      www      6705:    }
1.29      www      6706: 
1.52      www      6707: #
1.103     harris41 6708: # Gathered now: all privileges that could apply, and condition number
1.52      www      6709: # 
                   6710: #
                   6711: # Full or no access?
                   6712: #
1.29      www      6713: 
1.52      www      6714:     if ($thisallowed=~/F/) {
                   6715: 	return 'F';
                   6716:     }
1.29      www      6717: 
1.52      www      6718:     unless ($thisallowed) {
                   6719:         return '';
                   6720:     }
1.29      www      6721: 
1.52      www      6722: # Restrictions exist, deal with them
                   6723: #
                   6724: #   C:according to course preferences
                   6725: #   R:according to resource settings
                   6726: #   L:unless locked
                   6727: #   X:according to user session state
                   6728: #
                   6729: 
                   6730: # Possibly locked functionality, check all courses
1.54      www      6731: # Locks might take effect only after 10 minutes cache expiration for other
                   6732: # courses, and 2 minutes for current course
1.52      www      6733: 
                   6734:     my $envkey;
                   6735:     if ($thisallowed=~/L/) {
1.1000    raeburn  6736:         foreach $envkey (keys(%env)) {
1.54      www      6737:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6738:                my $courseid=$2;
                   6739:                my $roleid=$1.'.'.$2;
1.92      www      6740:                $courseid=~s/^\///;
1.54      www      6741:                my $expiretime=600;
1.620     albertel 6742:                if ($env{'request.role'} eq $roleid) {
1.54      www      6743: 		  $expiretime=120;
                   6744:                }
                   6745: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6746:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6747:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6748: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6749:                }
1.620     albertel 6750:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6751:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6752: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6753:                        &log($env{'user.domain'},$env{'user.name'},
                   6754:                             $env{'user.home'},
1.57      www      6755:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6756:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6757:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6758: 		       return '';
                   6759:                    }
                   6760:                }
1.620     albertel 6761:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6762:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6763: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6764:                        &log($env{'user.domain'},$env{'user.name'},
                   6765:                             $env{'user.home'},
1.57      www      6766:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6767:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6768:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6769: 		       return '';
                   6770:                    }
                   6771:                }
                   6772: 	   }
1.29      www      6773:        }
1.52      www      6774:     }
                   6775:    
                   6776: #
                   6777: # Rest of the restrictions depend on selected course
                   6778: #
                   6779: 
1.620     albertel 6780:     unless ($env{'request.course.id'}) {
1.766     albertel 6781: 	if ($thisallowed eq 'A') {
                   6782: 	    return 'A';
1.814     raeburn  6783:         } elsif ($thisallowed eq 'B') {
                   6784:             return 'B';
1.766     albertel 6785: 	} else {
                   6786: 	    return '1';
                   6787: 	}
1.52      www      6788:     }
1.29      www      6789: 
1.52      www      6790: #
                   6791: # Now user is definitely in a course
                   6792: #
1.53      www      6793: 
                   6794: 
                   6795: # Course preferences
                   6796: 
                   6797:    if ($thisallowed=~/C/) {
1.620     albertel 6798:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6799:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6800:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6801: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6802: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6803: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6804: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6805: 			$env{'request.course.id'});
                   6806: 	   }
1.237     www      6807:            return '';
                   6808:        }
                   6809: 
1.620     albertel 6810:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6811: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6812: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6813: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6814: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6815: 			$env{'request.course.id'});
                   6816: 	   }
1.54      www      6817:            return '';
                   6818:        }
1.53      www      6819:    }
                   6820: 
                   6821: # Resource preferences
                   6822: 
                   6823:    if ($thisallowed=~/R/) {
1.620     albertel 6824:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6825:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6826: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6827: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6828: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6829: 	   }
                   6830: 	   return '';
1.54      www      6831:        }
1.53      www      6832:    }
1.30      www      6833: 
1.246     www      6834: # Restricted by state or randomout?
1.30      www      6835: 
1.52      www      6836:    if ($thisallowed=~/X/) {
1.620     albertel 6837:       if ($env{'acc.randomout'}) {
1.579     albertel 6838: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6839:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6840:             return ''; 
                   6841:          }
1.247     www      6842:       }
                   6843:       if (&condval($statecond)) {
1.52      www      6844: 	 return '2';
                   6845:       } else {
                   6846:          return '';
                   6847:       }
                   6848:    }
1.30      www      6849: 
1.766     albertel 6850:     if ($thisallowed eq 'A') {
                   6851: 	return 'A';
1.814     raeburn  6852:     } elsif ($thisallowed eq 'B') {
                   6853:         return 'B';
1.766     albertel 6854:     }
1.52      www      6855:    return 'F';
1.232     www      6856: }
1.1162    raeburn  6857: 
1.1192    raeburn  6858: # ------------------------------------------- Check construction space access
                   6859: 
                   6860: sub constructaccess {
                   6861:     my ($url,$setpriv)=@_;
                   6862: 
                   6863: # We do not allow editing of previous versions of files
                   6864:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6865: 
                   6866: # Get username and domain from URL
                   6867:     my ($ownername,$ownerdomain,$ownerhome);
                   6868: 
                   6869:     ($ownerdomain,$ownername) =
                   6870:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6871: 
                   6872: # The URL does not really point to any authorspace, forget it
                   6873:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6874: 
                   6875: # Now we need to see if the user has access to the authorspace of
                   6876: # $ownername at $ownerdomain
                   6877: 
                   6878:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6879: # Real author for this?
                   6880:        $ownerhome = $env{'user.home'};
                   6881:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6882:           return ($ownername,$ownerdomain,$ownerhome);
                   6883:        }
                   6884:     } else {
                   6885: # Co-author for this?
                   6886:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6887:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6888:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6889:             return ($ownername,$ownerdomain,$ownerhome);
                   6890:         }
                   6891:     }
                   6892: 
                   6893: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6894: # we might as well leave
                   6895:    unless ($setpriv) { return ''; }
                   6896: 
                   6897: # Backdoor access?
                   6898:     my $allowed=&allowed('eco',$ownerdomain);
                   6899: # Nope
                   6900:     unless ($allowed) { return ''; }
                   6901: # Looks like we may have access, but could be locked by the owner of the construction space
                   6902:     if ($allowed eq 'U') {
                   6903:         my %blocked=&get('environment',['domcoord.author'],
                   6904:                          $ownerdomain,$ownername);
                   6905: # Is blocked by owner
                   6906:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6907:     }
                   6908:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6909: # Grant temporary access
                   6910:         my $then=$env{'user.login.time'};
1.1209    raeburn  6911:         my $update=$env{'user.update.time'};
1.1192    raeburn  6912:         if (!$update) { $update = $then; }
                   6913:         my $refresh=$env{'user.refresh.time'};
                   6914:         if (!$refresh) { $refresh = $update; }
                   6915:         my $now = time;
                   6916:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6917:                            $now,'ca','constructaccess');
                   6918:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6919:         return($ownername,$ownerdomain,$ownerhome);
                   6920:     }
                   6921: # No business here
                   6922:     return '';
                   6923: }
                   6924: 
1.1162    raeburn  6925: sub get_comm_blocks {
                   6926:     my ($cdom,$cnum) = @_;
                   6927:     if ($cdom eq '' || $cnum eq '') {
                   6928:         return unless ($env{'request.course.id'});
                   6929:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6930:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6931:     }
                   6932:     my %commblocks;
                   6933:     my $hashid=$cdom.'_'.$cnum;
                   6934:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6935:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6936:         %commblocks = %{$blocksref};
                   6937:     } else {
                   6938:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6939:         my $cachetime = 600;
                   6940:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6941:     }
                   6942:     return %commblocks;
                   6943: }
                   6944: 
                   6945: sub has_comm_blocking {
                   6946:     my ($priv,$symb,$uri,$blocks) = @_;
                   6947:     return unless ($env{'request.course.id'});
                   6948:     return unless ($priv eq 'bre');
                   6949:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6950:     my %commblocks;
                   6951:     if (ref($blocks) eq 'HASH') {
                   6952:         %commblocks = %{$blocks};
                   6953:     } else {
                   6954:         %commblocks = &get_comm_blocks();
                   6955:     }
                   6956:     return unless (keys(%commblocks) > 0);
                   6957:     if (!$symb) { $symb=&symbread($uri,1); }
                   6958:     my ($map,$resid,undef)=&decode_symb($symb);
                   6959:     my %tocheck = (
                   6960:                     maps      => $map,
                   6961:                     resources => $symb,
                   6962:                   );
                   6963:     my @blockers;
                   6964:     my $now = time;
1.1163    raeburn  6965:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6966:     foreach my $block (keys(%commblocks)) {
                   6967:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6968:             my ($start,$end) = ($1,$2);
                   6969:             if ($start <= $now && $end >= $now) {
                   6970:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6971:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6972:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6973:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6974:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6975:                                     push(@blockers,$block);
                   6976:                                 }
                   6977:                             }
                   6978:                         }
                   6979:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6980:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6981:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6982:                                     push(@blockers,$block);
                   6983:                                 }
                   6984:                             }
                   6985:                         }
                   6986:                     }
                   6987:                 }
                   6988:             }
                   6989:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6990:             my $item = $1;
1.1163    raeburn  6991:             my @to_test;
1.1162    raeburn  6992:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6993:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6994:                     my $check_interval;
                   6995:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6996:                         my @interval;
                   6997:                         my $type = 'map';
                   6998:                         if ($item eq 'course') {
                   6999:                             $type = 'course';
                   7000:                             @interval=&EXT("resource.0.interval");
                   7001:                         } else {
                   7002:                             if ($item =~ /___\d+___/) {
                   7003:                                 $type = 'resource';
                   7004:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7005:                                 if (ref($navmap)) {                        
                   7006:                                     my $res = $navmap->getBySymb($item); 
                   7007:                                     push(@to_test,$res);
                   7008:                                 }
1.1162    raeburn  7009:                             } else {
                   7010:                                 my $mapsymb = &symbread($item,1);
                   7011:                                 if ($mapsymb) {
                   7012:                                     if (ref($navmap)) {
                   7013:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7014:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7015:                                         foreach my $res (@to_test) {
1.1162    raeburn  7016:                                             my $symb = $res->symb();
                   7017:                                             next if ($symb eq $mapsymb);
                   7018:                                             if ($symb ne '') {
                   7019:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7020:                                                 last;
                   7021:                                             }
                   7022:                                         }
                   7023:                                     }
                   7024:                                 }
                   7025:                             }
                   7026:                         }
                   7027:                         if ($interval[0] =~ /\d+/) {
                   7028:                             my $first_access;
                   7029:                             if ($type eq 'resource') {
                   7030:                                 $first_access=&get_first_access($interval[1],$item);
                   7031:                             } elsif ($type eq 'map') {
                   7032:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7033:                             } else {
                   7034:                                 $first_access=&get_first_access($interval[1]);
                   7035:                             }
                   7036:                             if ($first_access) {
                   7037:                                 my $timesup = $first_access+$interval[0];
                   7038:                                 if ($timesup > $now) {
1.1163    raeburn  7039:                                     foreach my $res (@to_test) {
                   7040:                                         if ($res->is_problem()) {
                   7041:                                             if ($res->completable()) {
                   7042:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7043:                                                     push(@blockers,$block);
                   7044:                                                 }
                   7045:                                                 last;
                   7046:                                             }
                   7047:                                         }
1.1162    raeburn  7048:                                     }
                   7049:                                 }
                   7050:                             }
                   7051:                         }
                   7052:                     }
                   7053:                 }
                   7054:             }
                   7055:         }
                   7056:     }
                   7057:     return @blockers;
                   7058: }
                   7059: 
                   7060: sub check_docs_block {
                   7061:     my ($docsblock,$tocheck) =@_;
                   7062:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7063:         return;
                   7064:     }
                   7065:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7066:         if ($tocheck->{'maps'}) {
                   7067:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7068:                 return 1;
                   7069:             }
                   7070:         }
                   7071:     }
                   7072:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7073:         if ($tocheck->{'resources'}) {
                   7074:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7075:                 return 1;
                   7076:             }
                   7077:         }
                   7078:     }
                   7079:     return;
                   7080: }
                   7081: 
1.1133    foxr     7082: #
                   7083: #   Removes the versino from a URI and
                   7084: #   splits it in to its filename and path to the filename.
                   7085: #   Seems like File::Basename could have done this more clearly.
                   7086: #   Parameters:
                   7087: #      $uri   - input URI
                   7088: #   Returns:
                   7089: #     Two element list consisting of 
                   7090: #     $pathname  - the URI up to and excluding the trailing /
                   7091: #     $filename  - The part of the URI following the last /
                   7092: #  NOTE:
                   7093: #    Another realization of this is simply:
                   7094: #    use File::Basename;
                   7095: #    ...
                   7096: #    $uri = shift;
                   7097: #    $filename = basename($uri);
                   7098: #    $path     = dirname($uri);
                   7099: #    return ($filename, $path);
                   7100: #
                   7101: #     The implementation below is probably faster however.
                   7102: #
1.710     albertel 7103: sub split_uri_for_cond {
                   7104:     my $uri=&deversion(&declutter(shift));
                   7105:     my @uriparts=split(/\//,$uri);
                   7106:     my $filename=pop(@uriparts);
                   7107:     my $pathname=join('/',@uriparts);
                   7108:     return ($pathname,$filename);
                   7109: }
1.232     www      7110: # --------------------------------------------------- Is a resource on the map?
                   7111: 
                   7112: sub is_on_map {
1.710     albertel 7113:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7114:     #Trying to find the conditional for the file
1.620     albertel 7115:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7116: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7117:     if ($match) {
1.289     bowersj2 7118: 	return (1,$1);
                   7119:     } else {
1.434     www      7120: 	return (0,0);
1.289     bowersj2 7121:     }
1.12      www      7122: }
                   7123: 
1.427     www      7124: # --------------------------------------------------------- Get symb from alias
                   7125: 
                   7126: sub get_symb_from_alias {
                   7127:     my $symb=shift;
                   7128:     my ($map,$resid,$url)=&decode_symb($symb);
                   7129: # Already is a symb
                   7130:     if ($url) { return $symb; }
                   7131: # Must be an alias
                   7132:     my $aliassymb='';
                   7133:     my %bighash;
1.620     albertel 7134:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7135:                             &GDBM_READER(),0640)) {
                   7136:         my $rid=$bighash{'mapalias_'.$symb};
                   7137: 	if ($rid) {
                   7138: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7139: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7140: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7141: 	}
                   7142:         untie %bighash;
                   7143:     }
                   7144:     return $aliassymb;
                   7145: }
                   7146: 
1.12      www      7147: # ----------------------------------------------------------------- Define Role
                   7148: 
                   7149: sub definerole {
                   7150:   if (allowed('mcr','/')) {
                   7151:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7152:     foreach my $role (split(':',$sysrole)) {
                   7153: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7154:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7155:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7156: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7157:                return "refused:s:$crole&$cqual"; 
                   7158:             }
                   7159:         }
1.191     harris41 7160:     }
1.800     albertel 7161:     foreach my $role (split(':',$domrole)) {
                   7162: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7163:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7164:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7165: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7166:                return "refused:d:$crole&$cqual"; 
                   7167:             }
                   7168:         }
1.191     harris41 7169:     }
1.800     albertel 7170:     foreach my $role (split(':',$courole)) {
                   7171: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7172:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7173:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7174: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7175:                return "refused:c:$crole&$cqual"; 
                   7176:             }
                   7177:         }
1.191     harris41 7178:     }
1.620     albertel 7179:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7180:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7181: 	        "rolesdef_$rolename=".
                   7182:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7183:     return reply($command,$env{'user.home'});
1.12      www      7184:   } else {
                   7185:     return 'refused';
                   7186:   }
1.105     harris41 7187: }
                   7188: 
                   7189: # ---------------- Make a metadata query against the network of library servers
                   7190: 
                   7191: sub metadata_query {
1.244     matthew  7192:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7193:     my %rhash;
1.845     albertel 7194:     my %libserv = &all_library();
1.244     matthew  7195:     my @server_list = (defined($server_array) ? @$server_array
                   7196:                                               : keys(%libserv) );
                   7197:     for my $server (@server_list) {
1.118     harris41 7198: 	unless ($custom or $customshow) {
                   7199: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7200: 	    $rhash{$server}=$reply;
                   7201: 	}
                   7202: 	else {
                   7203: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7204: 			     &escape($custom).':'.&escape($customshow),
                   7205: 			     $server);
                   7206: 	    $rhash{$server}=$reply;
                   7207: 	}
1.112     harris41 7208:     }
1.118     harris41 7209:     return \%rhash;
1.240     www      7210: }
                   7211: 
                   7212: # ----------------------------------------- Send log queries and wait for reply
                   7213: 
                   7214: sub log_query {
                   7215:     my ($uname,$udom,$query,%filters)=@_;
                   7216:     my $uhome=&homeserver($uname,$udom);
                   7217:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7218:     my $uhost=&hostname($uhome);
1.800     albertel 7219:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7220:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7221:                        $uhome);
1.479     albertel 7222:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7223:     return get_query_reply($queryid);
                   7224: }
                   7225: 
1.818     raeburn  7226: # -------------------------- Update MySQL table for portfolio file
                   7227: 
                   7228: sub update_portfolio_table {
1.821     raeburn  7229:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7230:     if ($group ne '') {
                   7231:         $file_name =~s /^\Q$group\E//;
                   7232:     }
1.818     raeburn  7233:     my $homeserver = &homeserver($uname,$udom);
                   7234:     my $queryid=
1.821     raeburn  7235:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7236:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7237:     my $reply = &get_query_reply($queryid);
                   7238:     return $reply;
                   7239: }
                   7240: 
1.899     raeburn  7241: # -------------------------- Update MySQL allusers table
                   7242: 
                   7243: sub update_allusers_table {
                   7244:     my ($uname,$udom,$names) = @_;
                   7245:     my $homeserver = &homeserver($uname,$udom);
                   7246:     my $queryid=
                   7247:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7248:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7249:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7250:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7251:                'generation='.&escape($names->{'generation'}).'%%'.
                   7252:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7253:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7254:     return;
1.899     raeburn  7255: }
                   7256: 
1.508     raeburn  7257: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7258: 
                   7259: sub fetch_enrollment_query {
1.511     raeburn  7260:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7261:     my $homeserver;
1.547     raeburn  7262:     my $maxtries = 1;
1.508     raeburn  7263:     if ($context eq 'automated') {
                   7264:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7265:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7266:     } else {
                   7267:         $homeserver = &homeserver($cnum,$dom);
                   7268:     }
1.838     albertel 7269:     my $host=&hostname($homeserver);
1.506     raeburn  7270:     my $cmd = '';
1.1000    raeburn  7271:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7272:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7273:     }
                   7274:     $cmd =~ s/%%$//;
                   7275:     $cmd = &escape($cmd);
                   7276:     my $query = 'fetchenrollment';
1.620     albertel 7277:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7278:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7279:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7280:         return 'error: '.$queryid;
                   7281:     }
1.506     raeburn  7282:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7283:     my $tries = 1;
                   7284:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7285:         $reply = &get_query_reply($queryid);
                   7286:         $tries ++;
                   7287:     }
1.526     raeburn  7288:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7289:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7290:     } else {
1.901     albertel 7291:         my @responses = split(/:/,$reply);
1.515     raeburn  7292:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7293:             foreach my $line (@responses) {
                   7294:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7295:                 $$replyref{$key} = $value;
                   7296:             }
                   7297:         } else {
1.1117    foxr     7298:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7299:             foreach my $line (@responses) {
                   7300:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7301:                 $$replyref{$key} = $value;
                   7302:                 if ($value > 0) {
1.800     albertel 7303:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7304:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7305:                         my $destname = $pathname.'/'.$filename;
                   7306:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7307:                         if ($xml_classlist =~ /^error/) {
                   7308:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7309:                         } else {
1.506     raeburn  7310:                             if ( open(FILE,">$destname") ) {
                   7311:                                 print FILE &unescape($xml_classlist);
                   7312:                                 close(FILE);
1.526     raeburn  7313:                             } else {
                   7314:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7315:                             }
                   7316:                         }
                   7317:                     }
                   7318:                 }
                   7319:             }
                   7320:         }
                   7321:         return 'ok';
                   7322:     }
                   7323:     return 'error';
                   7324: }
                   7325: 
1.242     www      7326: sub get_query_reply {
                   7327:     my $queryid=shift;
1.1117    foxr     7328:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7329:     my $reply='';
                   7330:     for (1..100) {
                   7331: 	sleep 2;
                   7332:         if (-e $replyfile.'.end') {
1.448     albertel 7333: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7334: 		$reply = join('',<$fh>);
                   7335: 		close($fh);
1.240     www      7336: 	   } else { return 'error: reply_file_error'; }
1.242     www      7337:            return &unescape($reply);
                   7338: 	}
1.240     www      7339:     }
1.242     www      7340:     return 'timeout:'.$queryid;
1.240     www      7341: }
                   7342: 
                   7343: sub courselog_query {
1.241     www      7344: #
                   7345: # possible filters:
                   7346: # url: url or symb
                   7347: # username
                   7348: # domain
                   7349: # action: view, submit, grade
                   7350: # start: timestamp
                   7351: # end: timestamp
                   7352: #
1.240     www      7353:     my (%filters)=@_;
1.620     albertel 7354:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7355:     if ($filters{'url'}) {
                   7356: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7357:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7358:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7359:     }
1.620     albertel 7360:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7361:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7362:     return &log_query($cname,$cdom,'courselog',%filters);
                   7363: }
                   7364: 
                   7365: sub userlog_query {
1.858     raeburn  7366: #
                   7367: # possible filters:
                   7368: # action: log check role
                   7369: # start: timestamp
                   7370: # end: timestamp
                   7371: #
1.240     www      7372:     my ($uname,$udom,%filters)=@_;
                   7373:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7374: }
                   7375: 
1.506     raeburn  7376: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7377: 
                   7378: sub auto_run {
1.508     raeburn  7379:     my ($cnum,$cdom) = @_;
1.876     raeburn  7380:     my $response = 0;
                   7381:     my $settings;
                   7382:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7383:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7384:         $settings = $domconfig{'autoenroll'};
                   7385:         if ($settings->{'run'} eq '1') {
                   7386:             $response = 1;
                   7387:         }
                   7388:     } else {
1.934     raeburn  7389:         my $homeserver;
                   7390:         if (&is_course($cdom,$cnum)) {
                   7391:             $homeserver = &homeserver($cnum,$cdom);
                   7392:         } else {
                   7393:             $homeserver = &domain($cdom,'primary');
                   7394:         }
                   7395:         if ($homeserver ne 'no_host') {
                   7396:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7397:         }
1.876     raeburn  7398:     }
1.506     raeburn  7399:     return $response;
                   7400: }
1.776     albertel 7401: 
1.506     raeburn  7402: sub auto_get_sections {
1.508     raeburn  7403:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7404:     my $homeserver;
                   7405:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7406:         $homeserver = &homeserver($cnum,$cdom);
                   7407:     }
                   7408:     if (!defined($homeserver)) { 
                   7409:         if ($cdom =~ /^$match_domain$/) {
                   7410:             $homeserver = &domain($cdom,'primary');
                   7411:         }
                   7412:     }
                   7413:     my @secs;
                   7414:     if (defined($homeserver)) {
                   7415:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7416:         unless ($response eq 'refused') {
                   7417:             @secs = split(/:/,$response);
                   7418:         }
1.506     raeburn  7419:     }
                   7420:     return @secs;
                   7421: }
1.776     albertel 7422: 
1.506     raeburn  7423: sub auto_new_course {
1.1099    raeburn  7424:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7425:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7426:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7427:     return $response;
                   7428: }
1.776     albertel 7429: 
1.506     raeburn  7430: sub auto_validate_courseID {
1.508     raeburn  7431:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7432:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7433:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7434:     return $response;
                   7435: }
1.776     albertel 7436: 
1.1007    raeburn  7437: sub auto_validate_instcode {
1.1020    raeburn  7438:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7439:     my ($homeserver,$response);
                   7440:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7441:         $homeserver = &homeserver($cnum,$cdom);
                   7442:     }
                   7443:     if (!defined($homeserver)) {
                   7444:         if ($cdom =~ /^$match_domain$/) {
                   7445:             $homeserver = &domain($cdom,'primary');
                   7446:         }
                   7447:     }
1.1065    raeburn  7448:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7449:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7450:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7451:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7452: }
                   7453: 
1.506     raeburn  7454: sub auto_create_password {
1.873     raeburn  7455:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7456:     my ($homeserver,$response);
1.506     raeburn  7457:     my $create_passwd = 0;
                   7458:     my $authchk = '';
1.873     raeburn  7459:     if ($udom =~ /^$match_domain$/) {
                   7460:         $homeserver = &domain($udom,'primary');
                   7461:     }
                   7462:     if ($homeserver eq '') {
                   7463:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7464:             $homeserver = &homeserver($cnum,$cdom);
                   7465:         }
                   7466:     }
                   7467:     if ($homeserver eq '') {
                   7468:         $authchk = 'nodomain';
1.506     raeburn  7469:     } else {
1.873     raeburn  7470:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7471:         if ($response eq 'refused') {
                   7472:             $authchk = 'refused';
                   7473:         } else {
1.901     albertel 7474:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7475:         }
1.506     raeburn  7476:     }
                   7477:     return ($authparam,$create_passwd,$authchk);
                   7478: }
                   7479: 
1.706     raeburn  7480: sub auto_photo_permission {
                   7481:     my ($cnum,$cdom,$students) = @_;
                   7482:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7483:     my ($outcome,$perm_reqd,$conditions) = 
                   7484: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7485:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7486: 	return (undef,undef);
                   7487:     }
1.706     raeburn  7488:     return ($outcome,$perm_reqd,$conditions);
                   7489: }
                   7490: 
                   7491: sub auto_checkphotos {
                   7492:     my ($uname,$udom,$pid) = @_;
                   7493:     my $homeserver = &homeserver($uname,$udom);
                   7494:     my ($result,$resulttype);
                   7495:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7496: 				   &escape($uname).':'.&escape($pid),
                   7497: 				   $homeserver));
1.709     albertel 7498:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7499: 	return (undef,undef);
                   7500:     }
1.706     raeburn  7501:     if ($outcome) {
                   7502:         ($result,$resulttype) = split(/:/,$outcome);
                   7503:     } 
                   7504:     return ($result,$resulttype);
                   7505: }
                   7506: 
                   7507: sub auto_photochoice {
                   7508:     my ($cnum,$cdom) = @_;
                   7509:     my $homeserver = &homeserver($cnum,$cdom);
                   7510:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7511: 						       &escape($cdom),
                   7512: 						       $homeserver)));
1.709     albertel 7513:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7514: 	return (undef,undef);
                   7515:     }
1.706     raeburn  7516:     return ($update,$comment);
                   7517: }
                   7518: 
                   7519: sub auto_photoupdate {
                   7520:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7521:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7522:     my $host=&hostname($homeserver);
1.706     raeburn  7523:     my $cmd = '';
                   7524:     my $maxtries = 1;
1.800     albertel 7525:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7526:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7527:     }
                   7528:     $cmd =~ s/%%$//;
                   7529:     $cmd = &escape($cmd);
                   7530:     my $query = 'institutionalphotos';
                   7531:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7532:     unless ($queryid=~/^\Q$host\E\_/) {
                   7533:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7534:         return 'error: '.$queryid;
                   7535:     }
                   7536:     my $reply = &get_query_reply($queryid);
                   7537:     my $tries = 1;
                   7538:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7539:         $reply = &get_query_reply($queryid);
                   7540:         $tries ++;
                   7541:     }
                   7542:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7543:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7544:     } else {
                   7545:         my @responses = split(/:/,$reply);
                   7546:         my $outcome = shift(@responses); 
                   7547:         foreach my $item (@responses) {
                   7548:             my ($key,$value) = split(/=/,$item);
                   7549:             $$photo{$key} = $value;
                   7550:         }
                   7551:         return $outcome;
                   7552:     }
                   7553:     return 'error';
                   7554: }
                   7555: 
1.521     raeburn  7556: sub auto_instcode_format {
1.793     albertel 7557:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7558: 	$cat_order) = @_;
1.521     raeburn  7559:     my $courses = '';
1.772     raeburn  7560:     my @homeservers;
1.521     raeburn  7561:     if ($caller eq 'global') {
1.841     albertel 7562: 	my %servers = &get_servers($codedom,'library');
                   7563: 	foreach my $tryserver (keys(%servers)) {
                   7564: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7565: 		push(@homeservers,$tryserver);
                   7566: 	    }
1.584     raeburn  7567:         }
1.1022    raeburn  7568:     } elsif ($caller eq 'requests') {
                   7569:         if ($codedom =~ /^$match_domain$/) {
                   7570:             my $chome = &domain($codedom,'primary');
                   7571:             unless ($chome eq 'no_host') {
                   7572:                 push(@homeservers,$chome);
                   7573:             }
                   7574:         }
1.521     raeburn  7575:     } else {
1.772     raeburn  7576:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7577:     }
1.793     albertel 7578:     foreach my $code (keys(%{$instcodes})) {
                   7579:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7580:     }
                   7581:     chop($courses);
1.772     raeburn  7582:     my $ok_response = 0;
                   7583:     my $response;
                   7584:     while (@homeservers > 0 && $ok_response == 0) {
                   7585:         my $server = shift(@homeservers); 
                   7586:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7587:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7588:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7589: 		split(/:/,$response);
1.772     raeburn  7590:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7591:             push(@{$codetitles},&str2array($codetitles_str));
                   7592:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7593:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7594:             $ok_response = 1;
                   7595:         }
                   7596:     }
                   7597:     if ($ok_response) {
1.521     raeburn  7598:         return 'ok';
1.772     raeburn  7599:     } else {
                   7600:         return $response;
1.521     raeburn  7601:     }
                   7602: }
                   7603: 
1.792     raeburn  7604: sub auto_instcode_defaults {
                   7605:     my ($domain,$returnhash,$code_order) = @_;
                   7606:     my @homeservers;
1.841     albertel 7607: 
                   7608:     my %servers = &get_servers($domain,'library');
                   7609:     foreach my $tryserver (keys(%servers)) {
                   7610: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7611: 	    push(@homeservers,$tryserver);
                   7612: 	}
1.792     raeburn  7613:     }
1.841     albertel 7614: 
1.792     raeburn  7615:     my $response;
1.841     albertel 7616:     foreach my $server (@homeservers) {
1.792     raeburn  7617:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7618:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7619: 	
                   7620: 	foreach my $pair (split(/\&/,$response)) {
                   7621: 	    my ($name,$value)=split(/\=/,$pair);
                   7622: 	    if ($name eq 'code_order') {
                   7623: 		@{$code_order} = split(/\&/,&unescape($value));
                   7624: 	    } else {
                   7625: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7626: 	    }
                   7627: 	}
                   7628: 	return 'ok';
1.792     raeburn  7629:     }
1.841     albertel 7630: 
                   7631:     return $response;
1.1003    raeburn  7632: }
                   7633: 
                   7634: sub auto_possible_instcodes {
1.1007    raeburn  7635:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7636:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7637:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7638:         return;
                   7639:     }
1.1003    raeburn  7640:     my (@homeservers,$uhome);
                   7641:     if (defined(&domain($domain,'primary'))) {
                   7642:         $uhome=&domain($domain,'primary');
                   7643:         push(@homeservers,&domain($domain,'primary'));
                   7644:     } else {
                   7645:         my %servers = &get_servers($domain,'library');
                   7646:         foreach my $tryserver (keys(%servers)) {
                   7647:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7648:                 push(@homeservers,$tryserver);
                   7649:             }
                   7650:         }
                   7651:     }
                   7652:     my $response;
                   7653:     foreach my $server (@homeservers) {
                   7654:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7655:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7656:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7657:             split(':',$response);
                   7658:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7659:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7660:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7661:             my ($name,$value)=split('=',$item);
                   7662:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7663:         }
                   7664:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7665:             my ($name,$value)=split('=',$item);
                   7666:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7667:         }
                   7668:         return 'ok';
                   7669:     }
                   7670:     return $response;
                   7671: }
1.792     raeburn  7672: 
1.1010    raeburn  7673: sub auto_courserequest_checks {
                   7674:     my ($dom) = @_;
1.1020    raeburn  7675:     my ($homeserver,%validations);
                   7676:     if ($dom =~ /^$match_domain$/) {
                   7677:         $homeserver = &domain($dom,'primary');
                   7678:     }
                   7679:     unless ($homeserver eq 'no_host') {
                   7680:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7681:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7682:             my @items = split(/&/,$response);
                   7683:             foreach my $item (@items) {
                   7684:                 my ($key,$value) = split('=',$item);
                   7685:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7686:             }
                   7687:         }
                   7688:     }
1.1010    raeburn  7689:     return %validations; 
                   7690: }
                   7691: 
1.1020    raeburn  7692: sub auto_courserequest_validation {
                   7693:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7694:     my ($homeserver,$response);
                   7695:     if ($dom =~ /^$match_domain$/) {
                   7696:         $homeserver = &domain($dom,'primary');
                   7697:     }
                   7698:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7699:           
1.1020    raeburn  7700:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7701:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7702:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7703:                                     $homeserver));
                   7704:     }
                   7705:     return $response;
                   7706: }
                   7707: 
1.777     albertel 7708: sub auto_validate_class_sec {
1.918     raeburn  7709:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7710:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7711:     my $ownerlist;
                   7712:     if (ref($owners) eq 'ARRAY') {
                   7713:         $ownerlist = join(',',@{$owners});
                   7714:     } else {
                   7715:         $ownerlist = $owners;
                   7716:     }
1.773     raeburn  7717:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7718:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7719:     return $response;
                   7720: }
                   7721: 
1.679     raeburn  7722: # ------------------------------------------------------- Course Group routines
                   7723: 
                   7724: sub get_coursegroups {
1.809     raeburn  7725:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7726:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7727: }
                   7728: 
1.679     raeburn  7729: sub modify_coursegroup {
                   7730:     my ($cdom,$cnum,$groupsettings) = @_;
                   7731:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7732: }
                   7733: 
1.809     raeburn  7734: sub toggle_coursegroup_status {
                   7735:     my ($cdom,$cnum,$group,$action) = @_;
                   7736:     my ($from_namespace,$to_namespace);
                   7737:     if ($action eq 'delete') {
                   7738:         $from_namespace = 'coursegroups';
                   7739:         $to_namespace = 'deleted_groups';
                   7740:     } else {
                   7741:         $from_namespace = 'deleted_groups';
                   7742:         $to_namespace = 'coursegroups';
                   7743:     }
                   7744:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7745:     if (my $tmp = &error(%curr_group)) {
                   7746:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7747:         return ('read error',$tmp);
                   7748:     } else {
                   7749:         my %savedsettings = %curr_group; 
1.809     raeburn  7750:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7751:         my $deloutcome;
                   7752:         if ($result eq 'ok') {
1.809     raeburn  7753:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7754:         } else {
                   7755:             return ('write error',$result);
                   7756:         }
                   7757:         if ($deloutcome eq 'ok') {
                   7758:             return 'ok';
                   7759:         } else {
                   7760:             return ('delete error',$deloutcome);
                   7761:         }
                   7762:     }
                   7763: }
                   7764: 
1.679     raeburn  7765: sub modify_group_roles {
1.957     raeburn  7766:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7767:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7768:     my $role = 'gr/'.&escape($userprivs);
                   7769:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7770:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7771:     if ($result eq 'ok') {
                   7772:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7773:     }
1.679     raeburn  7774:     return $result;
                   7775: }
                   7776: 
                   7777: sub modify_coursegroup_membership {
                   7778:     my ($cdom,$cnum,$membership) = @_;
                   7779:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7780:     return $result;
                   7781: }
                   7782: 
1.682     raeburn  7783: sub get_active_groups {
                   7784:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7785:     my $now = time;
                   7786:     my %groups = ();
                   7787:     foreach my $key (keys(%env)) {
1.811     albertel 7788:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7789:             my ($start,$end) = split(/\./,$env{$key});
                   7790:             if (($end!=0) && ($end<$now)) { next; }
                   7791:             if (($start!=0) && ($start>$now)) { next; }
                   7792:             if ($1 eq $cdom && $2 eq $cnum) {
                   7793:                 $groups{$3} = $env{$key} ;
                   7794:             }
                   7795:         }
                   7796:     }
                   7797:     return %groups;
                   7798: }
                   7799: 
1.683     raeburn  7800: sub get_group_membership {
                   7801:     my ($cdom,$cnum,$group) = @_;
                   7802:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7803: }
                   7804: 
                   7805: sub get_users_groups {
                   7806:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7807:     my @usersgroups;
1.683     raeburn  7808:     my $cachetime=1800;
                   7809: 
                   7810:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7811:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7812:     if (defined($cached)) {
1.734     albertel 7813:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7814:     } else {  
                   7815:         $grouplist = '';
1.816     raeburn  7816:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7817:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7818:         my $access_end = $env{'course.'.$courseid.
                   7819:                               '.default_enrollment_end_date'};
                   7820:         my $now = time;
                   7821:         foreach my $key (keys(%roleshash)) {
                   7822:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7823:                 my $group = $1;
                   7824:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7825:                     my $start = $2;
                   7826:                     my $end = $1;
                   7827:                     if ($start == -1) { next; } # deleted from group
                   7828:                     if (($start!=0) && ($start>$now)) { next; }
                   7829:                     if (($end!=0) && ($end<$now)) {
                   7830:                         if ($access_end && $access_end < $now) {
                   7831:                             if ($access_end - $end < 86400) {
                   7832:                                 push(@usersgroups,$group);
1.733     raeburn  7833:                             }
                   7834:                         }
1.817     raeburn  7835:                         next;
1.733     raeburn  7836:                     }
1.817     raeburn  7837:                     push(@usersgroups,$group);
1.683     raeburn  7838:                 }
                   7839:             }
                   7840:         }
1.817     raeburn  7841:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7842:         $grouplist = join(':',@usersgroups);
                   7843:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7844:     }
1.733     raeburn  7845:     return @usersgroups;
1.683     raeburn  7846: }
                   7847: 
                   7848: sub devalidate_getgroups_cache {
                   7849:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7850:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7851: 
1.683     raeburn  7852:     my $hashid="$udom:$uname:$courseid";
                   7853:     &devalidate_cache_new('getgroups',$hashid);
                   7854: }
                   7855: 
1.12      www      7856: # ------------------------------------------------------------------ Plain Text
                   7857: 
                   7858: sub plaintext {
1.988     raeburn  7859:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7860:     if ($short =~ m{^cr/}) {
1.758     albertel 7861: 	return (split('/',$short))[-1];
                   7862:     }
1.742     raeburn  7863:     if (!defined($cid)) {
                   7864:         $cid = $env{'request.course.id'};
                   7865:     }
                   7866:     my %rolenames = (
1.1008    raeburn  7867:                       Course    => 'std',
                   7868:                       Community => 'alt1',
1.742     raeburn  7869:                     );
1.1037    raeburn  7870:     if ($cid ne '') {
                   7871:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7872:             unless ($forcedefault) {
                   7873:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7874:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7875:                 return &Apache::lonlocal::mt($roletext);
                   7876:             }
                   7877:         }
                   7878:     }
                   7879:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7880:         (defined($rolenames{$type})) && 
                   7881:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7882:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7883:     } elsif ($cid ne '') {
                   7884:         my $crstype = $env{'course.'.$cid.'.type'};
                   7885:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7886:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7887:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7888:         }
1.742     raeburn  7889:     }
1.1037    raeburn  7890:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7891: }
                   7892: 
                   7893: # ----------------------------------------------------------------- Assign Role
                   7894: 
                   7895: sub assignrole {
1.957     raeburn  7896:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7897:         $context)=@_;
1.21      www      7898:     my $mrole;
                   7899:     if ($role =~ /^cr\//) {
1.393     www      7900:         my $cwosec=$url;
1.811     albertel 7901:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7902: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7903:            my $refused = 1;
                   7904:            if ($context eq 'requestcourses') {
                   7905:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7906:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7907:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7908:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7909:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7910:                            if ($crsenv{'internal.courseowner'} eq
                   7911:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7912:                                $refused = '';
                   7913:                            }
                   7914:                        }
                   7915:                    }
                   7916:                }
                   7917:            }
                   7918:            if ($refused) {
                   7919:                &logthis('Refused custom assignrole: '.
                   7920:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7921:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7922:                return 'refused';
                   7923:            }
1.104     www      7924:         }
1.21      www      7925:         $mrole='cr';
1.678     raeburn  7926:     } elsif ($role =~ /^gr\//) {
                   7927:         my $cwogrp=$url;
1.811     albertel 7928:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7929:         unless (&allowed('mdg',$cwogrp)) {
                   7930:             &logthis('Refused group assignrole: '.
                   7931:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7932:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7933:             return 'refused';
                   7934:         }
                   7935:         $mrole='gr';
1.21      www      7936:     } else {
1.82      www      7937:         my $cwosec=$url;
1.811     albertel 7938:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7939:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7940:             my $refused;
                   7941:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7942:                 if (!(&allowed('c'.$role,$url))) {
                   7943:                     $refused = 1;
                   7944:                 }
                   7945:             } else {
                   7946:                 $refused = 1;
                   7947:             }
1.947     raeburn  7948:             if ($refused) {
1.1045    raeburn  7949:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7950:                 if (!$selfenroll && $context eq 'course') {
                   7951:                     my %crsenv;
                   7952:                     if ($role eq 'cc' || $role eq 'co') {
                   7953:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7954:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7955:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7956:                                 if ($crsenv{'internal.courseowner'} eq 
                   7957:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7958:                                     $refused = '';
                   7959:                                 }
                   7960:                             }
                   7961:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7962:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7963:                                 if ($crsenv{'internal.courseowner'} eq 
                   7964:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7965:                                     $refused = '';
                   7966:                                 }
                   7967:                             }
                   7968:                         }
                   7969:                     }
                   7970:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7971:                     $refused = '';
1.1017    raeburn  7972:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7973:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7974:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7975:                         my $wrongcc;
                   7976:                         if ($cnum =~ /^$match_community$/) {
                   7977:                             $wrongcc = 1 if ($role eq 'cc');
                   7978:                         } else {
                   7979:                             $wrongcc = 1 if ($role eq 'co');
                   7980:                         }
                   7981:                         unless ($wrongcc) {
                   7982:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7983:                             if ($crsenv{'internal.courseowner'} eq 
                   7984:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7985:                                 $refused = '';
                   7986:                             }
1.1017    raeburn  7987:                         }
                   7988:                     }
1.1183    raeburn  7989:                 } elsif ($context eq 'requestauthor') {
                   7990:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   7991:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7992:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7993:                             $refused = '';
                   7994:                         } else {
                   7995:                             my %domdefaults = &get_domain_defaults($udom);
                   7996:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7997:                                 my $checkbystatus;
                   7998:                                 if ($env{'user.adv'}) { 
                   7999:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8000:                                     if ($disposition eq 'automatic') {
                   8001:                                         $refused = '';
                   8002:                                     } elsif ($disposition eq '') {
                   8003:                                         $checkbystatus = 1;
                   8004:                                     } 
                   8005:                                 } else {
                   8006:                                     $checkbystatus = 1;
                   8007:                                 }
                   8008:                                 if ($checkbystatus) {
                   8009:                                     if ($env{'environment.inststatus'}) {
                   8010:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8011:                                         foreach my $type (@inststatuses) {
                   8012:                                             if (($type ne '') &&
                   8013:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8014:                                                 $refused = '';
                   8015:                                             }
                   8016:                                         }
                   8017:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8018:                                         $refused = '';
                   8019:                                     }
                   8020:                                 }
                   8021:                             }
                   8022:                         }
                   8023:                     }
1.1017    raeburn  8024:                 }
                   8025:                 if ($refused) {
1.947     raeburn  8026:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8027:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8028: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8029:                     return 'refused';
                   8030:                 }
1.932     raeburn  8031:             }
1.1131    raeburn  8032:         } elsif ($role eq 'au') {
                   8033:             if ($url ne '/'.$udom.'/') {
                   8034:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8035:                          ' to assign author role for '.$uname.':'.$udom.
                   8036:                          ' in domain: '.$url.' refused (wrong domain).');
                   8037:                 return 'refused';
                   8038:             }
1.104     www      8039:         }
1.21      www      8040:         $mrole=$role;
                   8041:     }
1.620     albertel 8042:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8043:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8044:     if ($end) { $command.='_'.$end; }
1.21      www      8045:     if ($start) {
                   8046: 	if ($end) { 
1.81      www      8047:            $command.='_'.$start; 
1.21      www      8048:         } else {
1.81      www      8049:            $command.='_0_'.$start;
1.21      www      8050:         }
                   8051:     }
1.739     raeburn  8052:     my $origstart = $start;
                   8053:     my $origend = $end;
1.957     raeburn  8054:     my $delflag;
1.357     www      8055: # actually delete
                   8056:     if ($deleteflag) {
1.373     www      8057: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8058: # modify command to delete the role
1.620     albertel 8059:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8060:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8061: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8062: # set start and finish to negative values for userrolelog
                   8063:            $start=-1;
                   8064:            $end=-1;
1.957     raeburn  8065:            $delflag = 1;
1.357     www      8066:         }
                   8067:     }
                   8068: # send command
1.349     www      8069:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8070: # log new user role if status is ok
1.349     www      8071:     if ($answer eq 'ok') {
1.663     raeburn  8072: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8073:         if (($role eq 'cc') || ($role eq 'in') ||
                   8074:             ($role eq 'ep') || ($role eq 'ad') ||
                   8075:             ($role eq 'ta') || ($role eq 'st') ||
                   8076:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8077:             ($role eq 'co')) {
1.1200    raeburn  8078: # for course roles, perform group memberships changes triggered by role change.
                   8079:             unless ($role =~ /^gr/) {
                   8080:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8081:                                                  $origstart,$selfenroll,$context);
                   8082:             }
1.1184    raeburn  8083:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8084:                            $selfenroll,$context);
                   8085:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8086:                  ($role eq 'au') || ($role eq 'dc')) {
                   8087:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8088:                            $context);
                   8089:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8090:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8091:                              $context); 
                   8092:         }
1.1053    raeburn  8093:         if ($role eq 'cc') {
                   8094:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8095:         }
1.349     www      8096:     }
                   8097:     return $answer;
1.169     harris41 8098: }
                   8099: 
1.1053    raeburn  8100: sub autoupdate_coowners {
                   8101:     my ($url,$end,$start,$uname,$udom) = @_;
                   8102:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8103:     if (($cdom ne '') && ($cnum ne '')) {
                   8104:         my $now = time;
                   8105:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8106:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8107:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8108:             my $instcode = $coursehash{'internal.coursecode'};
                   8109:             if ($instcode ne '') {
1.1056    raeburn  8110:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8111:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8112:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8113:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8114:                         if ($result eq 'valid') {
                   8115:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8116:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8117:                                     push(@newcoowners,$coowner);
                   8118:                                 }
                   8119:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8120:                                     push(@newcoowners,$uname.':'.$udom);
                   8121:                                 }
                   8122:                                 @newcoowners = sort(@newcoowners);
                   8123:                             } else {
                   8124:                                 push(@newcoowners,$uname.':'.$udom);
                   8125:                             }
                   8126:                         } else {
                   8127:                             if ($coursehash{'internal.co-owners'}) {
                   8128:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8129:                                     unless ($coowner eq $uname.':'.$udom) {
                   8130:                                         push(@newcoowners,$coowner);
                   8131:                                     }
                   8132:                                 }
                   8133:                                 unless (@newcoowners > 0) {
                   8134:                                     $delcoowners = 1;
                   8135:                                     $coowners = '';
                   8136:                                 }
                   8137:                             }
                   8138:                         }
                   8139:                         if (@newcoowners || $delcoowners) {
                   8140:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8141:                                             $delcoowners,@newcoowners);
                   8142:                         }
                   8143:                     }
                   8144:                 }
                   8145:             }
                   8146:         }
                   8147:     }
                   8148: }
                   8149: 
                   8150: sub store_coowners {
                   8151:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8152:     my $cid = $cdom.'_'.$cnum;
                   8153:     my ($coowners,$delresult,$putresult);
                   8154:     if (@newcoowners) {
                   8155:         $coowners = join(',',@newcoowners);
                   8156:         my %coownershash = (
                   8157:                             'internal.co-owners' => $coowners,
                   8158:                            );
                   8159:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8160:         if ($putresult eq 'ok') {
                   8161:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8162:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8163:             }
                   8164:         }
                   8165:     }
                   8166:     if ($delcoowners) {
                   8167:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8168:         if ($delresult eq 'ok') {
                   8169:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8170:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8171:             }
                   8172:         }
                   8173:     }
                   8174:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8175:         my %crsinfo =
                   8176:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8177:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8178:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8179:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8180:         }
                   8181:     }
                   8182: }
                   8183: 
1.169     harris41 8184: # -------------------------------------------------- Modify user authentication
1.197     www      8185: # Overrides without validation
                   8186: 
1.169     harris41 8187: sub modifyuserauth {
                   8188:     my ($udom,$uname,$umode,$upass)=@_;
                   8189:     my $uhome=&homeserver($uname,$udom);
1.197     www      8190:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8191:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8192:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8193:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8194:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8195: 		     &escape($upass),$uhome);
1.620     albertel 8196:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8197:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8198:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8199:     &log($udom,,$uname,$uhome,
1.620     albertel 8200:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8201:                                      $env{'user.name'}.', '.$umode.
1.197     www      8202:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8203:     unless ($reply eq 'ok') {
1.197     www      8204:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8205: 	return 'error: '.$reply;
                   8206:     }   
1.170     harris41 8207:     return 'ok';
1.80      www      8208: }
                   8209: 
1.81      www      8210: # --------------------------------------------------------------- Modify a user
1.80      www      8211: 
1.81      www      8212: sub modifyuser {
1.206     matthew  8213:     my ($udom,    $uname, $uid,
                   8214:         $umode,   $upass, $first,
                   8215:         $middle,  $last,  $gene,
1.1058    raeburn  8216:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8217:     $udom= &LONCAPA::clean_domain($udom);
                   8218:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8219:     my $showcandelete = 'none';
                   8220:     if (ref($candelete) eq 'ARRAY') {
                   8221:         if (@{$candelete} > 0) {
                   8222:             $showcandelete = join(', ',@{$candelete});
                   8223:         }
                   8224:     }
1.81      www      8225:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8226:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8227: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8228:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8229:                                      ' desiredhome not specified'). 
1.620     albertel 8230:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8231:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8232:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8233:     my $newuser;
                   8234:     if ($uhome eq 'no_host') {
                   8235:         $newuser = 1;
                   8236:     }
1.80      www      8237: # ----------------------------------------------------------------- Create User
1.406     albertel 8238:     if (($uhome eq 'no_host') && 
                   8239: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8240:         my $unhome='';
1.844     albertel 8241:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8242:             $unhome = $desiredhome;
1.620     albertel 8243: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8244: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8245:         } else { # load balancing routine for determining $unhome
1.81      www      8246:             my $loadm=10000000;
1.841     albertel 8247: 	    my %servers = &get_servers($udom,'library');
                   8248: 	    foreach my $tryserver (keys(%servers)) {
                   8249: 		my $answer=reply('load',$tryserver);
                   8250: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8251: 		    $loadm=$answer;
                   8252: 		    $unhome=$tryserver;
                   8253: 		}
1.80      www      8254: 	    }
                   8255:         }
                   8256:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8257: 	    return 'error: unable to find a home server for '.$uname.
                   8258:                    ' in domain '.$udom;
1.80      www      8259:         }
                   8260:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8261:                          &escape($upass),$unhome);
                   8262: 	unless ($reply eq 'ok') {
                   8263:             return 'error: '.$reply;
                   8264:         }   
1.230     stredwic 8265:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8266:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8267: 	    return 'error: unable verify users home machine.';
1.80      www      8268:         }
1.209     matthew  8269:     }   # End of creation of new user
1.80      www      8270: # ---------------------------------------------------------------------- Add ID
                   8271:     if ($uid) {
                   8272:        $uid=~tr/A-Z/a-z/;
                   8273:        my %uidhash=&idrget($udom,$uname);
1.196     www      8274:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8275:          && (!$forceid)) {
1.80      www      8276: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8277: 	      return 'error: user id "'.$uid.'" does not match '.
                   8278:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8279:           }
                   8280:        } else {
                   8281: 	  &idput($udom,($uname => $uid));
                   8282:        }
                   8283:     }
                   8284: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8285:     my @tmp=&get('environment',
1.899     raeburn  8286: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8287:                     'permanentemail','inststatus'],
1.134     albertel 8288: 		   $udom,$uname);
1.1075    raeburn  8289:     my (%names,%oldnames);
1.313     matthew  8290:     if ($tmp[0] =~ m/^error:.*/) { 
                   8291:         %names=(); 
                   8292:     } else {
                   8293:         %names = @tmp;
1.1075    raeburn  8294:         %oldnames = %names;
1.313     matthew  8295:     }
1.388     www      8296: #
1.1058    raeburn  8297: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8298: # of users did not contain them), do not overwrite existing values
                   8299: # unless field is in $candelete array ref.  
                   8300: #
                   8301: 
                   8302:     my @fields = ('firstname','middlename','lastname','generation',
                   8303:                   'permanentemail','id');
                   8304:     my %newvalues;
                   8305:     if (ref($candelete) eq 'ARRAY') {
                   8306:         foreach my $field (@fields) {
                   8307:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8308:                 if ($field eq 'firstname') {
                   8309:                     $names{$field} = $first;
                   8310:                 } elsif ($field eq 'middlename') {
                   8311:                     $names{$field} = $middle;
                   8312:                 } elsif ($field eq 'lastname') {
                   8313:                     $names{$field} = $last;
                   8314:                 } elsif ($field eq 'generation') { 
                   8315:                     $names{$field} = $gene;
                   8316:                 } elsif ($field eq 'permanentemail') {
                   8317:                     $names{$field} = $email;
                   8318:                 } elsif ($field eq 'id') {
                   8319:                     $names{$field}  = $uid;
                   8320:                 }
                   8321:             }
                   8322:         }
                   8323:     }
1.388     www      8324:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8325:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8326:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8327:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8328:     if ($email) {
                   8329:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8330:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8331:     }
1.899     raeburn  8332:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8333:     if (defined($inststatus)) {
                   8334:         $names{'inststatus'} = '';
                   8335:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8336:         if (ref($usertypes) eq 'HASH') {
                   8337:             my @okstatuses; 
                   8338:             foreach my $item (split(/:/,$inststatus)) {
                   8339:                 if (defined($usertypes->{$item})) {
                   8340:                     push(@okstatuses,$item);  
                   8341:                 }
                   8342:             }
                   8343:             if (@okstatuses) {
                   8344:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8345:             }
                   8346:         }
                   8347:     }
1.1075    raeburn  8348:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8349:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8350:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8351:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8352:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8353:     } else {
                   8354:         $logmsg .= ' during self creation';
                   8355:     }
1.1075    raeburn  8356:     my $changed;
                   8357:     if ($newuser) {
                   8358:         $changed = 1;
                   8359:     } else {
                   8360:         foreach my $field (@fields) {
                   8361:             if ($names{$field} ne $oldnames{$field}) {
                   8362:                 $changed = 1;
                   8363:                 last;
                   8364:             }
                   8365:         }
                   8366:     }
                   8367:     unless ($changed) {
                   8368:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8369:         &logthis($logmsg);
                   8370:         return 'ok';
                   8371:     }
                   8372:     my $reply = &put('environment', \%names, $udom,$uname);
                   8373:     if ($reply ne 'ok') { 
                   8374:         return 'error: '.$reply;
                   8375:     }
1.1087    raeburn  8376:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8377:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8378:     }
1.1075    raeburn  8379:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8380:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8381:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8382:     &logthis($logmsg);
1.134     albertel 8383:     return 'ok';
1.80      www      8384: }
                   8385: 
1.81      www      8386: # -------------------------------------------------------------- Modify student
1.80      www      8387: 
1.81      www      8388: sub modifystudent {
                   8389:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8390:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8391:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8392:     if (!$cid) {
1.620     albertel 8393: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8394: 	    return 'not_in_class';
                   8395: 	}
1.80      www      8396:     }
                   8397: # --------------------------------------------------------------- Make the user
1.81      www      8398:     my $reply=&modifyuser
1.209     matthew  8399: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8400:          $desiredhome,$email,$inststatus);
1.80      www      8401:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8402:     # This will cause &modify_student_enrollment to get the uid from the
                   8403:     # students environment
                   8404:     $uid = undef if (!$forceid);
1.455     albertel 8405:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8406:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8407:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8408:     return $reply;
                   8409: }
                   8410: 
                   8411: sub modify_student_enrollment {
1.1216    raeburn  8412:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8413:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8414:     my ($cdom,$cnum,$chome);
                   8415:     if (!$cid) {
1.620     albertel 8416: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8417: 	    return 'not_in_class';
                   8418: 	}
1.620     albertel 8419: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8420: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8421:     } else {
                   8422: 	($cdom,$cnum)=split(/_/,$cid);
                   8423:     }
1.620     albertel 8424:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8425:     if (!$chome) {
1.457     raeburn  8426: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8427:     }
1.455     albertel 8428:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8429:     # Make sure the user exists
1.81      www      8430:     my $uhome=&homeserver($uname,$udom);
                   8431:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8432: 	return 'error: no such user';
                   8433:     }
1.297     matthew  8434:     # Get student data if we were not given enough information
                   8435:     if (!defined($first)  || $first  eq '' || 
                   8436:         !defined($last)   || $last   eq '' || 
                   8437:         !defined($uid)    || $uid    eq '' || 
                   8438:         !defined($middle) || $middle eq '' || 
                   8439:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8440:         # They did not supply us with enough data to enroll the student, so
                   8441:         # we need to pick up more information.
1.297     matthew  8442:         my %tmp = &get('environment',
1.294     matthew  8443:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8444:                        ,$udom,$uname);
                   8445: 
1.800     albertel 8446:         #foreach my $key (keys(%tmp)) {
                   8447:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8448:         #}
1.294     matthew  8449:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8450:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8451:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8452:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8453:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8454:     }
1.556     albertel 8455:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8456:     my $user = "$uname:$udom";
                   8457:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8458:     my $reply=cput('classlist',
1.1148    raeburn  8459: 		   {$user => 
1.1216    raeburn  8460: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8461: 		   $cdom,$cnum);
1.1148    raeburn  8462:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8463:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8464:     } else { 
1.81      www      8465: 	return 'error: '.$reply;
                   8466:     }
1.297     matthew  8467:     # Add student role to user
1.83      www      8468:     my $uurl='/'.$cid;
1.81      www      8469:     $uurl=~s/\_/\//g;
                   8470:     if ($usec) {
                   8471: 	$uurl.='/'.$usec;
                   8472:     }
1.1148    raeburn  8473:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8474:                              $selfenroll,$context);
                   8475:     if ($result ne 'ok') {
                   8476:         if ($old_entry{$user} ne '') {
                   8477:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8478:         } else {
                   8479:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8480:         }
                   8481:     }
                   8482:     return $result; 
1.21      www      8483: }
                   8484: 
1.556     albertel 8485: sub format_name {
                   8486:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8487:     my $name;
                   8488:     if ($first ne 'lastname') {
                   8489: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8490:     } else {
                   8491: 	if ($lastname=~/\S/) {
                   8492: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8493: 	    $name=~s/\s+,/,/;
                   8494: 	} else {
                   8495: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8496: 	}
                   8497:     }
                   8498:     $name=~s/^\s+//;
                   8499:     $name=~s/\s+$//;
                   8500:     $name=~s/\s+/ /g;
                   8501:     return $name;
                   8502: }
                   8503: 
1.84      www      8504: # ------------------------------------------------- Write to course preferences
                   8505: 
                   8506: sub writecoursepref {
                   8507:     my ($courseid,%prefs)=@_;
                   8508:     $courseid=~s/^\///;
                   8509:     $courseid=~s/\_/\//g;
                   8510:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8511:     my $chome=homeserver($cnum,$cdomain);
                   8512:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8513: 	return 'error: no such course';
                   8514:     }
                   8515:     my $cstring='';
1.800     albertel 8516:     foreach my $pref (keys(%prefs)) {
                   8517: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8518:     }
1.84      www      8519:     $cstring=~s/\&$//;
                   8520:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8521: }
                   8522: 
                   8523: # ---------------------------------------------------------- Make/modify course
                   8524: 
                   8525: sub createcourse {
1.741     raeburn  8526:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8527:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8528:     $url=&declutter($url);
                   8529:     my $cid='';
1.1028    raeburn  8530:     if ($context eq 'requestcourses') {
                   8531:         my $can_create = 0;
                   8532:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8533:         if ($udom eq $ownerdom) {
                   8534:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8535:                                   $context)) {
                   8536:                 $can_create = 1;
                   8537:             }
                   8538:         } else {
                   8539:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8540:                                            $category);
                   8541:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8542:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8543:                 if (@curr > 0) {
                   8544:                     my @options = qw(approval validate autolimit);
                   8545:                     my $optregex = join('|',@options);
                   8546:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8547:                         $can_create = 1;
                   8548:                     }
                   8549:                 }
                   8550:             }
                   8551:         }
                   8552:         if ($can_create) {
                   8553:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8554:                 unless (&allowed('ccc',$udom)) {
                   8555:                     return 'refused'; 
                   8556:                 }
1.1017    raeburn  8557:             }
                   8558:         } else {
                   8559:             return 'refused';
                   8560:         }
1.1028    raeburn  8561:     } elsif (!&allowed('ccc',$udom)) {
                   8562:         return 'refused';
1.84      www      8563:     }
1.1011    raeburn  8564: # --------------------------------------------------------------- Get Unique ID
                   8565:     my $uname;
                   8566:     if ($cnum =~ /^$match_courseid$/) {
                   8567:         my $chome=&homeserver($cnum,$udom,'true');
                   8568:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8569:             $uname = $cnum;
                   8570:         } else {
1.1038    raeburn  8571:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8572:         }
                   8573:     } else {
1.1038    raeburn  8574:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8575:     }
                   8576:     return $uname if ($uname =~ /^error/);
                   8577: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8578:     if (!defined($course_server)) {
                   8579:         if (defined(&domain($udom,'primary'))) {
                   8580:             $course_server = &domain($udom,'primary');
                   8581:         } else {
                   8582:             $course_server = $env{'user.home'}; 
                   8583:         }
                   8584:     }
                   8585:     my %host_servers =
                   8586:         &Apache::lonnet::get_servers($udom,'library');
                   8587:     unless ($host_servers{$course_server}) {
                   8588:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8589:     }
1.84      www      8590: # ------------------------------------------------------------- Make the course
                   8591:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8592:                       $course_server);
1.84      www      8593:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8594:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8595:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8596: 	return 'error: no such course';
                   8597:     }
1.271     www      8598: # ----------------------------------------------------------------- Course made
1.516     raeburn  8599: # log existence
1.1029    raeburn  8600:     my $now = time;
1.918     raeburn  8601:     my $newcourse = {
                   8602:                     $udom.'_'.$uname => {
1.921     raeburn  8603:                                      description => $description,
                   8604:                                      inst_code   => $inst_code,
                   8605:                                      owner       => $course_owner,
                   8606:                                      type        => $crstype,
1.1029    raeburn  8607:                                      creator     => $env{'user.name'}.':'.
                   8608:                                                     $env{'user.domain'},
                   8609:                                      created     => $now,
                   8610:                                      context     => $context,
1.918     raeburn  8611:                                                 },
                   8612:                     };
1.921     raeburn  8613:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8614: # set toplevel url
1.271     www      8615:     my $topurl=$url;
                   8616:     unless ($nonstandard) {
                   8617: # ------------------------------------------ For standard courses, make top url
                   8618:         my $mapurl=&clutter($url);
1.278     www      8619:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8620:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8621: <map>
                   8622: <resource id="1" type="start"></resource>
                   8623: <resource id="2" src="$mapurl"></resource>
                   8624: <resource id="3" type="finish"></resource>
                   8625: <link index="1" from="1" to="2"></link>
                   8626: <link index="2" from="2" to="3"></link>
                   8627: </map>
                   8628: ENDINITMAP
                   8629:         $topurl=&declutter(
1.638     albertel 8630:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8631:                           );
                   8632:     }
                   8633: # ----------------------------------------------------------- Write preferences
1.84      www      8634:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8635:                      ('description'              => $description,
                   8636:                       'url'                      => $topurl,
                   8637:                       'internal.creator'         => $env{'user.name'}.':'.
                   8638:                                                     $env{'user.domain'},
                   8639:                       'internal.created'         => $now,
                   8640:                       'internal.creationcontext' => $context)
                   8641:                     );
1.84      www      8642:     return '/'.$udom.'/'.$uname;
                   8643: }
                   8644: 
1.1011    raeburn  8645: # ------------------------------------------------------------------- Create ID
                   8646: sub generate_coursenum {
1.1038    raeburn  8647:     my ($udom,$crstype) = @_;
1.1011    raeburn  8648:     my $domdesc = &domain($udom);
                   8649:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8650:     my $first;
                   8651:     if ($crstype eq 'Community') {
                   8652:         $first = '0';
                   8653:     } else {
                   8654:         $first = int(1+rand(9)); 
                   8655:     } 
                   8656:     my $uname=$first.
1.1011    raeburn  8657:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8658:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8659:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8660: # ----------------------------------------------- Make sure that does not exist
                   8661:     my $uhome=&homeserver($uname,$udom,'true');
                   8662:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8663:         if ($crstype eq 'Community') {
                   8664:             $first = '0';
                   8665:         } else {
                   8666:             $first = int(1+rand(9));
                   8667:         }
                   8668:         $uname=$first.
1.1011    raeburn  8669:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8670:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8671:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8672:         $uhome=&homeserver($uname,$udom,'true');
                   8673:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8674:             return 'error: unable to generate unique course-ID';
                   8675:         }
                   8676:     }
                   8677:     return $uname;
                   8678: }
                   8679: 
1.813     albertel 8680: sub is_course {
1.1167    droeschl 8681:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8682:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8683: 
                   8684:     return unless $cdom and $cnum;
                   8685: 
                   8686:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8687:         '.');
                   8688: 
                   8689:     return unless exists($courses{$cdom.'_'.$cnum});
                   8690:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8691: }
                   8692: 
1.1015    raeburn  8693: sub store_userdata {
                   8694:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8695:     my $result;
1.1016    raeburn  8696:     if ($datakey ne '') {
1.1013    raeburn  8697:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8698:             if ($udom eq '' || $uname eq '') {
                   8699:                 $udom = $env{'user.domain'};
                   8700:                 $uname = $env{'user.name'};
                   8701:             }
                   8702:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8703:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8704:                 $result = 'error: no_host';
                   8705:             } else {
                   8706:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8707:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8708: 
                   8709:                 my $namevalue='';
                   8710:                 foreach my $key (keys(%{$storehash})) {
                   8711:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8712:                 }
                   8713:                 $namevalue=~s/\&$//;
1.1105    raeburn  8714:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8715:                                   $namevalue,$uhome);
1.1013    raeburn  8716:             }
                   8717:         } else {
                   8718:             $result = 'error: data to store was not a hash reference'; 
                   8719:         }
                   8720:     } else {
                   8721:         $result= 'error: invalid requestkey'; 
                   8722:     }
                   8723:     return $result;
                   8724: }
                   8725: 
1.21      www      8726: # ---------------------------------------------------------- Assign Custom Role
                   8727: 
                   8728: sub assigncustomrole {
1.957     raeburn  8729:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8730:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8731:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8732: }
                   8733: 
                   8734: # ----------------------------------------------------------------- Revoke Role
                   8735: 
                   8736: sub revokerole {
1.957     raeburn  8737:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8738:     my $now=time;
1.965     raeburn  8739:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8740: }
                   8741: 
                   8742: # ---------------------------------------------------------- Revoke Custom Role
                   8743: 
                   8744: sub revokecustomrole {
1.957     raeburn  8745:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8746:     my $now=time;
1.357     www      8747:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8748:            $deleteflag,$selfenroll,$context);
1.17      www      8749: }
                   8750: 
1.533     banghart 8751: # ------------------------------------------------------------ Disk usage
1.535     albertel 8752: sub diskusage {
1.955     raeburn  8753:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8754:     $directorypath =~ s/\/$//;
                   8755:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8756:                        .&escape($getpropath).':'.&escape($uname).':'
                   8757:                        .&escape($udom),homeserver($uname,$udom));
                   8758:     if ($listing eq 'unknown_cmd') {
                   8759:         if ($getpropath) {
                   8760:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8761:         }
                   8762:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8763:     }
1.514     albertel 8764:     return $listing;
1.512     banghart 8765: }
                   8766: 
1.566     banghart 8767: sub is_locked {
1.1096    raeburn  8768:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8769:     my @check;
                   8770:     my $is_locked;
1.1093    raeburn  8771:     push (@check,$file_name);
1.613     albertel 8772:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8773: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8774:     my ($tmp)=keys(%locked);
                   8775:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8776:     
1.566     banghart 8777:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8778:         $is_locked = 'false';
                   8779:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8780:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8781:                $is_locked = 'true';
1.1096    raeburn  8782:                if (ref($which) eq 'ARRAY') {
                   8783:                    push(@{$which},$entry);
                   8784:                } else {
                   8785:                    last;
                   8786:                }
1.745     raeburn  8787:            }
                   8788:        }
1.566     banghart 8789:     } else {
                   8790:         $is_locked = 'false';
                   8791:     }
1.1093    raeburn  8792:     return $is_locked;
1.566     banghart 8793: }
                   8794: 
1.759     albertel 8795: sub declutter_portfile {
                   8796:     my ($file) = @_;
1.833     albertel 8797:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8798:     return $file;
                   8799: }
                   8800: 
1.559     banghart 8801: # ------------------------------------------------------------- Mark as Read Only
                   8802: 
                   8803: sub mark_as_readonly {
                   8804:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8805:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8806:     my ($tmp)=keys(%current_permissions);
                   8807:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8808:     foreach my $file (@{$files}) {
1.759     albertel 8809: 	$file = &declutter_portfile($file);
1.561     banghart 8810:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8811:     }
1.613     albertel 8812:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8813:     return;
                   8814: }
                   8815: 
1.572     banghart 8816: # ------------------------------------------------------------Save Selected Files
                   8817: 
                   8818: sub save_selected_files {
                   8819:     my ($user, $path, @files) = @_;
                   8820:     my $filename = $user."savedfiles";
1.573     banghart 8821:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8822:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8823:     foreach my $file (@files) {
1.620     albertel 8824:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8825:     }
                   8826:     foreach my $file (@other_files) {
1.574     banghart 8827:         print (OUT $file."\n");
1.572     banghart 8828:     }
1.574     banghart 8829:     close (OUT);
1.572     banghart 8830:     return 'ok';
                   8831: }
                   8832: 
1.574     banghart 8833: sub clear_selected_files {
                   8834:     my ($user) = @_;
                   8835:     my $filename = $user."savedfiles";
1.1117    foxr     8836:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8837:     print (OUT undef);
                   8838:     close (OUT);
                   8839:     return ("ok");    
                   8840: }
                   8841: 
1.572     banghart 8842: sub files_in_path {
                   8843:     my ($user, $path) = @_;
                   8844:     my $filename = $user."savedfiles";
                   8845:     my %return_files;
1.1117    foxr     8846:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8847:     while (my $line_in = <IN>) {
1.574     banghart 8848:         chomp ($line_in);
                   8849:         my @paths_and_file = split (m!/!, $line_in);
                   8850:         my $file_part = pop (@paths_and_file);
                   8851:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8852:         $path_part.='/';
                   8853:         my $path_and_file = $path_part.$file_part;
                   8854:         if ($path_part eq $path) {
                   8855:             $return_files{$file_part}= 'selected';
                   8856:         }
                   8857:     }
1.574     banghart 8858:     close (IN);
                   8859:     return (\%return_files);
1.572     banghart 8860: }
                   8861: 
                   8862: # called in portfolio select mode, to show files selected NOT in current directory
                   8863: sub files_not_in_path {
                   8864:     my ($user, $path) = @_;
                   8865:     my $filename = $user."savedfiles";
                   8866:     my @return_files;
                   8867:     my $path_part;
1.1117    foxr     8868:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8869:     while (my $line = <IN>) {
1.572     banghart 8870:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8871:         my @paths_and_file = split(m|/|, $line);
                   8872:         my $file_part = pop(@paths_and_file);
                   8873:         chomp($file_part);
                   8874:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8875:         $path_part .= '/';
                   8876:         my $path_and_file = $path_part.$file_part;
                   8877:         if ($path_part ne $path) {
1.800     albertel 8878:             push(@return_files, ($path_and_file));
1.572     banghart 8879:         }
                   8880:     }
1.800     albertel 8881:     close(OUT);
1.574     banghart 8882:     return (@return_files);
1.572     banghart 8883: }
                   8884: 
1.745     raeburn  8885: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8886: 
1.745     raeburn  8887: sub get_portfile_permissions {
                   8888:     my ($domain,$user) = @_;
1.613     albertel 8889:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8890:     my ($tmp)=keys(%current_permissions);
                   8891:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8892:     return \%current_permissions;
                   8893: }
                   8894: 
                   8895: #---------------------------------------------Get portfolio file access controls
                   8896: 
1.749     raeburn  8897: sub get_access_controls {
1.745     raeburn  8898:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8899:     my %access;
                   8900:     my $real_file = $file;
                   8901:     $file =~ s/\.meta$//;
1.745     raeburn  8902:     if (defined($file)) {
1.749     raeburn  8903:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8904:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8905:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8906:             }
                   8907:         }
1.745     raeburn  8908:     } else {
1.749     raeburn  8909:         foreach my $key (keys(%{$current_permissions})) {
                   8910:             if ($key =~ /\0accesscontrol$/) {
                   8911:                 if (defined($group)) {
                   8912:                     if ($key !~ m-^\Q$group\E/-) {
                   8913:                         next;
                   8914:                     }
                   8915:                 }
                   8916:                 my ($fullpath) = split(/\0/,$key);
                   8917:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8918:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8919:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8920:                     }
                   8921:                 }
                   8922:             }
                   8923:         }
                   8924:     }
                   8925:     return %access;
                   8926: }
                   8927: 
                   8928: sub modify_access_controls {
                   8929:     my ($file_name,$changes,$domain,$user)=@_;
                   8930:     my ($outcome,$deloutcome);
                   8931:     my %store_permissions;
                   8932:     my %new_values;
                   8933:     my %new_control;
                   8934:     my %translation;
                   8935:     my @deletions = ();
                   8936:     my $now = time;
                   8937:     if (exists($$changes{'activate'})) {
                   8938:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8939:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8940:             my $numnew = scalar(@newitems);
                   8941:             for (my $i=0; $i<$numnew; $i++) {
                   8942:                 my $newkey = $newitems[$i];
                   8943:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8944:                 if ($newkey =~ /^\d+:/) { 
                   8945:                     $newkey =~ s/^(\d+)/$newid/;
                   8946:                     $translation{$1} = $newid;
                   8947:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8948:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8949:                     $translation{$1} = $newid;
                   8950:                 }
1.749     raeburn  8951:                 $new_values{$file_name."\0".$newkey} = 
                   8952:                                           $$changes{'activate'}{$newitems[$i]};
                   8953:                 $new_control{$newkey} = $now;
                   8954:             }
                   8955:         }
                   8956:     }
                   8957:     my %todelete;
                   8958:     my %changed_items;
                   8959:     foreach my $action ('delete','update') {
                   8960:         if (exists($$changes{$action})) {
                   8961:             if (ref($$changes{$action}) eq 'HASH') {
                   8962:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8963:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8964:                     if ($action eq 'delete') { 
                   8965:                         $todelete{$itemnum} = 1;
                   8966:                     } else {
                   8967:                         $changed_items{$itemnum} = $key;
                   8968:                     }
                   8969:                 }
1.745     raeburn  8970:             }
                   8971:         }
1.749     raeburn  8972:     }
                   8973:     # get lock on access controls for file.
                   8974:     my $lockhash = {
                   8975:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8976:                                                        ':'.$env{'user.domain'},
                   8977:                    }; 
                   8978:     my $tries = 0;
                   8979:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8980:    
                   8981:     while (($gotlock ne 'ok') && $tries <3) {
                   8982:         $tries ++;
                   8983:         sleep 1;
                   8984:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8985:     }
                   8986:     if ($gotlock eq 'ok') {
                   8987:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8988:         my ($tmp)=keys(%curr_permissions);
                   8989:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8990:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8991:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8992:             if (ref($curr_controls) eq 'HASH') {
                   8993:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8994:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8995:                     if (defined($todelete{$itemnum})) {
                   8996:                         push(@deletions,$file_name."\0".$control_item);
                   8997:                     } else {
                   8998:                         if (defined($changed_items{$itemnum})) {
                   8999:                             $new_control{$changed_items{$itemnum}} = $now;
                   9000:                             push(@deletions,$file_name."\0".$control_item);
                   9001:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9002:                         } else {
                   9003:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9004:                         }
                   9005:                     }
1.745     raeburn  9006:                 }
                   9007:             }
                   9008:         }
1.970     raeburn  9009:         my ($group);
                   9010:         if (&is_course($domain,$user)) {
                   9011:             ($group,my $file) = split(/\//,$file_name,2);
                   9012:         }
1.749     raeburn  9013:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9014:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9015:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9016:         #  remove lock
                   9017:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9018:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9019:         my $sqlresult =
1.970     raeburn  9020:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9021:                                     $group);
1.749     raeburn  9022:     } else {
                   9023:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9024:     }
1.749     raeburn  9025:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9026: }
                   9027: 
1.827     raeburn  9028: sub make_public_indefinitely {
                   9029:     my ($requrl) = @_;
                   9030:     my $now = time;
                   9031:     my $action = 'activate';
                   9032:     my $aclnum = 0;
                   9033:     if (&is_portfolio_url($requrl)) {
                   9034:         my (undef,$udom,$unum,$file_name,$group) =
                   9035:             &parse_portfolio_url($requrl);
                   9036:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9037:         my %access_controls = &get_access_controls($current_perms,
                   9038:                                                    $group,$file_name);
                   9039:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9040:             my ($num,$scope,$end,$start) = 
                   9041:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9042:             if ($scope eq 'public') {
                   9043:                 if ($start <= $now && $end == 0) {
                   9044:                     $action = 'none';
                   9045:                 } else {
                   9046:                     $action = 'update';
                   9047:                     $aclnum = $num;
                   9048:                 }
                   9049:                 last;
                   9050:             }
                   9051:         }
                   9052:         if ($action eq 'none') {
                   9053:              return 'ok';
                   9054:         } else {
                   9055:             my %changes;
                   9056:             my $newend = 0;
                   9057:             my $newstart = $now;
                   9058:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9059:             $changes{$action}{$newkey} = {
                   9060:                 type => 'public',
                   9061:                 time => {
                   9062:                     start => $newstart,
                   9063:                     end   => $newend,
                   9064:                 },
                   9065:             };
                   9066:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9067:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9068:             return $outcome;
                   9069:         }
                   9070:     } else {
                   9071:         return 'invalid';
                   9072:     }
                   9073: }
                   9074: 
1.745     raeburn  9075: #------------------------------------------------------Get Marked as Read Only
                   9076: 
                   9077: sub get_marked_as_readonly {
                   9078:     my ($domain,$user,$what,$group) = @_;
                   9079:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9080:     my @readonly_files;
1.629     banghart 9081:     my $cmp1=$what;
                   9082:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9083:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9084:         if (defined($group)) {
                   9085:             if ($file_name !~ m-^\Q$group\E/-) {
                   9086:                 next;
                   9087:             }
                   9088:         }
1.561     banghart 9089:         if (ref($value) eq "ARRAY"){
                   9090:             foreach my $stored_what (@{$value}) {
1.629     banghart 9091:                 my $cmp2=$stored_what;
1.759     albertel 9092:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9093:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9094:                 }
1.629     banghart 9095:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9096:                     push(@readonly_files, $file_name);
1.745     raeburn  9097:                     last;
1.563     banghart 9098:                 } elsif (!defined($what)) {
                   9099:                     push(@readonly_files, $file_name);
1.745     raeburn  9100:                     last;
1.561     banghart 9101:                 }
                   9102:             }
1.745     raeburn  9103:         }
1.561     banghart 9104:     }
                   9105:     return @readonly_files;
                   9106: }
1.577     banghart 9107: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9108: 
1.577     banghart 9109: sub get_marked_as_readonly_hash {
1.745     raeburn  9110:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9111:     my %readonly_files;
1.745     raeburn  9112:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9113:         if (defined($group)) {
                   9114:             if ($file_name !~ m-^\Q$group\E/-) {
                   9115:                 next;
                   9116:             }
                   9117:         }
1.577     banghart 9118:         if (ref($value) eq "ARRAY"){
                   9119:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9120:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9121:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9122:                         if ($lock_descriptor eq 'graded') {
                   9123:                             $readonly_files{$file_name} = 'graded';
                   9124:                         } elsif ($lock_descriptor eq 'handback') {
                   9125:                             $readonly_files{$file_name} = 'handback';
                   9126:                         } else {
                   9127:                             if (!exists($readonly_files{$file_name})) {
                   9128:                                 $readonly_files{$file_name} = 'locked';
                   9129:                             }
                   9130:                         }
1.745     raeburn  9131:                     }
1.750     banghart 9132:                 } 
1.577     banghart 9133:             }
                   9134:         } 
                   9135:     }
                   9136:     return %readonly_files;
                   9137: }
1.559     banghart 9138: # ------------------------------------------------------------ Unmark as Read Only
                   9139: 
                   9140: sub unmark_as_readonly {
1.629     banghart 9141:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9142:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9143:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9144:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9145:     my $symb_crs = $what;
                   9146:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9147:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9148:     my ($tmp)=keys(%current_permissions);
                   9149:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9150:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9151:     foreach my $file (@readonly_files) {
1.759     albertel 9152: 	my $clean_file = &declutter_portfile($file);
                   9153: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9154: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9155:         my @new_locks;
                   9156:         my @del_keys;
                   9157:         if (ref($current_locks) eq "ARRAY"){
                   9158:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9159:                 my $compare=$locker;
1.749     raeburn  9160:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9161:                     $compare=join('',@{$locker});
1.746     raeburn  9162:                     if ($compare ne $symb_crs) {
                   9163:                         push(@new_locks, $locker);
                   9164:                     }
1.563     banghart 9165:                 }
                   9166:             }
1.650     albertel 9167:             if (scalar(@new_locks) > 0) {
1.563     banghart 9168:                 $current_permissions{$file} = \@new_locks;
                   9169:             } else {
                   9170:                 push(@del_keys, $file);
1.613     albertel 9171:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9172:                 delete($current_permissions{$file});
1.563     banghart 9173:             }
                   9174:         }
1.561     banghart 9175:     }
1.613     albertel 9176:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9177:     return;
                   9178: }
1.512     banghart 9179: 
1.17      www      9180: # ------------------------------------------------------------ Directory lister
                   9181: 
                   9182: sub dirlist {
1.955     raeburn  9183:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9184:     $uri=~s/^\///;
                   9185:     $uri=~s/\/$//;
1.253     stredwic 9186:     my ($udom, $uname);
1.955     raeburn  9187:     if ($getuserdir) {
1.253     stredwic 9188:         $udom = $userdomain;
                   9189:         $uname = $username;
1.955     raeburn  9190:     } else {
                   9191:         (undef,$udom,$uname)=split(/\//,$uri);
                   9192:         if(defined($userdomain)) {
                   9193:             $udom = $userdomain;
                   9194:         }
                   9195:         if(defined($username)) {
                   9196:             $uname = $username;
                   9197:         }
1.253     stredwic 9198:     }
1.955     raeburn  9199:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9200: 
1.955     raeburn  9201:     $dirRoot = $perlvar{'lonDocRoot'};
                   9202:     if (defined($getpropath)) {
                   9203:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9204:         $dirRoot =~ s/\/$//;
1.955     raeburn  9205:     } elsif (defined($getuserdir)) {
                   9206:         my $subdir=$uname.'__';
                   9207:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9208:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9209:                    ."/$udom/$subdir/$uname";
                   9210:     } elsif (defined($alternateRoot)) {
                   9211:         $dirRoot = $alternateRoot;
1.751     banghart 9212:     }
1.253     stredwic 9213: 
                   9214:     if($udom) {
                   9215:         if($uname) {
1.1135    raeburn  9216:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9217:             if ($uhome eq 'no_host') {
                   9218:                 return ([],'no_host');
                   9219:             }
1.955     raeburn  9220:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9221:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9222:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9223:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9224:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9225:             } else {
                   9226:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9227:             }
1.605     matthew  9228:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9229:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9230:                 @listing_results = split(/:/,$listing);
                   9231:             } else {
                   9232:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9233:             }
1.1135    raeburn  9234:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9235:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9236:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9237:                 return ([],$listing);
                   9238:             } else {
                   9239:                 return (\@listing_results);
1.1135    raeburn  9240:             }
1.955     raeburn  9241:         } elsif(!$alternateRoot) {
1.1136    raeburn  9242:             my (%allusers,%listerror);
1.841     albertel 9243: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9244:  	    foreach my $tryserver (keys(%servers)) {
                   9245:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9246:                                   &escape($udom),$tryserver);
                   9247:                 if ($listing eq 'unknown_cmd') {
                   9248: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9249: 				      $udom, $tryserver);
                   9250:                 } else {
                   9251:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9252:                 }
1.841     albertel 9253: 		if ($listing eq 'unknown_cmd') {
                   9254: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9255: 				      $udom, $tryserver);
                   9256: 		    @listing_results = split(/:/,$listing);
                   9257: 		} else {
                   9258: 		    @listing_results =
                   9259: 			map { &unescape($_); } split(/:/,$listing);
                   9260: 		}
1.1136    raeburn  9261:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9262:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9263:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9264:                     $listerror{$tryserver} = $listing;
                   9265:                 } else {
1.841     albertel 9266: 		    foreach my $line (@listing_results) {
                   9267: 			my ($entry) = split(/&/,$line,2);
                   9268: 			$allusers{$entry} = 1;
                   9269: 		    }
                   9270: 		}
1.253     stredwic 9271:             }
1.1136    raeburn  9272:             my @alluserslist=();
1.800     albertel 9273:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9274:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9275:             }
1.1136    raeburn  9276:             return (\@alluserslist);
1.253     stredwic 9277:         } else {
1.1136    raeburn  9278:             return ([],'missing username');
1.253     stredwic 9279:         }
1.955     raeburn  9280:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9281:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9282:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9283:         return (\@all_domains);
1.955     raeburn  9284:     } else {
1.1136    raeburn  9285:         return ([],'missing domain');
1.275     stredwic 9286:     }
                   9287: }
                   9288: 
                   9289: # --------------------------------------------- GetFileTimestamp
                   9290: # This function utilizes dirlist and returns the date stamp for
                   9291: # when it was last modified.  It will also return an error of -1
                   9292: # if an error occurs
                   9293: 
                   9294: sub GetFileTimestamp {
1.955     raeburn  9295:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9296:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9297:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9298:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9299:                                     undef,$getuserdir);
                   9300:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9301:         return -1;
                   9302:     }
                   9303:     if (ref($fileref) eq 'ARRAY') {
                   9304:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9305:         # @stats contains first the filename, then the stat output
                   9306:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9307:     } else {
                   9308:         return -1;
1.253     stredwic 9309:     }
1.26      www      9310: }
                   9311: 
1.712     albertel 9312: sub stat_file {
                   9313:     my ($uri) = @_;
1.787     albertel 9314:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9315: 
1.955     raeburn  9316:     my ($udom,$uname,$file);
1.712     albertel 9317:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9318: 	($udom,$uname,$file) =
1.811     albertel 9319: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9320: 	$file = 'userfiles/'.$file;
                   9321:     }
                   9322:     if ($uri =~ m-^/res/-) {
                   9323: 	($udom,$uname) = 
1.807     albertel 9324: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9325: 	$file = $uri;
                   9326:     }
                   9327: 
                   9328:     if (!$udom || !$uname || !$file) {
                   9329: 	# unable to handle the uri
                   9330: 	return ();
                   9331:     }
1.956     raeburn  9332:     my $getpropath;
                   9333:     if ($file =~ /^userfiles\//) {
                   9334:         $getpropath = 1;
                   9335:     }
1.1136    raeburn  9336:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9337:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9338:         return ();
                   9339:     } else {
                   9340:         if (ref($listref) eq 'ARRAY') {
                   9341:             my @stats = split('&',$listref->[0]);
                   9342: 	    shift(@stats); #filename is first
                   9343: 	    return @stats;
                   9344:         }
1.712     albertel 9345:     }
                   9346:     return ();
                   9347: }
                   9348: 
1.26      www      9349: # -------------------------------------------------------- Value of a Condition
                   9350: 
1.713     albertel 9351: # gets the value of a specific preevaluated condition
                   9352: #    stored in the string  $env{user.state.<cid>}
                   9353: # or looks up a condition reference in the bighash and if if hasn't
                   9354: # already been evaluated recurses into docondval to get the value of
                   9355: # the condition, then memoizing it to 
                   9356: #   $env{user.state.<cid>.<condition>}
1.40      www      9357: sub directcondval {
                   9358:     my $number=shift;
1.620     albertel 9359:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9360: 	&Apache::lonuserstate::evalstate();
                   9361:     }
1.713     albertel 9362:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9363: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9364:     } elsif ($number =~ /^_/) {
                   9365: 	my $sub_condition;
                   9366: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9367: 		&GDBM_READER(),0640)) {
                   9368: 	    $sub_condition=$bighash{'conditions'.$number};
                   9369: 	    untie(%bighash);
                   9370: 	}
                   9371: 	my $value = &docondval($sub_condition);
1.949     raeburn  9372: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9373: 	return $value;
                   9374:     }
1.620     albertel 9375:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9376:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9377:     } else {
                   9378:        return 2;
                   9379:     }
                   9380: }
                   9381: 
1.713     albertel 9382: # get the collection of conditions for this resource
1.26      www      9383: sub condval {
                   9384:     my $condidx=shift;
1.54      www      9385:     my $allpathcond='';
1.713     albertel 9386:     foreach my $cond (split(/\|/,$condidx)) {
                   9387: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9388: 	    $allpathcond.=
                   9389: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9390: 	}
1.191     harris41 9391:     }
1.54      www      9392:     $allpathcond=~s/\|$//;
1.713     albertel 9393:     return &docondval($allpathcond);
                   9394: }
                   9395: 
                   9396: #evaluates an expression of conditions
                   9397: sub docondval {
                   9398:     my ($allpathcond) = @_;
                   9399:     my $result=0;
                   9400:     if ($env{'request.course.id'}
                   9401: 	&& defined($allpathcond)) {
                   9402: 	my $operand='|';
                   9403: 	my @stack;
                   9404: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9405: 	    if ($chunk eq '(') {
                   9406: 		push @stack,($operand,$result);
                   9407: 	    } elsif ($chunk eq ')') {
                   9408: 		my $before=pop @stack;
                   9409: 		if (pop @stack eq '&') {
                   9410: 		    $result=$result>$before?$before:$result;
                   9411: 		} else {
                   9412: 		    $result=$result>$before?$result:$before;
                   9413: 		}
                   9414: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9415: 		$operand=$chunk;
                   9416: 	    } else {
                   9417: 		my $new=directcondval($chunk);
                   9418: 		if ($operand eq '&') {
                   9419: 		    $result=$result>$new?$new:$result;
                   9420: 		} else {
                   9421: 		    $result=$result>$new?$result:$new;
                   9422: 		}
                   9423: 	    }
                   9424: 	}
1.26      www      9425:     }
                   9426:     return $result;
1.421     albertel 9427: }
                   9428: 
                   9429: # ---------------------------------------------------- Devalidate courseresdata
                   9430: 
                   9431: sub devalidatecourseresdata {
                   9432:     my ($coursenum,$coursedomain)=@_;
                   9433:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9434:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9435: }
                   9436: 
1.763     www      9437: 
1.200     www      9438: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9439: #
                   9440: #  Parameters:
                   9441: #      $coursenum    - Number of the course.
                   9442: #      $coursedomain - Domain at which the course was created.
                   9443: #  Returns:
                   9444: #     A hash of the course parameters along (I think) with timestamps
                   9445: #     and version info.
1.877     foxr     9446: 
1.624     albertel 9447: sub get_courseresdata {
                   9448:     my ($coursenum,$coursedomain)=@_;
1.200     www      9449:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9450:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9451:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9452:     my %dumpreply;
1.417     albertel 9453:     unless (defined($cached)) {
1.624     albertel 9454: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9455: 	$result=\%dumpreply;
1.251     albertel 9456: 	my ($tmp) = keys(%dumpreply);
                   9457: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9458: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9459: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9460: 	    return $tmp;
1.416     albertel 9461: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9462: 	    $result=undef;
1.599     albertel 9463: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9464: 	}
                   9465:     }
1.624     albertel 9466:     return $result;
                   9467: }
                   9468: 
1.633     albertel 9469: sub devalidateuserresdata {
                   9470:     my ($uname,$udom)=@_;
                   9471:     my $hashid="$udom:$uname";
                   9472:     &devalidate_cache_new('userres',$hashid);
                   9473: }
                   9474: 
1.624     albertel 9475: sub get_userresdata {
                   9476:     my ($uname,$udom)=@_;
                   9477:     #most student don\'t have any data set, check if there is some data
                   9478:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9479: 
                   9480:     my $hashid="$udom:$uname";
                   9481:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9482:     if (!defined($cached)) {
                   9483: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9484: 	$result=\%resourcedata;
                   9485: 	&do_cache_new('userres',$hashid,$result,600);
                   9486:     }
                   9487:     my ($tmp)=keys(%$result);
                   9488:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9489: 	return $result;
                   9490:     }
                   9491:     #error 2 occurs when the .db doesn't exist
                   9492:     if ($tmp!~/error: 2 /) {
1.672     albertel 9493: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9494: 		 " Trying to get resource data for ".
                   9495: 		 $uname." at ".$udom.": ".
                   9496: 		 $tmp."</font>");
                   9497:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9498: 	#&EXT_cache_set($udom,$uname);
                   9499: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9500: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9501:     }
                   9502:     return $tmp;
                   9503: }
1.879     foxr     9504: #----------------------------------------------- resdata - return resource data
                   9505: #  Purpose:
                   9506: #    Return resource data for either users or for a course.
                   9507: #  Parameters:
                   9508: #     $name      - Course/user name.
                   9509: #     $domain    - Name of the domain the user/course is registered on.
                   9510: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9511: #     @which     - Array of names of resources desired.
                   9512: #  Returns:
                   9513: #     The value of the first reasource in @which that is found in the
                   9514: #     resource hash.
                   9515: #  Exceptional Conditions:
                   9516: #     If the $type passed in is not valid (not the string 'course' or 
                   9517: #     'user', an undefined  reference is returned.
                   9518: #     If none of the resources are found, an undef is returned
1.624     albertel 9519: sub resdata {
                   9520:     my ($name,$domain,$type,@which)=@_;
                   9521:     my $result;
                   9522:     if ($type eq 'course') {
                   9523: 	$result=&get_courseresdata($name,$domain);
                   9524:     } elsif ($type eq 'user') {
                   9525: 	$result=&get_userresdata($name,$domain);
                   9526:     }
                   9527:     if (!ref($result)) { return $result; }    
1.251     albertel 9528:     foreach my $item (@which) {
1.927     albertel 9529: 	if (defined($result->{$item->[0]})) {
                   9530: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9531: 	}
1.250     albertel 9532:     }
1.291     albertel 9533:     return undef;
1.200     www      9534: }
                   9535: 
1.379     matthew  9536: #
                   9537: # EXT resource caching routines
                   9538: #
                   9539: 
                   9540: sub clear_EXT_cache_status {
1.383     albertel 9541:     &delenv('cache.EXT.');
1.379     matthew  9542: }
                   9543: 
                   9544: sub EXT_cache_status {
                   9545:     my ($target_domain,$target_user) = @_;
1.383     albertel 9546:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9547:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9548:         # We know already the user has no data
                   9549:         return 1;
                   9550:     } else {
                   9551:         return 0;
                   9552:     }
                   9553: }
                   9554: 
                   9555: sub EXT_cache_set {
                   9556:     my ($target_domain,$target_user) = @_;
1.383     albertel 9557:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9558:     #&appenv({$cachename => time});
1.379     matthew  9559: }
                   9560: 
1.28      www      9561: # --------------------------------------------------------- Value of a Variable
1.58      www      9562: sub EXT {
1.715     albertel 9563: 
1.395     albertel 9564:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9565:     unless ($varname) { return ''; }
1.218     albertel 9566:     #get real user name/domain, courseid and symb
                   9567:     my $courseid;
1.359     albertel 9568:     my $publicuser;
1.427     www      9569:     if ($symbparm) {
                   9570: 	$symbparm=&get_symb_from_alias($symbparm);
                   9571:     }
1.218     albertel 9572:     if (!($uname && $udom)) {
1.790     albertel 9573:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9574:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9575:     } else {
1.620     albertel 9576: 	$courseid=$env{'request.course.id'};
1.218     albertel 9577:     }
1.48      www      9578:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9579:     my $rest;
1.320     albertel 9580:     if (defined($therest[0])) {
1.48      www      9581:        $rest=join('.',@therest);
                   9582:     } else {
                   9583:        $rest='';
                   9584:     }
1.320     albertel 9585: 
1.57      www      9586:     my $qualifierrest=$qualifier;
                   9587:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9588:     my $spacequalifierrest=$space;
                   9589:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9590:     if ($realm eq 'user') {
1.48      www      9591: # --------------------------------------------------------------- user.resource
                   9592: 	if ($space eq 'resource') {
1.651     albertel 9593: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9594: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9595: 		 &&
1.744     albertel 9596: 		 ($symbparm eq &symbread()) ) {	
                   9597: 		# if we are in the middle of processing the resource the
                   9598: 		# get the value we are planning on committing
                   9599:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9600:                     return $Apache::lonhomework::results{$qualifierrest};
                   9601:                 } else {
                   9602:                     return $Apache::lonhomework::history{$qualifierrest};
                   9603:                 }
1.335     albertel 9604: 	    } else {
1.359     albertel 9605: 		my %restored;
1.620     albertel 9606: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9607: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9608: 		} else {
                   9609: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9610: 		}
1.335     albertel 9611: 		return $restored{$qualifierrest};
                   9612: 	    }
1.48      www      9613: # ----------------------------------------------------------------- user.access
                   9614:         } elsif ($space eq 'access') {
1.218     albertel 9615: 	    # FIXME - not supporting calls for a specific user
1.48      www      9616:             return &allowed($qualifier,$rest);
                   9617: # ------------------------------------------ user.preferences, user.environment
                   9618:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9619: 	    if (($uname eq $env{'user.name'}) &&
                   9620: 		($udom eq $env{'user.domain'})) {
                   9621: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9622: 	    } else {
1.359     albertel 9623: 		my %returnhash;
                   9624: 		if (!$publicuser) {
                   9625: 		    %returnhash=&userenvironment($udom,$uname,
                   9626: 						 $qualifierrest);
                   9627: 		}
1.218     albertel 9628: 		return $returnhash{$qualifierrest};
                   9629: 	    }
1.48      www      9630: # ----------------------------------------------------------------- user.course
                   9631:         } elsif ($space eq 'course') {
1.218     albertel 9632: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9633:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9634: # ------------------------------------------------------------------- user.role
                   9635:         } elsif ($space eq 'role') {
1.218     albertel 9636: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9637:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9638:             if ($qualifier eq 'value') {
                   9639: 		return $role;
                   9640:             } elsif ($qualifier eq 'extent') {
                   9641:                 return $where;
                   9642:             }
                   9643: # ----------------------------------------------------------------- user.domain
                   9644:         } elsif ($space eq 'domain') {
1.218     albertel 9645:             return $udom;
1.48      www      9646: # ------------------------------------------------------------------- user.name
                   9647:         } elsif ($space eq 'name') {
1.218     albertel 9648:             return $uname;
1.48      www      9649: # ---------------------------------------------------- Any other user namespace
1.29      www      9650:         } else {
1.359     albertel 9651: 	    my %reply;
                   9652: 	    if (!$publicuser) {
                   9653: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9654: 	    }
                   9655: 	    return $reply{$qualifierrest};
1.48      www      9656:         }
1.236     www      9657:     } elsif ($realm eq 'query') {
                   9658: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9659:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9660: 						[$spacequalifierrest]);
1.620     albertel 9661: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9662:    } elsif ($realm eq 'request') {
1.48      www      9663: # ------------------------------------------------------------- request.browser
                   9664:         if ($space eq 'browser') {
1.1145    bisitz   9665:             return $env{'browser.'.$qualifier};
1.57      www      9666: # ------------------------------------------------------------ request.filename
                   9667:         } else {
1.620     albertel 9668:             return $env{'request.'.$spacequalifierrest};
1.29      www      9669:         }
1.28      www      9670:     } elsif ($realm eq 'course') {
1.48      www      9671: # ---------------------------------------------------------- course.description
1.620     albertel 9672:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9673:     } elsif ($realm eq 'resource') {
1.165     www      9674: 
1.620     albertel 9675: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9676: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9677: 	}
1.693     albertel 9678: 
                   9679: 	if ($space eq 'title') {
                   9680: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9681: 	    return &gettitle($symbparm);
                   9682: 	}
                   9683: 	
                   9684: 	if ($space eq 'map') {
                   9685: 	    my ($map) = &decode_symb($symbparm);
                   9686: 	    return &symbread($map);
                   9687: 	}
1.905     albertel 9688: 	if ($space eq 'filename') {
                   9689: 	    if ($symbparm) {
                   9690: 		return &clutter((&decode_symb($symbparm))[2]);
                   9691: 	    }
                   9692: 	    return &hreflocation('',$env{'request.filename'});
                   9693: 	}
1.693     albertel 9694: 
                   9695: 	my ($section, $group, @groups);
1.593     albertel 9696: 	my ($courselevelm,$courselevel);
1.539     albertel 9697: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9698: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9699: 
1.218     albertel 9700: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9701: 
1.60      www      9702: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9703: 	    my $symbp=$symbparm;
1.735     albertel 9704: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9705: 
                   9706: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9707: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9708: 
1.620     albertel 9709: 	    if (($env{'user.name'} eq $uname) &&
                   9710: 		($env{'user.domain'} eq $udom)) {
                   9711: 		$section=$env{'request.course.sec'};
1.733     raeburn  9712:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9713:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9714: 	    } else {
1.539     albertel 9715: 		if (! defined($usection)) {
1.551     albertel 9716: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9717: 		} else {
                   9718: 		    $section = $usection;
                   9719: 		}
1.733     raeburn  9720:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9721: 	    }
                   9722: 
                   9723: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9724: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9725: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9726: 
1.593     albertel 9727: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9728: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9729: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9730: 
1.60      www      9731: # ----------------------------------------------------------- first, check user
1.624     albertel 9732: 
                   9733: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9734: 				       ([$courselevelr,'resource'],
                   9735: 					[$courselevelm,'map'     ],
                   9736: 					[$courselevel, 'course'  ]));
1.931     albertel 9737: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9738: 
1.594     albertel 9739: # ------------------------------------------------ second, check some of course
1.684     raeburn  9740:             my $coursereply;
1.691     raeburn  9741:             if (@groups > 0) {
                   9742:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9743:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9744:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9745:             }
1.96      www      9746: 
1.684     raeburn  9747: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9748: 				  $env{'course.'.$courseid.'.domain'},
                   9749: 				  'course',
                   9750: 				  ([$seclevelr,   'resource'],
                   9751: 				   [$seclevelm,   'map'     ],
                   9752: 				   [$seclevel,    'course'  ],
                   9753: 				   [$courselevelr,'resource']));
                   9754: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9755: 
1.60      www      9756: # ------------------------------------------------------ third, check map parms
1.218     albertel 9757: 	    my %parmhash=();
                   9758: 	    my $thisparm='';
                   9759: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9760: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9761: 		    &GDBM_READER(),0640)) {
1.218     albertel 9762: 		$thisparm=$parmhash{$symbparm};
                   9763: 		untie(%parmhash);
                   9764: 	    }
1.927     albertel 9765: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9766: 	}
1.594     albertel 9767: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9768: 
1.218     albertel 9769: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9770: 	my $filename;
                   9771: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9772: 	if ($symbparm) {
1.409     www      9773: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9774: 	} else {
1.620     albertel 9775: 	    $filename=$env{'request.filename'};
1.282     albertel 9776: 	}
                   9777: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9778: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9779: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9780: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9781: 
1.927     albertel 9782: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9783: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9784: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9785: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9786: 				     $env{'course.'.$courseid.'.domain'},
                   9787: 				     'course',
1.927     albertel 9788: 				     ([$courselevelm,'map'   ],
                   9789: 				      [$courselevel, 'course']));
                   9790: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9791: 	}
1.145     www      9792: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9793: 	unless ($space eq '0') {
1.336     albertel 9794: 	    my @parts=split(/_/,$space);
                   9795: 	    my $id=pop(@parts);
                   9796: 	    my $part=join('_',@parts);
                   9797: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9798: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9799: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9800: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9801: 	}
1.395     albertel 9802: 	if ($recurse) { return undef; }
                   9803: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9804: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9805: # ---------------------------------------------------- Any other user namespace
                   9806:     } elsif ($realm eq 'environment') {
                   9807: # ----------------------------------------------------------------- environment
1.620     albertel 9808: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9809: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9810: 	} else {
1.770     albertel 9811: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9812: 		return '';
                   9813: 	    }
1.219     albertel 9814: 	    my %returnhash=&userenvironment($udom,$uname,
                   9815: 					    $spacequalifierrest);
                   9816: 	    return $returnhash{$spacequalifierrest};
                   9817: 	}
1.28      www      9818:     } elsif ($realm eq 'system') {
1.48      www      9819: # ----------------------------------------------------------------- system.time
                   9820: 	if ($space eq 'time') {
                   9821: 	    return time;
                   9822:         }
1.696     albertel 9823:     } elsif ($realm eq 'server') {
                   9824: # ----------------------------------------------------------------- system.time
                   9825: 	if ($space eq 'name') {
                   9826: 	    return $ENV{'SERVER_NAME'};
                   9827:         }
1.28      www      9828:     }
1.48      www      9829:     return '';
1.61      www      9830: }
                   9831: 
1.927     albertel 9832: sub get_reply {
                   9833:     my ($reply_value) = @_;
1.940     raeburn  9834:     if (ref($reply_value) eq 'ARRAY') {
                   9835:         if (wantarray) {
                   9836: 	    return @$reply_value;
                   9837:         }
                   9838:         return $reply_value->[0];
                   9839:     } else {
                   9840:         return $reply_value;
1.927     albertel 9841:     }
                   9842: }
                   9843: 
1.691     raeburn  9844: sub check_group_parms {
                   9845:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9846:     my @groupitems = ();
                   9847:     my $resultitem;
1.927     albertel 9848:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9849:     foreach my $group (@{$groups}) {
                   9850:         foreach my $level (@levels) {
1.927     albertel 9851:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9852:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9853:         }
                   9854:     }
                   9855:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9856:                             $env{'course.'.$courseid.'.domain'},
                   9857:                                      'course',@groupitems);
                   9858:     return $coursereply;
                   9859: }
                   9860: 
                   9861: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9862:     my ($courseid,@groups) = @_;
                   9863:     @groups = sort(@groups);
1.691     raeburn  9864:     return @groups;
                   9865: }
                   9866: 
1.395     albertel 9867: sub packages_tab_default {
                   9868:     my ($uri,$varname)=@_;
                   9869:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9870: 
                   9871:     my (@extension,@specifics,$do_default);
                   9872:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9873: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9874: 	if ($pack_type eq 'default') {
                   9875: 	    $do_default=1;
                   9876: 	} elsif ($pack_type eq 'extension') {
                   9877: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9878: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9879: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9880: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9881: 	}
                   9882:     }
                   9883:     # first look for a package that matches the requested part id
                   9884:     foreach my $package (@specifics) {
                   9885: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9886: 	next if ($pack_part ne $part);
                   9887: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9888: 	    return $packagetab{"$pack_type&$name&default"};
                   9889: 	}
                   9890:     }
                   9891:     # look for any possible matching non extension_ package
                   9892:     foreach my $package (@specifics) {
                   9893: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9894: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9895: 	    return $packagetab{"$pack_type&$name&default"};
                   9896: 	}
1.585     albertel 9897: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9898: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9899: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9900: 	}
                   9901:     }
1.738     albertel 9902:     # look for any posible extension_ match
                   9903:     foreach my $package (@extension) {
                   9904: 	my ($package,$pack_type)=@{$package};
                   9905: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9906: 	    return $packagetab{"$pack_type&$name&default"};
                   9907: 	}
                   9908: 	if (defined($packagetab{$package."&$name&default"})) {
                   9909: 	    return $packagetab{$package."&$name&default"};
                   9910: 	}
                   9911:     }
                   9912:     # look for a global default setting
                   9913:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9914: 	return $packagetab{"default&$name&default"};
                   9915:     }
1.395     albertel 9916:     return undef;
                   9917: }
                   9918: 
1.334     albertel 9919: sub add_prefix_and_part {
                   9920:     my ($prefix,$part)=@_;
                   9921:     my $keyroot;
                   9922:     if (defined($prefix) && $prefix !~ /^__/) {
                   9923: 	# prefix that has a part already
                   9924: 	$keyroot=$prefix;
                   9925:     } elsif (defined($prefix)) {
                   9926: 	# prefix that is missing a part
                   9927: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9928:     } else {
                   9929: 	# no prefix at all
                   9930: 	if (defined($part)) { $keyroot='_'.$part; }
                   9931:     }
                   9932:     return $keyroot;
                   9933: }
                   9934: 
1.71      www      9935: # ---------------------------------------------------------------- Get metadata
                   9936: 
1.599     albertel 9937: my %metaentry;
1.1070    www      9938: my %importedpartids;
1.71      www      9939: sub metadata {
1.176     www      9940:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9941:     $uri=&declutter($uri);
1.288     albertel 9942:     # if it is a non metadata possible uri return quickly
1.529     albertel 9943:     if (($uri eq '') || 
                   9944: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  9945: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  9946:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9947: 	return undef;
                   9948:     }
1.1140    www      9949:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9950: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9951: 	return undef;
1.288     albertel 9952:     }
1.73      www      9953:     my $filename=$uri;
                   9954:     $uri=~s/\.meta$//;
1.172     www      9955: #
                   9956: # Is the metadata already cached?
1.177     www      9957: # Look at timestamp of caching
1.172     www      9958: # Everything is cached by the main uri, libraries are never directly cached
                   9959: #
1.428     albertel 9960:     if (!defined($liburi)) {
1.599     albertel 9961: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9962: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9963:     }
                   9964:     {
1.1069    www      9965: # Imported parts would go here
1.1070    www      9966:         my %importedids=();
                   9967:         my @origfileimportpartids=();
1.1069    www      9968:         my $importedparts=0;
1.172     www      9969: #
                   9970: # Is this a recursive call for a library?
                   9971: #
1.599     albertel 9972: #	if (! exists($metacache{$uri})) {
                   9973: #	    $metacache{$uri}={};
                   9974: #	}
1.924     albertel 9975: 	my $cachetime = 60*60;
1.171     www      9976:         if ($liburi) {
                   9977: 	    $liburi=&declutter($liburi);
                   9978:             $filename=$liburi;
1.401     bowersj2 9979:         } else {
1.599     albertel 9980: 	    &devalidate_cache_new('meta',$uri);
                   9981: 	    undef(%metaentry);
1.401     bowersj2 9982: 	}
1.140     www      9983:         my %metathesekeys=();
1.73      www      9984:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9985: 	my $metastring;
1.1140    www      9986: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9987: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9988: 	    $metastring = 
1.929     albertel 9989: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9990: 					  ('grade_target' => 'meta'));
                   9991: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9992: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9993:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9994: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9995: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9996: 	    $metastring=&getfile($file);
1.489     albertel 9997: 	}
1.208     albertel 9998:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9999:         my $token;
1.140     www      10000:         undef %metathesekeys;
1.71      www      10001:         while ($token=$parser->get_token) {
1.339     albertel 10002: 	    if ($token->[0] eq 'S') {
                   10003: 		if (defined($token->[2]->{'package'})) {
1.172     www      10004: #
                   10005: # This is a package - get package info
                   10006: #
1.339     albertel 10007: 		    my $package=$token->[2]->{'package'};
                   10008: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10009: 		    if (defined($token->[2]->{'id'})) { 
                   10010: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10011: 		    }
1.599     albertel 10012: 		    if ($metaentry{':packages'}) {
                   10013: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10014: 		    } else {
1.599     albertel 10015: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10016: 		    }
1.736     albertel 10017: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10018: 			my $part=$keyroot;
                   10019: 			$part=~s/^\_//;
1.736     albertel 10020: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10021: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10022: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10023: 			    # ignore package.tab specified default values
                   10024:                             # here &package_tab_default() will fetch those
                   10025: 			    if ($subp eq 'default') { next; }
1.736     albertel 10026: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10027: 			    my $unikey;
                   10028: 			    if ($pack =~ /_0$/) {
                   10029: 				$unikey='parameter_0_'.$name;
                   10030: 				$part=0;
                   10031: 			    } else {
                   10032: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10033: 			    }
1.339     albertel 10034: 			    if ($subp eq 'display') {
                   10035: 				$value.=' [Part: '.$part.']';
                   10036: 			    }
1.599     albertel 10037: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10038: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10039: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10040: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10041: 			    }
1.599     albertel 10042: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10043: 				$metaentry{':'.$unikey}=
                   10044: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10045: 			    }
1.339     albertel 10046: 			}
                   10047: 		    }
                   10048: 		} else {
1.172     www      10049: #
                   10050: # This is not a package - some other kind of start tag
1.339     albertel 10051: #
                   10052: 		    my $entry=$token->[1];
1.1068    www      10053: 		    my $unikey='';
1.175     www      10054: 
1.339     albertel 10055: 		    if ($entry eq 'import') {
1.175     www      10056: #
                   10057: # Importing a library here
1.339     albertel 10058: #
1.1067    www      10059:                         my $location=$parser->get_text('/import');
                   10060:                         my $dir=$filename;
                   10061:                         $dir=~s|[^/]*$||;
                   10062:                         $location=&filelocation($dir,$location);
1.1069    www      10063:                        
1.1068    www      10064:                         my $importmode=$token->[2]->{'importmode'};
                   10065:                         if ($importmode eq 'problem') {
1.1069    www      10066: # Import as problem/response
1.1068    www      10067:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10068:                         } elsif ($importmode eq 'part') {
                   10069: # Import as part(s)
1.1069    www      10070:                            $importedparts=1;
                   10071: # We need to get the original file and the imported file to get the part order correct
                   10072: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10073: # Load and inspect original file
1.1070    www      10074:                            if ($#origfileimportpartids<0) {
                   10075:                               undef(%importedpartids);
                   10076:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10077:                               my $origfile=&getfile($origfilelocation);
                   10078:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10079:                            }
                   10080: 
1.1069    www      10081: # Load and inspect imported file
                   10082:                            my $impfile=&getfile($location);
                   10083:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10084:                            if ($#impfilepartids>=0) {
                   10085: # This problem had parts
1.1070    www      10086:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10087:                            } else {
                   10088: # Importing by turning a single problem into a problem part
                   10089: # It gets the import-tags ID as part-ID
                   10090:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10091:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10092:                            }
1.1068    www      10093:                         } else {
                   10094: # Normal import
                   10095:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10096:                            if (defined($token->[2]->{'id'})) {
                   10097:                               $unikey.='_'.$token->[2]->{'id'};
                   10098:                            }
1.1067    www      10099:                         }
                   10100: 
1.339     albertel 10101: 			if ($depthcount<20) {
1.736     albertel 10102: 			    my $metadata = 
                   10103: 				&metadata($uri,'keys', $location,$unikey,
                   10104: 					  $depthcount+1);
                   10105: 			    foreach my $meta (split(',',$metadata)) {
                   10106: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10107: 				$metathesekeys{$meta}=1;
1.339     albertel 10108: 			    }
1.1068    www      10109: 			
                   10110:                         }
1.1067    www      10111: 		    } else {
                   10112: #
                   10113: # Not importing, some other kind of non-package, non-library start tag
                   10114: # 
                   10115:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10116:                         if (defined($token->[2]->{'id'})) {
                   10117:                             $unikey.='_'.$token->[2]->{'id'};
                   10118:                         }
1.339     albertel 10119: 			if (defined($token->[2]->{'name'})) { 
                   10120: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10121: 			}
                   10122: 			$metathesekeys{$unikey}=1;
1.736     albertel 10123: 			foreach my $param (@{$token->[3]}) {
                   10124: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10125: 				$token->[2]->{$param};
1.339     albertel 10126: 			}
                   10127: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10128: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10129: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10130: 		 # only ws inside the tag, and not in default, so use default
                   10131: 		 # as value
1.599     albertel 10132: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10133: 			} elsif ( $internaltext =~ /\S/ ) {
                   10134: 		  # something interesting inside the tag
                   10135: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10136: 			} else {
1.908     albertel 10137: 		  # no interesting values, don't set a default
1.339     albertel 10138: 			}
1.172     www      10139: # end of not-a-package not-a-library import
1.339     albertel 10140: 		    }
1.172     www      10141: # end of not-a-package start tag
1.339     albertel 10142: 		}
1.172     www      10143: # the next is the end of "start tag"
1.339     albertel 10144: 	    }
                   10145: 	}
1.483     albertel 10146: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10147: 	$extension = lc($extension);
                   10148: 	if ($extension eq 'htm') { $extension='html'; }
                   10149: 
1.737     albertel 10150: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10151: 	    #no specific packages #how's our extension
                   10152: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10153: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10154: 					 \%metathesekeys);
                   10155: 	}
1.883     albertel 10156: 
                   10157: 	if (!exists($metaentry{':packages'})
                   10158: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10159: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10160: 		#no specific packages well let's get default then
                   10161: 		if ($key!~/^default&/) { next; }
1.488     albertel 10162: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10163: 					     \%metathesekeys);
                   10164: 	    }
                   10165: 	}
1.338     www      10166: # are there custom rights to evaluate
1.599     albertel 10167: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10168: 
1.338     www      10169:     #
                   10170:     # Importing a rights file here
1.339     albertel 10171:     #
                   10172: 	    unless ($depthcount) {
1.599     albertel 10173: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10174: 		my $dir=$filename;
                   10175: 		$dir=~s|[^/]*$||;
                   10176: 		$location=&filelocation($dir,$location);
1.736     albertel 10177: 		my $rights_metadata =
                   10178: 		    &metadata($uri,'keys',$location,'_rights',
                   10179: 			      $depthcount+1);
                   10180: 		foreach my $rights (split(',',$rights_metadata)) {
                   10181: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10182: 		    $metathesekeys{$rights}=1;
1.339     albertel 10183: 		}
                   10184: 	    }
                   10185: 	}
1.737     albertel 10186: 	# uniqifiy package listing
                   10187: 	my %seen;
                   10188: 	my @uniq_packages =
                   10189: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10190: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10191: 
1.1070    www      10192:         if ($importedparts) {
                   10193: # We had imported parts and need to rebuild partorder
                   10194:            $metaentry{':partorder'}='';
                   10195:            $metathesekeys{'partorder'}=1;
                   10196:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10197:                if ($origfileimportpartids[$index] eq 'part') {
                   10198: # original part, part of the problem
                   10199:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10200:                } else {
                   10201: # we have imported parts at this position
                   10202:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10203:                }
                   10204:            }
                   10205:            $metaentry{':partorder'}=~s/^\,//;
                   10206:         }
                   10207: 
1.737     albertel 10208: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10209: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10210: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10211: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10212: # this is the end of "was not already recently cached
1.71      www      10213:     }
1.599     albertel 10214:     return $metaentry{':'.$what};
1.261     albertel 10215: }
                   10216: 
1.488     albertel 10217: sub metadata_create_package_def {
1.483     albertel 10218:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10219:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10220:     if ($subp eq 'default') { next; }
                   10221:     
1.599     albertel 10222:     if (defined($metaentry{':packages'})) {
                   10223: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10224:     } else {
1.599     albertel 10225: 	$metaentry{':packages'}=$package;
1.483     albertel 10226:     }
                   10227:     my $value=$packagetab{$key};
                   10228:     my $unikey;
                   10229:     $unikey='parameter_0_'.$name;
1.599     albertel 10230:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10231:     $$metathesekeys{$unikey}=1;
1.599     albertel 10232:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10233: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10234:     }
1.599     albertel 10235:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10236: 	$metaentry{':'.$unikey}=
                   10237: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10238:     }
                   10239: }
                   10240: 
1.261     albertel 10241: sub metadata_generate_part0 {
                   10242:     my ($metadata,$metacache,$uri) = @_;
                   10243:     my %allnames;
1.737     albertel 10244:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10245: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10246: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10247: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10248: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10249: 	    $allnames{$name}=$part;
                   10250: 	  }
                   10251: 	}
                   10252:     }
                   10253:     foreach my $name (keys(%allnames)) {
                   10254:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10255:       my $key=":parameter_0_$name";
1.261     albertel 10256:       $$metacache{"$key.part"}='0';
                   10257:       $$metacache{"$key.name"}=$name;
1.428     albertel 10258:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10259: 					   $allnames{$name}.'_'.$name.
                   10260: 					   '.type'};
1.428     albertel 10261:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10262: 			     '.display'};
1.644     www      10263:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10264:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10265:       $$metacache{"$key.display"}=$olddis;
                   10266:     }
1.71      www      10267: }
                   10268: 
1.764     albertel 10269: # ------------------------------------------------------ Devalidate title cache
                   10270: 
                   10271: sub devalidate_title_cache {
                   10272:     my ($url)=@_;
                   10273:     if (!$env{'request.course.id'}) { return; }
                   10274:     my $symb=&symbread($url);
                   10275:     if (!$symb) { return; }
                   10276:     my $key=$env{'request.course.id'}."\0".$symb;
                   10277:     &devalidate_cache_new('title',$key);
                   10278: }
                   10279: 
1.1014    droeschl 10280: # ------------------------------------------------- Get the title of a course
                   10281: 
                   10282: sub current_course_title {
                   10283:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10284: }
1.301     www      10285: # ------------------------------------------------- Get the title of a resource
                   10286: 
                   10287: sub gettitle {
                   10288:     my $urlsymb=shift;
                   10289:     my $symb=&symbread($urlsymb);
1.534     albertel 10290:     if ($symb) {
1.620     albertel 10291: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10292: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10293: 	if (defined($cached)) { 
                   10294: 	    return $result;
                   10295: 	}
1.534     albertel 10296: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10297: 	my $title='';
1.907     albertel 10298: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10299: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10300: 	} else {
                   10301: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10302: 		    &GDBM_READER(),0640)) {
                   10303: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10304: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10305: 		untie(%bighash);
                   10306: 	    }
1.534     albertel 10307: 	}
                   10308: 	$title=~s/\&colon\;/\:/gs;
                   10309: 	if ($title) {
1.1159    www      10310: # Remember both $symb and $title for dynamic metadata
                   10311:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10312:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10313: # Cache this title and then return it
1.599     albertel 10314: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10315: 	}
                   10316: 	$urlsymb=$url;
                   10317:     }
                   10318:     my $title=&metadata($urlsymb,'title');
                   10319:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10320:     return $title;
1.301     www      10321: }
1.613     albertel 10322: 
1.1199    raeburn  10323: sub getdocspath {
                   10324:     my ($symb) = @_;
                   10325:     my $path;
                   10326:     if ($symb) {
                   10327:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10328:         if ($resurl=~/\.(sequence|page)$/) {
                   10329:             $mapurl=$resurl;
                   10330:         } elsif ($resurl eq 'adm/navmaps') {
                   10331:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10332:         }
                   10333:         my $mapresobj;
                   10334:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10335:         if (ref($navmap)) {
                   10336:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10337:         }
                   10338:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10339:         my $type=$2;
                   10340:         if (ref($mapresobj)) {
                   10341:             my $pcslist = $mapresobj->map_hierarchy();
                   10342:             if ($pcslist ne '') {
                   10343:                 foreach my $pc (split(/,/,$pcslist)) {
                   10344:                     next if ($pc <= 1);
                   10345:                     my $res = $navmap->getByMapPc($pc);
                   10346:                     if (ref($res)) {
                   10347:                         my $thisurl = $res->src();
                   10348:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10349:                         my $thistitle = $res->title();
                   10350:                         $path .= '&'.
                   10351:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10352:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10353:                                  ':'.$res->randompick().
                   10354:                                  ':'.$res->randomout().
                   10355:                                  ':'.$res->encrypted().
1.1205    raeburn  10356:                                  ':'.$res->randomorder().
                   10357:                                  ':'.$res->is_page();
1.1199    raeburn  10358:                     }
                   10359:                 }
                   10360:             }
                   10361:             $path =~ s/^\&//;
                   10362:             my $maptitle = $mapresobj->title();
                   10363:             if ($mapurl eq 'default') {
                   10364:                 $maptitle = 'Main Course Documents';
                   10365:             }
                   10366:             $path .= ($path ne '')? '&' : ''.
                   10367:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10368:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10369:                     ':'.$mapresobj->randompick().
                   10370:                     ':'.$mapresobj->randomout().
                   10371:                     ':'.$mapresobj->encrypted().
1.1205    raeburn  10372:                     ':'.$mapresobj->randomorder().
                   10373:                     ':'.$mapresobj->is_page();
1.1199    raeburn  10374:         } else {
                   10375:             my $maptitle = &gettitle($mapurl);
1.1205    raeburn  10376:             my $ispage;
                   10377:             if ($mapurl =~ /\.page$/) {
                   10378:                 $ispage = 1;
                   10379:             }
1.1199    raeburn  10380:             if ($mapurl eq 'default') {
                   10381:                 $maptitle = 'Main Course Documents';
                   10382:             }
                   10383:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1205    raeburn  10384:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
1.1199    raeburn  10385:         }
                   10386:         unless ($mapurl eq 'default') {
                   10387:             $path = 'default&'.
                   10388:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
1.1205    raeburn  10389:                     ':::::&'.$path;
1.1199    raeburn  10390:         }
                   10391:     }
                   10392:     return $path;
                   10393: }
                   10394: 
1.614     albertel 10395: sub get_slot {
                   10396:     my ($which,$cnum,$cdom)=@_;
                   10397:     if (!$cnum || !$cdom) {
1.790     albertel 10398: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10399: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10400: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10401:     }
1.703     albertel 10402:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10403:     my %slotinfo;
                   10404:     if (exists($remembered{$key})) {
                   10405: 	$slotinfo{$which} = $remembered{$key};
                   10406:     } else {
                   10407: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10408: 	&Apache::lonhomework::showhash(%slotinfo);
                   10409: 	my ($tmp)=keys(%slotinfo);
                   10410: 	if ($tmp=~/^error:/) { return (); }
                   10411: 	$remembered{$key} = $slotinfo{$which};
                   10412:     }
1.616     albertel 10413:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10414: 	return %{$slotinfo{$which}};
                   10415:     }
                   10416:     return $slotinfo{$which};
1.614     albertel 10417: }
1.1150    raeburn  10418: 
                   10419: sub get_reservable_slots {
                   10420:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10421:     my $now = time;
                   10422:     my $reservable_info;
                   10423:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10424:     if (exists($remembered{$key})) {
                   10425:         $reservable_info = $remembered{$key};
                   10426:     } else {
                   10427:         my %resv;
                   10428:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10429:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10430:         $reservable_info = \%resv;
                   10431:         $remembered{$key} = $reservable_info;
                   10432:     }
                   10433:     return $reservable_info;
                   10434: }
                   10435: 
                   10436: sub get_course_slots {
                   10437:     my ($cnum,$cdom) = @_;
                   10438:     my $hashid=$cnum.':'.$cdom;
                   10439:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10440:     if (defined($cached)) {
                   10441:         if (ref($result) eq 'HASH') {
                   10442:             return %{$result};
                   10443:         }
                   10444:     } else {
                   10445:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10446:         my ($tmp) = keys(%slots);
                   10447:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10448:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10449:             return %slots;
                   10450:         }
                   10451:     }
                   10452:     return;
                   10453: }
                   10454: 
                   10455: sub devalidate_slots_cache {
                   10456:     my ($cnum,$cdom)=@_;
                   10457:     my $hashid=$cnum.':'.$cdom;
                   10458:     &devalidate_cache_new('allslots',$hashid);
                   10459: }
                   10460: 
1.1181    raeburn  10461: sub get_coursechange {
                   10462:     my ($cdom,$cnum) = @_;
                   10463:     if ($cdom eq '' || $cnum eq '') {
                   10464:         return unless ($env{'request.course.id'});
                   10465:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10466:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10467:     }
                   10468:     my $hashid=$cdom.'_'.$cnum;
                   10469:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10470:     if ((defined($cached)) && ($change ne '')) {
                   10471:         return $change;
                   10472:     } else {
                   10473:         my %crshash;
                   10474:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10475:         if ($crshash{'internal.contentchange'} eq '') {
                   10476:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10477:             if ($change eq '') {
                   10478:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10479:                 $change = $crshash{'internal.created'};
                   10480:             }
                   10481:         } else {
                   10482:             $change = $crshash{'internal.contentchange'};
                   10483:         }
                   10484:         my $cachetime = 600;
                   10485:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10486:     }
                   10487:     return $change;
                   10488: }
                   10489: 
                   10490: sub devalidate_coursechange_cache {
                   10491:     my ($cnum,$cdom)=@_;
                   10492:     my $hashid=$cnum.':'.$cdom;
                   10493:     &devalidate_cache_new('crschange',$hashid);
                   10494: }
                   10495: 
1.31      www      10496: # ------------------------------------------------- Update symbolic store links
                   10497: 
                   10498: sub symblist {
                   10499:     my ($mapname,%newhash)=@_;
1.438     www      10500:     $mapname=&deversion(&declutter($mapname));
1.31      www      10501:     my %hash;
1.620     albertel 10502:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10503:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10504:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10505: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10506: 		next if ($url eq 'last_known'
                   10507: 			 && $env{'form.no_update_last_known'});
                   10508: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10509: 						    $newhash{$url}->[1],
                   10510: 						    $newhash{$url}->[0]);
1.191     harris41 10511:             }
1.31      www      10512:             if (untie(%hash)) {
                   10513: 		return 'ok';
                   10514:             }
                   10515:         }
                   10516:     }
                   10517:     return 'error';
1.212     www      10518: }
                   10519: 
                   10520: # --------------------------------------------------------------- Verify a symb
                   10521: 
                   10522: sub symbverify {
1.1190    raeburn  10523:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10524:     my $thisfn=$thisurl;
1.439     www      10525:     $thisfn=&declutter($thisfn);
1.215     www      10526: # direct jump to resource in page or to a sequence - will construct own symbs
                   10527:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10528: # check URL part
1.409     www      10529:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10530: 
1.431     www      10531:     unless ($url eq $thisfn) { return 0; }
1.213     www      10532: 
1.216     www      10533:     $symb=&symbclean($symb);
1.510     www      10534:     $thisurl=&deversion($thisurl);
1.439     www      10535:     $thisfn=&deversion($thisfn);
1.213     www      10536: 
                   10537:     my %bighash;
                   10538:     my $okay=0;
1.431     www      10539: 
1.620     albertel 10540:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10541:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10542:         my $noclutter;
1.1032    raeburn  10543:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10544:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10545:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10546:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10547:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10548:                 $noclutter = 1;
                   10549:             }
                   10550:         }
                   10551:         my $ids;
                   10552:         if ($noclutter) {
                   10553:             $ids=$bighash{'ids_'.$thisurl};
                   10554:         } else {
                   10555:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10556:         }
1.1102    raeburn  10557:         unless ($ids) {
                   10558:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10559:             $ids=$bighash{$idkey};
1.216     www      10560:         }
                   10561:         if ($ids) {
                   10562: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10563:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10564:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10565:             }
1.800     albertel 10566: 	    foreach my $id (split(/\,/,$ids)) {
                   10567: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10568:                if (
                   10569:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10570:    eq $symb) {
                   10571:                    if (ref($encstate)) {
                   10572:                        $$encstate = $bighash{'encrypted_'.$id};
                   10573:                    }
1.620     albertel 10574: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10575: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10576:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10577: 		       $okay=1;
1.1202    raeburn  10578:                        last;
1.582     albertel 10579: 		   }
                   10580: 	       }
1.216     www      10581: 	   }
                   10582:         }
1.213     www      10583: 	untie(%bighash);
                   10584:     }
                   10585:     return $okay;
1.31      www      10586: }
                   10587: 
1.210     www      10588: # --------------------------------------------------------------- Clean-up symb
                   10589: 
                   10590: sub symbclean {
                   10591:     my $symb=shift;
1.568     albertel 10592:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10593: # remove version from map
                   10594:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10595: 
1.210     www      10596: # remove version from URL
                   10597:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10598: 
1.507     www      10599: # remove wrapper
                   10600: 
1.510     www      10601:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10602:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10603:     return $symb;
1.409     www      10604: }
                   10605: 
                   10606: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10607: 
                   10608: sub encode_symb {
                   10609:     my ($map,$resid,$url)=@_;
                   10610:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10611: }
1.409     www      10612: 
                   10613: sub decode_symb {
1.568     albertel 10614:     my $symb=shift;
                   10615:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10616:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10617:     return (&fixversion($map),$resid,&fixversion($url));
                   10618: }
                   10619: 
                   10620: sub fixversion {
                   10621:     my $fn=shift;
1.609     banghart 10622:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10623:     my %bighash;
                   10624:     my $uri=&clutter($fn);
1.620     albertel 10625:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10626: # is this cached?
1.599     albertel 10627:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10628:     if (defined($cached)) { return $result; }
                   10629: # unfortunately not cached, or expired
1.620     albertel 10630:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10631: 	    &GDBM_READER(),0640)) {
                   10632:  	if ($bighash{'version_'.$uri}) {
                   10633:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10634:  	    unless (($version eq 'mostrecent') || 
                   10635: 		    ($version==&getversion($uri))) {
1.440     www      10636:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10637:  	    }
                   10638:  	}
                   10639:  	untie %bighash;
1.413     www      10640:     }
1.599     albertel 10641:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10642: }
                   10643: 
                   10644: sub deversion {
                   10645:     my $url=shift;
                   10646:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10647:     return $url;
1.210     www      10648: }
                   10649: 
1.31      www      10650: # ------------------------------------------------------ Return symb list entry
                   10651: 
                   10652: sub symbread {
1.249     www      10653:     my ($thisfn,$donotrecurse)=@_;
1.1206    raeburn  10654:     my $cache_str;
                   10655:     if ($thisfn ne '') {
                   10656:         $cache_str='request.symbread.cached.'.$thisfn;
                   10657:         if ($env{$cache_str} ne '') {
1.1179    raeburn  10658:             return $env{$cache_str};
                   10659:         }
1.1206    raeburn  10660:     } else {
1.242     www      10661: # no filename provided? try from environment
1.620     albertel 10662:         if ($env{'request.symb'}) {
                   10663: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10664: 	}
1.620     albertel 10665: 	$thisfn=$env{'request.filename'};
1.44      www      10666:     }
1.569     albertel 10667:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10668: # is that filename actually a symb? Verify, clean, and return
                   10669:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10670: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10671: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10672: 	}
1.242     www      10673:     }
1.44      www      10674:     $thisfn=declutter($thisfn);
1.31      www      10675:     my %hash;
1.37      www      10676:     my %bighash;
                   10677:     my $syval='';
1.620     albertel 10678:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10679:         my $targetfn = $thisfn;
1.609     banghart 10680:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10681:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10682:         }
1.687     albertel 10683: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10684: 	    $targetfn=$1;
                   10685: 	}
1.620     albertel 10686:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10687:                       &GDBM_READER(),0640)) {
1.481     raeburn  10688: 	    $syval=$hash{$targetfn};
1.37      www      10689:             untie(%hash);
                   10690:         }
                   10691: # ---------------------------------------------------------- There was an entry
                   10692:         if ($syval) {
1.601     albertel 10693: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10694: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10695: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10696: 		    #return $env{$cache_str}='';
1.601     albertel 10697: 		#}    
                   10698: 		#$syval.=$1;
                   10699: 	    #}
1.37      www      10700:         } else {
                   10701: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10702:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10703:                             &GDBM_READER(),0640)) {
1.37      www      10704: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10705:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10706:               unless ($ids) { 
                   10707:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10708:               }
                   10709:               unless ($ids) {
                   10710: # alias?
                   10711: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10712:               }
1.37      www      10713:               if ($ids) {
                   10714: # ------------------------------------------------------------------- Has ID(s)
                   10715:                  my @possibilities=split(/\,/,$ids);
1.39      www      10716:                  if ($#possibilities==0) {
                   10717: # ----------------------------------------------- There is only one possibility
1.37      www      10718: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10719: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10720: 						    $resid,$thisfn);
1.249     www      10721:                  } elsif (!$donotrecurse) {
1.39      www      10722: # ------------------------------------------ There is more than one possibility
                   10723:                      my $realpossible=0;
1.800     albertel 10724:                      foreach my $id (@possibilities) {
                   10725: 			 my $file=$bighash{'src_'.$id};
1.39      www      10726:                          if (&allowed('bre',$file)) {
1.800     albertel 10727:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10728:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10729: 				$realpossible++;
1.626     albertel 10730:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10731: 						    $resid,$thisfn);
1.39      www      10732:                             }
                   10733: 			 }
1.191     harris41 10734:                      }
1.39      www      10735: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10736:                  } else {
                   10737:                      $syval='';
1.37      www      10738:                  }
                   10739: 	      }
                   10740:               untie(%bighash)
1.481     raeburn  10741:            }
1.31      www      10742:         }
1.62      www      10743:         if ($syval) {
1.620     albertel 10744: 	    return $env{$cache_str}=$syval;
1.62      www      10745:         }
1.31      www      10746:     }
1.949     raeburn  10747:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10748:     return $env{$cache_str}='';
1.31      www      10749: }
                   10750: 
                   10751: # ---------------------------------------------------------- Return random seed
                   10752: 
1.32      www      10753: sub numval {
                   10754:     my $txt=shift;
                   10755:     $txt=~tr/A-J/0-9/;
                   10756:     $txt=~tr/a-j/0-9/;
                   10757:     $txt=~tr/K-T/0-9/;
                   10758:     $txt=~tr/k-t/0-9/;
                   10759:     $txt=~tr/U-Z/0-5/;
                   10760:     $txt=~tr/u-z/0-5/;
                   10761:     $txt=~s/\D//g;
1.564     albertel 10762:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10763:     return int($txt);
1.368     albertel 10764: }
                   10765: 
1.484     albertel 10766: sub numval2 {
                   10767:     my $txt=shift;
                   10768:     $txt=~tr/A-J/0-9/;
                   10769:     $txt=~tr/a-j/0-9/;
                   10770:     $txt=~tr/K-T/0-9/;
                   10771:     $txt=~tr/k-t/0-9/;
                   10772:     $txt=~tr/U-Z/0-5/;
                   10773:     $txt=~tr/u-z/0-5/;
                   10774:     $txt=~s/\D//g;
                   10775:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10776:     my $total;
                   10777:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10778:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10779:     return int($total);
                   10780: }
                   10781: 
1.575     albertel 10782: sub numval3 {
                   10783:     use integer;
                   10784:     my $txt=shift;
                   10785:     $txt=~tr/A-J/0-9/;
                   10786:     $txt=~tr/a-j/0-9/;
                   10787:     $txt=~tr/K-T/0-9/;
                   10788:     $txt=~tr/k-t/0-9/;
                   10789:     $txt=~tr/U-Z/0-5/;
                   10790:     $txt=~tr/u-z/0-5/;
                   10791:     $txt=~s/\D//g;
                   10792:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10793:     my $total;
                   10794:     foreach my $val (@txts) { $total+=$val; }
                   10795:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10796:     return $total;
                   10797: }
                   10798: 
1.675     albertel 10799: sub digest {
                   10800:     my ($data)=@_;
                   10801:     my $digest=&Digest::MD5::md5($data);
                   10802:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10803:     my ($e,$f);
                   10804:     {
                   10805:         use integer;
                   10806:         $e=($a+$b);
                   10807:         $f=($c+$d);
                   10808:         if ($_64bit) {
                   10809:             $e=(($e<<32)>>32);
                   10810:             $f=(($f<<32)>>32);
                   10811:         }
                   10812:     }
                   10813:     if (wantarray) {
                   10814: 	return ($e,$f);
                   10815:     } else {
                   10816: 	my $g;
                   10817: 	{
                   10818: 	    use integer;
                   10819: 	    $g=($e+$f);
                   10820: 	    if ($_64bit) {
                   10821: 		$g=(($g<<32)>>32);
                   10822: 	    }
                   10823: 	}
                   10824: 	return $g;
                   10825:     }
                   10826: }
                   10827: 
1.368     albertel 10828: sub latest_rnd_algorithm_id {
1.675     albertel 10829:     return '64bit5';
1.366     albertel 10830: }
1.32      www      10831: 
1.503     albertel 10832: sub get_rand_alg {
                   10833:     my ($courseid)=@_;
1.790     albertel 10834:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10835:     if ($courseid) {
1.620     albertel 10836: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10837:     }
                   10838:     return &latest_rnd_algorithm_id();
                   10839: }
                   10840: 
1.562     albertel 10841: sub validCODE {
                   10842:     my ($CODE)=@_;
                   10843:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10844:     return 0;
                   10845: }
                   10846: 
1.491     albertel 10847: sub getCODE {
1.620     albertel 10848:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10849:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10850: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10851: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10852: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10853:     }
                   10854:     return undef;
                   10855: }
1.1133    foxr     10856: #
                   10857: #  Determines the random seed for a specific context:
                   10858: #
                   10859: # parameters:
                   10860: #   symb      - in course context the symb for the seed.
                   10861: #   course_id - The course id of the form domain_coursenum.
                   10862: #   domain    - Domain for the user.
                   10863: #   course    - Course for the user.
                   10864: #   cenv      - environment of the course.
                   10865: #
                   10866: # NOTE:
                   10867: #   All parameters are picked out of the environment if missing
                   10868: #   or not defined.
                   10869: #   If a symb cannot be determined the current time is used instead.
                   10870: #
                   10871: #  For a given well defined symb, courside, domain, username,
                   10872: #  and course environment, the seed is reproducible.
                   10873: #
1.31      www      10874: sub rndseed {
1.1133    foxr     10875:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10876:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10877:     if (!defined($symb)) {
1.366     albertel 10878: 	unless ($symb=$wsymb) { return time; }
                   10879:     }
1.1146    foxr     10880:     if (!defined $courseid) { 
                   10881: 	$courseid=$wcourseid; 
                   10882:     }
                   10883:     if (!defined $domain) { $domain=$wdomain; }
                   10884:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10885: 
                   10886:     my $which;
                   10887:     if (defined($cenv->{'rndseed'})) {
                   10888: 	$which = $cenv->{'rndseed'};
                   10889:     } else {
                   10890: 	$which =&get_rand_alg($courseid);
                   10891:     }
1.491     albertel 10892:     if (defined(&getCODE())) {
1.1133    foxr     10893: 
1.675     albertel 10894: 	if ($which eq '64bit5') {
                   10895: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10896: 	} elsif ($which eq '64bit4') {
1.575     albertel 10897: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10898: 	} else {
                   10899: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10900: 	}
1.675     albertel 10901:     } elsif ($which eq '64bit5') {
                   10902: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10903:     } elsif ($which eq '64bit4') {
                   10904: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10905:     } elsif ($which eq '64bit3') {
                   10906: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10907:     } elsif ($which eq '64bit2') {
                   10908: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10909:     } elsif ($which eq '64bit') {
                   10910: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10911:     }
                   10912:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10913: }
                   10914: 
                   10915: sub rndseed_32bit {
                   10916:     my ($symb,$courseid,$domain,$username)=@_;
                   10917:     {
                   10918: 	use integer;
                   10919: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10920: 	my $symbseed=numval($symb) << 22;
                   10921: 	my $namechck=unpack("%32C*",$username) << 17;
                   10922: 	my $nameseed=numval($username) << 12;
                   10923: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10924: 	my $courseseed=unpack("%32C*",$courseid);
                   10925: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10926: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10927: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10928: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10929: 	return $num;
                   10930:     }
                   10931: }
                   10932: 
                   10933: sub rndseed_64bit {
                   10934:     my ($symb,$courseid,$domain,$username)=@_;
                   10935:     {
                   10936: 	use integer;
                   10937: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10938: 	my $symbseed=numval($symb) << 10;
                   10939: 	my $namechck=unpack("%32S*",$username);
                   10940: 	
                   10941: 	my $nameseed=numval($username) << 21;
                   10942: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10943: 	my $courseseed=unpack("%32S*",$courseid);
                   10944: 	
                   10945: 	my $num1=$symbchck+$symbseed+$namechck;
                   10946: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10947: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10948: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10949: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10950: 	return "$num1,$num2";
1.155     albertel 10951:     }
1.366     albertel 10952: }
                   10953: 
1.443     albertel 10954: sub rndseed_64bit2 {
                   10955:     my ($symb,$courseid,$domain,$username)=@_;
                   10956:     {
                   10957: 	use integer;
                   10958: 	# strings need to be an even # of cahracters long, it it is odd the
                   10959:         # last characters gets thrown away
                   10960: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10961: 	my $symbseed=numval($symb) << 10;
                   10962: 	my $namechck=unpack("%32S*",$username.' ');
                   10963: 	
                   10964: 	my $nameseed=numval($username) << 21;
1.501     albertel 10965: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10966: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10967: 	
                   10968: 	my $num1=$symbchck+$symbseed+$namechck;
                   10969: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10970: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10971: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10972: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10973: 	return "$num1,$num2";
                   10974:     }
                   10975: }
                   10976: 
                   10977: sub rndseed_64bit3 {
                   10978:     my ($symb,$courseid,$domain,$username)=@_;
                   10979:     {
                   10980: 	use integer;
                   10981: 	# strings need to be an even # of cahracters long, it it is odd the
                   10982:         # last characters gets thrown away
                   10983: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10984: 	my $symbseed=numval2($symb) << 10;
                   10985: 	my $namechck=unpack("%32S*",$username.' ');
                   10986: 	
                   10987: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10988: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10989: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10990: 	
                   10991: 	my $num1=$symbchck+$symbseed+$namechck;
                   10992: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10993: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10994: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10995: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10996: 	
1.503     albertel 10997: 	return "$num1:$num2";
1.443     albertel 10998:     }
                   10999: }
                   11000: 
1.575     albertel 11001: sub rndseed_64bit4 {
                   11002:     my ($symb,$courseid,$domain,$username)=@_;
                   11003:     {
                   11004: 	use integer;
                   11005: 	# strings need to be an even # of cahracters long, it it is odd the
                   11006:         # last characters gets thrown away
                   11007: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11008: 	my $symbseed=numval3($symb) << 10;
                   11009: 	my $namechck=unpack("%32S*",$username.' ');
                   11010: 	
                   11011: 	my $nameseed=numval3($username) << 21;
                   11012: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11013: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11014: 	
                   11015: 	my $num1=$symbchck+$symbseed+$namechck;
                   11016: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11017: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11018: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11019: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11020: 	
1.575     albertel 11021: 	return "$num1:$num2";
                   11022:     }
                   11023: }
                   11024: 
1.675     albertel 11025: sub rndseed_64bit5 {
                   11026:     my ($symb,$courseid,$domain,$username)=@_;
                   11027:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11028:     return "$num1:$num2";
                   11029: }
                   11030: 
1.366     albertel 11031: sub rndseed_CODE_64bit {
                   11032:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11033:     {
1.366     albertel 11034: 	use integer;
1.443     albertel 11035: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11036: 	my $symbseed=numval2($symb);
1.491     albertel 11037: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11038: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11039: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11040: 	my $num1=$symbseed+$CODEchck;
                   11041: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11042: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11043: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11044: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11045: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11046: 	return "$num1:$num2";
1.366     albertel 11047:     }
                   11048: }
                   11049: 
1.575     albertel 11050: sub rndseed_CODE_64bit4 {
                   11051:     my ($symb,$courseid,$domain,$username)=@_;
                   11052:     {
                   11053: 	use integer;
                   11054: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11055: 	my $symbseed=numval3($symb);
                   11056: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11057: 	my $CODEseed=numval3(&getCODE());
                   11058: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11059: 	my $num1=$symbseed+$CODEchck;
                   11060: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11061: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11062: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11063: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11064: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11065: 	return "$num1:$num2";
                   11066:     }
                   11067: }
                   11068: 
1.675     albertel 11069: sub rndseed_CODE_64bit5 {
                   11070:     my ($symb,$courseid,$domain,$username)=@_;
                   11071:     my $code = &getCODE();
                   11072:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11073:     return "$num1:$num2";
                   11074: }
                   11075: 
1.366     albertel 11076: sub setup_random_from_rndseed {
                   11077:     my ($rndseed)=@_;
1.503     albertel 11078:     if ($rndseed =~/([,:])/) {
                   11079: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11080: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11081:     } else {
                   11082: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11083:     }
1.36      albertel 11084: }
                   11085: 
1.474     albertel 11086: sub latest_receipt_algorithm_id {
1.835     albertel 11087:     return 'receipt3';
1.474     albertel 11088: }
                   11089: 
1.480     www      11090: sub recunique {
                   11091:     my $fucourseid=shift;
                   11092:     my $unique;
1.835     albertel 11093:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11094: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11095: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11096:     } else {
                   11097: 	$unique=$perlvar{'lonReceipt'};
                   11098:     }
                   11099:     return unpack("%32C*",$unique);
                   11100: }
                   11101: 
                   11102: sub recprefix {
                   11103:     my $fucourseid=shift;
                   11104:     my $prefix;
1.835     albertel 11105:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11106: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11107: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11108:     } else {
                   11109: 	$prefix=$perlvar{'lonHostID'};
                   11110:     }
                   11111:     return unpack("%32C*",$prefix);
                   11112: }
                   11113: 
1.76      www      11114: sub ireceipt {
1.474     albertel 11115:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11116: 
                   11117:     my $return =&recprefix($fucourseid).'-';
                   11118: 
                   11119:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11120: 	$env{'request.state'} eq 'construct') {
                   11121: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11122: 	return $return;
                   11123:     }
                   11124: 
1.76      www      11125:     my $cuname=unpack("%32C*",$funame);
                   11126:     my $cudom=unpack("%32C*",$fudom);
                   11127:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11128:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11129:     my $cunique=&recunique($fucourseid);
1.474     albertel 11130:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11131:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11132: 
1.790     albertel 11133: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11134: 			       
                   11135: 	$return.= ($cunique%$cuname+
                   11136: 		   $cunique%$cudom+
                   11137: 		   $cusymb%$cuname+
                   11138: 		   $cusymb%$cudom+
                   11139: 		   $cucourseid%$cuname+
                   11140: 		   $cucourseid%$cudom+
                   11141: 		   $cpart%$cuname+
                   11142: 		   $cpart%$cudom);
                   11143:     } else {
                   11144: 	$return.= ($cunique%$cuname+
                   11145: 		   $cunique%$cudom+
                   11146: 		   $cusymb%$cuname+
                   11147: 		   $cusymb%$cudom+
                   11148: 		   $cucourseid%$cuname+
                   11149: 		   $cucourseid%$cudom);
                   11150:     }
                   11151:     return $return;
1.76      www      11152: }
                   11153: 
                   11154: sub receipt {
1.474     albertel 11155:     my ($part)=@_;
1.790     albertel 11156:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11157:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11158: }
1.260     ng       11159: 
1.790     albertel 11160: sub whichuser {
                   11161:     my ($passedsymb)=@_;
                   11162:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11163:     if (defined($env{'form.grade_symb'})) {
                   11164: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11165: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11166: 	if (!$allowed &&
                   11167: 	    exists($env{'request.course.sec'}) &&
                   11168: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11169: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11170: 			      '/'.$env{'request.course.sec'});
                   11171: 	}
                   11172: 	if ($allowed) {
                   11173: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11174: 	    $courseid=$tmp_courseid;
                   11175: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11176: 	    ($name)=&get_env_multiple('form.grade_username');
                   11177: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11178: 	}
                   11179:     }
                   11180:     if (!$passedsymb) {
                   11181: 	$symb=&symbread();
                   11182:     } else {
                   11183: 	$symb=$passedsymb;
                   11184:     }
                   11185:     $courseid=$env{'request.course.id'};
                   11186:     $domain=$env{'user.domain'};
                   11187:     $name=$env{'user.name'};
                   11188:     if ($name eq 'public' && $domain eq 'public') {
                   11189: 	if (!defined($env{'form.username'})) {
                   11190: 	    $env{'form.username'}.=time.rand(10000000);
                   11191: 	}
                   11192: 	$name.=$env{'form.username'};
                   11193:     }
                   11194:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11195: 
                   11196: }
                   11197: 
1.36      albertel 11198: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11199: # returns either the contents of the file or 
                   11200: # -1 if the file doesn't exist
1.481     raeburn  11201: #
                   11202: # if the target is a file that was uploaded via DOCS, 
                   11203: # a check will be made to see if a current copy exists on the local server,
                   11204: # if it does this will be served, otherwise a copy will be retrieved from
                   11205: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11206: # the local server.   
1.472     albertel 11207: 
1.36      albertel 11208: sub getfile {
1.538     albertel 11209:     my ($file) = @_;
1.609     banghart 11210:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11211:     &repcopy($file);
                   11212:     return &readfile($file);
                   11213: }
                   11214: 
                   11215: sub repcopy_userfile {
                   11216:     my ($file)=@_;
1.1142    raeburn  11217:     my $londocroot = $perlvar{'lonDocRoot'};
                   11218:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11219:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11220:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11221: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11222:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11223:     if (-e "$file") {
1.828     www      11224: # we already have a local copy, check it out
1.538     albertel 11225: 	my @fileinfo = stat($file);
1.828     www      11226: 	my $rtncode;
                   11227: 	my $info;
1.538     albertel 11228: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11229: 	if ($lwpresp ne 'ok') {
1.828     www      11230: # there is no such file anymore, even though we had a local copy
1.482     albertel 11231: 	    if ($rtncode eq '404') {
1.538     albertel 11232: 		unlink($file);
1.482     albertel 11233: 	    }
                   11234: 	    return -1;
                   11235: 	}
                   11236: 	if ($info < $fileinfo[9]) {
1.828     www      11237: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11238: 	    return 'ok';
1.828     www      11239: 	} else {
                   11240: # the file is outdated, get rid of it
                   11241: 	    unlink($file);
1.482     albertel 11242: 	}
1.828     www      11243:     }
                   11244: # one way or the other, at this point, we don't have the file
                   11245: # construct the correct path for the file
                   11246:     my @parts = ($cdom,$cnum); 
                   11247:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11248: 	push @parts, split(/\//,$1);
                   11249:     }
                   11250:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11251:     foreach my $part (@parts) {
                   11252: 	$path .= '/'.$part;
                   11253: 	if (!-e $path) {
                   11254: 	    mkdir($path,0770);
1.482     albertel 11255: 	}
                   11256:     }
1.828     www      11257: # now the path exists for sure
                   11258: # get a user agent
                   11259:     my $ua=new LWP::UserAgent;
                   11260:     my $transferfile=$file.'.in.transfer';
                   11261: # FIXME: this should flock
                   11262:     if (-e $transferfile) { return 'ok'; }
                   11263:     my $request;
                   11264:     $uri=~s/^\///;
1.980     raeburn  11265:     my $homeserver = &homeserver($cnum,$cdom);
                   11266:     my $protocol = $protocol{$homeserver};
                   11267:     $protocol = 'http' if ($protocol ne 'https');
                   11268:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11269:     my $response=$ua->request($request,$transferfile);
                   11270: # did it work?
                   11271:     if ($response->is_error()) {
                   11272: 	unlink($transferfile);
                   11273: 	&logthis("Userfile repcopy failed for $uri");
                   11274: 	return -1;
                   11275:     }
                   11276: # worked, rename the transfer file
                   11277:     rename($transferfile,$file);
1.607     raeburn  11278:     return 'ok';
1.481     raeburn  11279: }
                   11280: 
1.517     albertel 11281: sub tokenwrapper {
                   11282:     my $uri=shift;
1.980     raeburn  11283:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11284:     $uri=~s|^/||;
1.620     albertel 11285:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11286:     my $token=$1;
1.552     albertel 11287:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11288:     if ($udom && $uname && $file) {
                   11289: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11290:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11291:         my $homeserver = &homeserver($uname,$udom);
                   11292:         my $protocol = $protocol{$homeserver};
                   11293:         $protocol = 'http' if ($protocol ne 'https');
                   11294:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11295:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11296:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11297:     } else {
                   11298:         return '/adm/notfound.html';
                   11299:     }
                   11300: }
                   11301: 
1.828     www      11302: # call with reqtype HEAD: get last modification time
                   11303: # call with reqtype GET: get the file contents
                   11304: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11305: #
1.481     raeburn  11306: sub getuploaded {
                   11307:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11308:     $uri=~s/^\///;
1.980     raeburn  11309:     my $homeserver = &homeserver($cnum,$cdom);
                   11310:     my $protocol = $protocol{$homeserver};
                   11311:     $protocol = 'http' if ($protocol ne 'https');
                   11312:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11313:     my $ua=new LWP::UserAgent;
                   11314:     my $request=new HTTP::Request($reqtype,$uri);
                   11315:     my $response=$ua->request($request);
                   11316:     $$rtncode = $response->code;
1.482     albertel 11317:     if (! $response->is_success()) {
                   11318: 	return 'failed';
                   11319:     }      
                   11320:     if ($reqtype eq 'HEAD') {
1.486     www      11321: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11322:     } elsif ($reqtype eq 'GET') {
                   11323: 	$$info = $response->content;
1.472     albertel 11324:     }
1.482     albertel 11325:     return 'ok';
1.36      albertel 11326: }
                   11327: 
1.481     raeburn  11328: sub readfile {
                   11329:     my $file = shift;
                   11330:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11331:     my $fh;
                   11332:     open($fh,"<$file");
                   11333:     my $a='';
1.800     albertel 11334:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11335:     return $a;
                   11336: }
                   11337: 
1.36      albertel 11338: sub filelocation {
1.590     banghart 11339:     my ($dir,$file) = @_;
                   11340:     my $location;
                   11341:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11342: 
                   11343:     if ($file =~ m-^/adm/-) {
                   11344: 	$file=~s-^/adm/wrapper/-/-;
                   11345: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11346:     }
1.882     albertel 11347: 
1.1139    www      11348:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11349:         $location = $file;
1.609     banghart 11350:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11351:         my ($udom,$uname,$filename)=
1.811     albertel 11352:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11353:         my $home=&homeserver($uname,$udom);
                   11354:         my $is_me=0;
                   11355:         my @ids=&current_machine_ids();
                   11356:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11357:         if ($is_me) {
1.1117    foxr     11358:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11359:         } else {
                   11360:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11361:   	      $udom.'/'.$uname.'/'.$filename;
                   11362:         }
1.882     albertel 11363:     } elsif ($file =~ m-^/adm/-) {
                   11364: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11365:     } else {
                   11366:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11367:         $file=~s:^/(res|priv)/:/:;
                   11368:         my $space=$1;
1.590     banghart 11369:         if ( !( $file =~ m:^/:) ) {
                   11370:             $location = $dir. '/'.$file;
                   11371:         } else {
1.1142    raeburn  11372:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11373:         }
1.59      albertel 11374:     }
1.590     banghart 11375:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11376:     while ($location=~m{/\.\./}) {
                   11377: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11378: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11379: 	} else {
                   11380: 	    $location=~ s{/\.\./}{/}g;
                   11381: 	}
                   11382:     } #remove dir/..
1.590     banghart 11383:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11384:     return $location;
1.46      www      11385: }
1.36      albertel 11386: 
1.46      www      11387: sub hreflocation {
                   11388:     my ($dir,$file)=@_;
1.980     raeburn  11389:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11390: 	$file=filelocation($dir,$file);
1.700     albertel 11391:     } elsif ($file=~m-^/adm/-) {
                   11392: 	$file=~s-^/adm/wrapper/-/-;
                   11393: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11394:     }
                   11395:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11396: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11397:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11398: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11399: 	        {/uploaded/$1/$2/}x;
1.46      www      11400:     }
1.913     albertel 11401:     if ($file=~ m{^/userfiles/}) {
                   11402: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11403:     }
1.462     albertel 11404:     return $file;
1.465     albertel 11405: }
                   11406: 
1.1139    www      11407: 
                   11408: 
                   11409: 
                   11410: 
1.465     albertel 11411: sub current_machine_domains {
1.853     albertel 11412:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11413: }
                   11414: 
                   11415: sub machine_domains {
                   11416:     my ($hostname) = @_;
1.465     albertel 11417:     my @domains;
1.838     albertel 11418:     my %hostname = &all_hostnames();
1.465     albertel 11419:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11420: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11421: 	if ($hostname eq $name) {
1.844     albertel 11422: 	    push(@domains,&host_domain($id));
1.465     albertel 11423: 	}
                   11424:     }
                   11425:     return @domains;
                   11426: }
                   11427: 
                   11428: sub current_machine_ids {
1.853     albertel 11429:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11430: }
                   11431: 
                   11432: sub machine_ids {
                   11433:     my ($hostname) = @_;
                   11434:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11435:     my @ids;
1.888     albertel 11436:     my %name_to_host = &all_names();
1.889     albertel 11437:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11438: 	return @{ $name_to_host{$hostname} };
                   11439:     }
                   11440:     return;
1.31      www      11441: }
                   11442: 
1.824     raeburn  11443: sub additional_machine_domains {
                   11444:     my @domains;
                   11445:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11446:     while( my $line = <$fh>) {
                   11447:         $line =~ s/\s//g;
                   11448:         push(@domains,$line);
                   11449:     }
                   11450:     return @domains;
                   11451: }
                   11452: 
                   11453: sub default_login_domain {
                   11454:     my $domain = $perlvar{'lonDefDomain'};
                   11455:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11456:     foreach my $posdom (&current_machine_domains(),
                   11457:                         &additional_machine_domains()) {
                   11458:         if (lc($posdom) eq lc($testdomain)) {
                   11459:             $domain=$posdom;
                   11460:             last;
                   11461:         }
                   11462:     }
                   11463:     return $domain;
                   11464: }
                   11465: 
1.31      www      11466: # ------------------------------------------------------------- Declutters URLs
                   11467: 
                   11468: sub declutter {
                   11469:     my $thisfn=shift;
1.569     albertel 11470:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11471:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11472:     $thisfn=~s/^\///;
1.697     albertel 11473:     $thisfn=~s|^adm/wrapper/||;
                   11474:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11475:     $thisfn=~s/^res\///;
1.1172    bisitz   11476:     $thisfn=~s/^priv\///;
1.1032    raeburn  11477:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11478:         $thisfn=~s/\?.+$//;
                   11479:     }
1.268     www      11480:     return $thisfn;
                   11481: }
                   11482: 
                   11483: # ------------------------------------------------------------- Clutter up URLs
                   11484: 
                   11485: sub clutter {
                   11486:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11487:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11488: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11489:        $thisfn='/res'.$thisfn; 
                   11490:     }
1.1031    raeburn  11491:     if ($thisfn !~m|^/adm|) {
                   11492: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11493: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11494: 	} else {
                   11495: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11496: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11497: 	    if ($embstyle eq 'ssi'
                   11498: 		|| ($embstyle eq 'hdn')
                   11499: 		|| ($embstyle eq 'rat')
                   11500: 		|| ($embstyle eq 'prv')
                   11501: 		|| ($embstyle eq 'ign')) {
                   11502: 		#do nothing with these
                   11503: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11504: 		|| ($embstyle eq 'emb')
                   11505: 		|| ($embstyle eq 'wrp')) {
                   11506: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11507: 	    } elsif ($embstyle eq 'unk'
                   11508: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11509: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11510: 	    } else {
1.718     www      11511: #		&logthis("Got a blank emb style");
1.695     albertel 11512: 	    }
1.694     albertel 11513: 	}
                   11514:     }
1.31      www      11515:     return $thisfn;
1.12      www      11516: }
                   11517: 
1.787     albertel 11518: sub clutter_with_no_wrapper {
                   11519:     my $uri = &clutter(shift);
                   11520:     if ($uri =~ m-^/adm/-) {
                   11521: 	$uri =~ s-^/adm/wrapper/-/-;
                   11522: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11523:     }
                   11524:     return $uri;
                   11525: }
                   11526: 
1.557     albertel 11527: sub freeze_escape {
                   11528:     my ($value)=@_;
                   11529:     if (ref($value)) {
                   11530: 	$value=&nfreeze($value);
                   11531: 	return '__FROZEN__'.&escape($value);
                   11532:     }
                   11533:     return &escape($value);
                   11534: }
                   11535: 
1.11      www      11536: 
1.557     albertel 11537: sub thaw_unescape {
                   11538:     my ($value)=@_;
                   11539:     if ($value =~ /^__FROZEN__/) {
                   11540: 	substr($value,0,10,undef);
                   11541: 	$value=&unescape($value);
                   11542: 	return &thaw($value);
                   11543:     }
                   11544:     return &unescape($value);
                   11545: }
                   11546: 
1.436     albertel 11547: sub correct_line_ends {
                   11548:     my ($result)=@_;
                   11549:     $$result =~s/\r\n/\n/mg;
                   11550:     $$result =~s/\r/\n/mg;
1.415     albertel 11551: }
1.1       albertel 11552: # ================================================================ Main Program
                   11553: 
1.184     www      11554: sub goodbye {
1.204     albertel 11555:    &logthis("Starting Shut down");
1.443     albertel 11556: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11557:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11558: #converted
1.599     albertel 11559: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11560:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11561: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11562: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11563: #1.1 only
1.870     albertel 11564: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11565: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11566: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11567: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11568:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11569:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11570:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11571:    &flushcourselogs();
                   11572:    &logthis("Shutting down");
                   11573: }
                   11574: 
1.852     albertel 11575: sub get_dns {
1.1210    raeburn  11576:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11577:     if (!$ignore_cache) {
                   11578: 	my ($content,$cached)=
                   11579: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11580: 	if ($cached) {
1.1210    raeburn  11581: 	    &$func($content,$hashref);
1.869     albertel 11582: 	    return;
                   11583: 	}
                   11584:     }
                   11585: 
                   11586:     my %alldns;
1.852     albertel 11587:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11588:     foreach my $dns (<$config>) {
                   11589: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11590:         my $line = $1;
                   11591:         my ($host,$protocol) = split(/:/,$line);
                   11592:         if ($protocol ne 'https') {
                   11593:             $protocol = 'http';
                   11594:         }
                   11595: 	$alldns{$host} = $protocol;
1.869     albertel 11596:     }
                   11597:     while (%alldns) {
                   11598: 	my ($dns) = keys(%alldns);
1.852     albertel 11599: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11600:         $ua->timeout(30);
1.979     raeburn  11601: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11602: 	my $response=$ua->request($request);
1.979     raeburn  11603:         delete($alldns{$dns});
1.852     albertel 11604: 	next if ($response->is_error());
                   11605: 	my @content = split("\n",$response->content);
1.1210    raeburn  11606: 	unless ($nocache) {
                   11607: 	    &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
                   11608: 	}
                   11609: 	&$func(\@content,$hashref);
1.869     albertel 11610: 	return;
1.852     albertel 11611:     }
                   11612:     close($config);
1.871     albertel 11613:     my $which = (split('/',$url))[3];
                   11614:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11615:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11616:     my @content = <$config>;
1.1210    raeburn  11617:     &$func(\@content,$hashref);
                   11618:     return;
                   11619: }
                   11620: 
                   11621: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11622: sub parse_dns_checksums_tab {
1.1210    raeburn  11623:     my ($lines,$hashref) = @_;
                   11624:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11625:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11626:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11627:     my (%chksum,%revnum);
                   11628:     if (ref($lines) eq 'ARRAY') {
                   11629:         chomp(@{$lines});
                   11630:         my $versions = shift(@{$lines});
                   11631:         my %supported;
                   11632:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11633:             my $releaseslist = $1;
                   11634:             if ($releaseslist =~ /,/) {
                   11635:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11636:             } elsif ($releaseslist) {
                   11637:                 $supported{$releaseslist} = 1;
                   11638:             }
                   11639:         }
                   11640:         if ($supported{$release}) {  
                   11641:             my $matchthis = 0;
                   11642:             foreach my $line (@{$lines}) {
                   11643:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11644:                     if ($matchthis) {
                   11645:                         last;
                   11646:                     } elsif ($1 eq $release) {
                   11647:                         $matchthis = 1;
                   11648:                     }
                   11649:                 } elsif ($matchthis) {
                   11650:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11651:                     $chksum{$file} = $shasum;
                   11652:                     $revnum{$file} = $version;
                   11653:                 }
                   11654:             }
                   11655:             if (ref($hashref) eq 'HASH') {
                   11656:                 %{$hashref} = (
                   11657:                                 sums     => \%chksum,
                   11658:                                 versions => \%revnum,
                   11659:                               );
                   11660:             }
                   11661:         }
                   11662:     }
1.869     albertel 11663:     return;
1.852     albertel 11664: }
1.1210    raeburn  11665: 
                   11666: sub fetch_dns_checksums {
                   11667:     my %checksums; 
1.1211    raeburn  11668:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11669:              \%checksums);
1.1210    raeburn  11670:     return \%checksums;
                   11671: }
                   11672: 
1.327     albertel 11673: # ------------------------------------------------------------ Read domain file
                   11674: {
1.852     albertel 11675:     my $loaded;
1.846     albertel 11676:     my %domain;
                   11677: 
1.852     albertel 11678:     sub parse_domain_tab {
                   11679: 	my ($lines) = @_;
                   11680: 	foreach my $line (@$lines) {
                   11681: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11682: 
1.846     albertel 11683: 	    chomp($line);
1.852     albertel 11684: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11685: 	    my %this_domain;
                   11686: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11687: 			       'lang_def', 'city', 'longi', 'lati',
                   11688: 			       'primary') {
                   11689: 		$this_domain{$field} = shift(@elements);
                   11690: 	    }
                   11691: 	    $domain{$name} = \%this_domain;
1.852     albertel 11692: 	}
                   11693:     }
1.864     albertel 11694: 
                   11695:     sub reset_domain_info {
                   11696: 	undef($loaded);
                   11697: 	undef(%domain);
                   11698:     }
                   11699: 
1.852     albertel 11700:     sub load_domain_tab {
1.869     albertel 11701: 	my ($ignore_cache) = @_;
                   11702: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11703: 	my $fh;
                   11704: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11705: 	    my @lines = <$fh>;
                   11706: 	    &parse_domain_tab(\@lines);
1.448     albertel 11707: 	}
1.852     albertel 11708: 	close($fh);
                   11709: 	$loaded = 1;
1.327     albertel 11710:     }
1.846     albertel 11711: 
                   11712:     sub domain {
1.852     albertel 11713: 	&load_domain_tab() if (!$loaded);
                   11714: 
1.846     albertel 11715: 	my ($name,$what) = @_;
                   11716: 	return if ( !exists($domain{$name}) );
                   11717: 
                   11718: 	if (!$what) {
                   11719: 	    return $domain{$name}{'description'};
                   11720: 	}
                   11721: 	return $domain{$name}{$what};
                   11722:     }
1.974     raeburn  11723: 
                   11724:     sub domain_info {
                   11725:         &load_domain_tab() if (!$loaded);
                   11726:         return %domain;
                   11727:     }
                   11728: 
1.327     albertel 11729: }
                   11730: 
                   11731: 
1.1       albertel 11732: # ------------------------------------------------------------- Read hosts file
                   11733: {
1.838     albertel 11734:     my %hostname;
1.844     albertel 11735:     my %hostdom;
1.845     albertel 11736:     my %libserv;
1.852     albertel 11737:     my $loaded;
1.888     albertel 11738:     my %name_to_host;
1.1074    raeburn  11739:     my %internetdom;
1.1107    raeburn  11740:     my %LC_dns_serv;
1.852     albertel 11741: 
                   11742:     sub parse_hosts_tab {
                   11743: 	my ($file) = @_;
                   11744: 	foreach my $configline (@$file) {
                   11745: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11746:             chomp($configline);
                   11747: 	    if ($configline =~ /^\^/) {
                   11748:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11749:                     $LC_dns_serv{$1} = 1;
                   11750:                 }
                   11751:                 next;
                   11752:             }
1.1074    raeburn  11753: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11754: 	    $name=~s/\s//g;
                   11755: 	    if ($id && $domain && $role && $name) {
                   11756: 		$hostname{$id}=$name;
1.888     albertel 11757: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11758: 		$hostdom{$id}=$domain;
                   11759: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11760:                 if (defined($protocol)) {
                   11761:                     if ($protocol eq 'https') {
                   11762:                         $protocol{$id} = $protocol;
                   11763:                     } else {
                   11764:                         $protocol{$id} = 'http'; 
                   11765:                     }
1.968     raeburn  11766:                 } else {
1.969     raeburn  11767:                     $protocol{$id} = 'http';
1.968     raeburn  11768:                 }
1.1074    raeburn  11769:                 if (defined($intdom)) {
                   11770:                     $internetdom{$id} = $intdom;
                   11771:                 }
1.852     albertel 11772: 	    }
                   11773: 	}
                   11774:     }
1.864     albertel 11775:     
                   11776:     sub reset_hosts_info {
1.897     albertel 11777: 	&purge_remembered();
1.864     albertel 11778: 	&reset_domain_info();
                   11779: 	&reset_hosts_ip_info();
1.892     albertel 11780: 	undef(%name_to_host);
1.864     albertel 11781: 	undef(%hostname);
                   11782: 	undef(%hostdom);
                   11783: 	undef(%libserv);
                   11784: 	undef($loaded);
                   11785:     }
1.1       albertel 11786: 
1.852     albertel 11787:     sub load_hosts_tab {
1.869     albertel 11788: 	my ($ignore_cache) = @_;
                   11789: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11790: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11791: 	my @config = <$config>;
                   11792: 	&parse_hosts_tab(\@config);
                   11793: 	close($config);
                   11794: 	$loaded=1;
1.1       albertel 11795:     }
1.852     albertel 11796: 
1.838     albertel 11797:     sub hostname {
1.852     albertel 11798: 	&load_hosts_tab() if (!$loaded);
                   11799: 
1.838     albertel 11800: 	my ($lonid) = @_;
                   11801: 	return $hostname{$lonid};
                   11802:     }
1.845     albertel 11803: 
1.838     albertel 11804:     sub all_hostnames {
1.852     albertel 11805: 	&load_hosts_tab() if (!$loaded);
                   11806: 
1.838     albertel 11807: 	return %hostname;
                   11808:     }
1.845     albertel 11809: 
1.888     albertel 11810:     sub all_names {
                   11811: 	&load_hosts_tab() if (!$loaded);
                   11812: 
                   11813: 	return %name_to_host;
                   11814:     }
                   11815: 
1.974     raeburn  11816:     sub all_host_domain {
                   11817:         &load_hosts_tab() if (!$loaded);
                   11818:         return %hostdom;
                   11819:     }
                   11820: 
1.845     albertel 11821:     sub is_library {
1.852     albertel 11822: 	&load_hosts_tab() if (!$loaded);
                   11823: 
1.845     albertel 11824: 	return exists($libserv{$_[0]});
                   11825:     }
                   11826: 
                   11827:     sub all_library {
1.852     albertel 11828: 	&load_hosts_tab() if (!$loaded);
                   11829: 
1.845     albertel 11830: 	return %libserv;
                   11831:     }
                   11832: 
1.1062    droeschl 11833:     sub unique_library {
                   11834: 	#2x reverse removes all hostnames that appear more than once
                   11835:         my %unique = reverse &all_library();
                   11836:         return reverse %unique;
                   11837:     }
                   11838: 
1.841     albertel 11839:     sub get_servers {
1.852     albertel 11840: 	&load_hosts_tab() if (!$loaded);
                   11841: 
1.841     albertel 11842: 	my ($domain,$type) = @_;
                   11843: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11844: 	                                          : %hostname;
                   11845: 	my %result;
1.842     albertel 11846: 	if (ref($domain) eq 'ARRAY') {
                   11847: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11848: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11849: 		    $result{$host} = $hostname;
                   11850: 		}
                   11851: 	    }
                   11852: 	} else {
                   11853: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11854: 		if ($hostdom{$host} eq $domain) {
                   11855: 		    $result{$host} = $hostname;
                   11856: 		}
1.841     albertel 11857: 	    }
                   11858: 	}
                   11859: 	return %result;
                   11860:     }
1.845     albertel 11861: 
1.1062    droeschl 11862:     sub get_unique_servers {
                   11863:         my %unique = reverse &get_servers(@_);
                   11864: 	return reverse %unique;
                   11865:     }
                   11866: 
1.844     albertel 11867:     sub host_domain {
1.852     albertel 11868: 	&load_hosts_tab() if (!$loaded);
                   11869: 
1.844     albertel 11870: 	my ($lonid) = @_;
                   11871: 	return $hostdom{$lonid};
                   11872:     }
                   11873: 
1.841     albertel 11874:     sub all_domains {
1.852     albertel 11875: 	&load_hosts_tab() if (!$loaded);
                   11876: 
1.841     albertel 11877: 	my %seen;
                   11878: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11879: 	return @uniq;
                   11880:     }
1.1074    raeburn  11881: 
                   11882:     sub internet_dom {
                   11883:         &load_hosts_tab() if (!$loaded);
                   11884: 
                   11885:         my ($lonid) = @_;
                   11886:         return $internetdom{$lonid};
                   11887:     }
1.1107    raeburn  11888: 
                   11889:     sub is_LC_dns {
                   11890:         &load_hosts_tab() if (!$loaded);
                   11891: 
                   11892:         my ($hostname) = @_;
                   11893:         return exists($LC_dns_serv{$hostname});
                   11894:     }
                   11895: 
1.1       albertel 11896: }
                   11897: 
1.847     albertel 11898: { 
                   11899:     my %iphost;
1.856     albertel 11900:     my %name_to_ip;
                   11901:     my %lonid_to_ip;
1.869     albertel 11902: 
1.847     albertel 11903:     sub get_hosts_from_ip {
                   11904: 	my ($ip) = @_;
                   11905: 	my %iphosts = &get_iphost();
                   11906: 	if (ref($iphosts{$ip})) {
                   11907: 	    return @{$iphosts{$ip}};
                   11908: 	}
                   11909: 	return;
1.839     albertel 11910:     }
1.864     albertel 11911:     
                   11912:     sub reset_hosts_ip_info {
                   11913: 	undef(%iphost);
                   11914: 	undef(%name_to_ip);
                   11915: 	undef(%lonid_to_ip);
                   11916:     }
1.856     albertel 11917: 
                   11918:     sub get_host_ip {
                   11919: 	my ($lonid) = @_;
                   11920: 	if (exists($lonid_to_ip{$lonid})) {
                   11921: 	    return $lonid_to_ip{$lonid};
                   11922: 	}
                   11923: 	my $name=&hostname($lonid);
                   11924:    	my $ip = gethostbyname($name);
                   11925: 	return if (!$ip || length($ip) ne 4);
                   11926: 	$ip=inet_ntoa($ip);
                   11927: 	$name_to_ip{$name}   = $ip;
                   11928: 	$lonid_to_ip{$lonid} = $ip;
                   11929: 	return $ip;
                   11930:     }
1.847     albertel 11931:     
                   11932:     sub get_iphost {
1.869     albertel 11933: 	my ($ignore_cache) = @_;
1.894     albertel 11934: 
1.869     albertel 11935: 	if (!$ignore_cache) {
                   11936: 	    if (%iphost) {
                   11937: 		return %iphost;
                   11938: 	    }
                   11939: 	    my ($ip_info,$cached)=
                   11940: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11941: 	    if ($cached) {
                   11942: 		%iphost      = %{$ip_info->[0]};
                   11943: 		%name_to_ip  = %{$ip_info->[1]};
                   11944: 		%lonid_to_ip = %{$ip_info->[2]};
                   11945: 		return %iphost;
                   11946: 	    }
                   11947: 	}
1.894     albertel 11948: 
                   11949: 	# get yesterday's info for fallback
                   11950: 	my %old_name_to_ip;
                   11951: 	my ($ip_info,$cached)=
                   11952: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11953: 	if ($cached) {
                   11954: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11955: 	}
                   11956: 
1.888     albertel 11957: 	my %name_to_host = &all_names();
                   11958: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11959: 	    my $ip;
                   11960: 	    if (!exists($name_to_ip{$name})) {
                   11961: 		$ip = gethostbyname($name);
                   11962: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11963: 		    if (defined($old_name_to_ip{$name})) {
                   11964: 			$ip = $old_name_to_ip{$name};
                   11965: 			&logthis("Can't find $name defaulting to old $ip");
                   11966: 		    } else {
                   11967: 			&logthis("Name $name no IP found");
                   11968: 			next;
                   11969: 		    }
                   11970: 		} else {
                   11971: 		    $ip=inet_ntoa($ip);
1.847     albertel 11972: 		}
                   11973: 		$name_to_ip{$name} = $ip;
                   11974: 	    } else {
                   11975: 		$ip = $name_to_ip{$name};
1.653     albertel 11976: 	    }
1.888     albertel 11977: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11978: 		$lonid_to_ip{$id} = $ip;
                   11979: 	    }
                   11980: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11981: 	}
1.869     albertel 11982: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11983: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11984: 				      48*60*60);
1.869     albertel 11985: 
1.847     albertel 11986: 	return %iphost;
1.598     albertel 11987:     }
                   11988: 
1.992     raeburn  11989:     #
                   11990:     #  Given a DNS returns the loncapa host name for that DNS 
                   11991:     # 
                   11992:     sub host_from_dns {
                   11993:         my ($dns) = @_;
                   11994:         my @hosts;
                   11995:         my $ip;
                   11996: 
1.993     raeburn  11997:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11998:             $ip = $name_to_ip{$dns};
                   11999:         }
                   12000:         if (!$ip) {
                   12001:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12002:             if (length($ip) == 4) { 
                   12003: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12004:             }
                   12005:         }
                   12006:         if ($ip) {
                   12007: 	    @hosts = get_hosts_from_ip($ip);
                   12008: 	    return $hosts[0];
                   12009:         }
                   12010:         return undef;
1.986     foxr     12011:     }
1.992     raeburn  12012: 
1.1074    raeburn  12013:     sub get_internet_names {
                   12014:         my ($lonid) = @_;
                   12015:         return if ($lonid eq '');
                   12016:         my ($idnref,$cached)=
                   12017:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12018:         if ($cached) {
                   12019:             return $idnref;
                   12020:         }
                   12021:         my $ip = &get_host_ip($lonid);
                   12022:         my @hosts = &get_hosts_from_ip($ip);
                   12023:         my %iphost = &get_iphost();
                   12024:         my (@idns,%seen);
                   12025:         foreach my $id (@hosts) {
                   12026:             my $dom = &host_domain($id);
                   12027:             my $prim_id = &domain($dom,'primary');
                   12028:             my $prim_ip = &get_host_ip($prim_id);
                   12029:             next if ($seen{$prim_ip});
                   12030:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12031:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12032:                     my $intdom = &internet_dom($id);
                   12033:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12034:                         push(@idns,$intdom);
                   12035:                     }
                   12036:                 }
                   12037:             }
                   12038:             $seen{$prim_ip} = 1;
                   12039:         }
                   12040:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   12041:     }
                   12042: 
1.986     foxr     12043: }
                   12044: 
1.1079    raeburn  12045: sub all_loncaparevs {
                   12046:     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);
                   12047: }
                   12048: 
1.862     albertel 12049: BEGIN {
                   12050: 
                   12051: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12052:     unless ($readit) {
                   12053: {
                   12054:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12055:     %perlvar = (%perlvar,%{$configvars});
                   12056: }
                   12057: 
                   12058: 
1.1       albertel 12059: # ------------------------------------------------------ Read spare server file
                   12060: {
1.448     albertel 12061:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12062: 
                   12063:     while (my $configline=<$config>) {
                   12064:        chomp($configline);
1.284     matthew  12065:        if ($configline) {
1.784     albertel 12066: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12067: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12068: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12069:        }
                   12070:     }
1.448     albertel 12071:     close($config);
1.1       albertel 12072: }
1.11      www      12073: # ------------------------------------------------------------ Read permissions
                   12074: {
1.448     albertel 12075:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12076: 
                   12077:     while (my $configline=<$config>) {
1.448     albertel 12078: 	chomp($configline);
                   12079: 	if ($configline) {
                   12080: 	    my ($role,$perm)=split(/ /,$configline);
                   12081: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12082: 	}
1.11      www      12083:     }
1.448     albertel 12084:     close($config);
1.11      www      12085: }
                   12086: 
                   12087: # -------------------------------------------- Read plain texts for permissions
                   12088: {
1.448     albertel 12089:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12090: 
                   12091:     while (my $configline=<$config>) {
1.448     albertel 12092: 	chomp($configline);
                   12093: 	if ($configline) {
1.742     raeburn  12094: 	    my ($short,@plain)=split(/:/,$configline);
                   12095:             %{$prp{$short}} = ();
                   12096: 	    if (@plain > 0) {
                   12097:                 $prp{$short}{'std'} = $plain[0];
                   12098:                 for (my $i=1; $i<@plain; $i++) {
                   12099:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12100:                 }
                   12101:             }
1.448     albertel 12102: 	}
1.135     www      12103:     }
1.448     albertel 12104:     close($config);
1.135     www      12105: }
                   12106: 
                   12107: # ---------------------------------------------------------- Read package table
                   12108: {
1.448     albertel 12109:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12110: 
                   12111:     while (my $configline=<$config>) {
1.483     albertel 12112: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12113: 	chomp($configline);
                   12114: 	my ($short,$plain)=split(/:/,$configline);
                   12115: 	my ($pack,$name)=split(/\&/,$short);
                   12116: 	if ($plain ne '') {
                   12117: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12118: 	    $packagetab{$short}=$plain; 
                   12119: 	}
1.11      www      12120:     }
1.448     albertel 12121:     close($config);
1.329     matthew  12122: }
                   12123: 
1.1073    raeburn  12124: # ---------------------------------------------------------- Read loncaparev table
                   12125: {
                   12126:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12127:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12128:             while (my $configline=<$config>) {
                   12129:                 chomp($configline);
                   12130:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12131:                 $loncaparevs{$hostid}=$loncaparev;
                   12132:             }
                   12133:             close($config);
                   12134:         }
                   12135:     }
                   12136: }
                   12137: 
1.1074    raeburn  12138: # ---------------------------------------------------------- Read serverhostID table
                   12139: {
                   12140:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12141:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12142:             while (my $configline=<$config>) {
                   12143:                 chomp($configline);
                   12144:                 my ($name,$id)=split(/:/,$configline);
                   12145:                 $serverhomeIDs{$name}=$id;
                   12146:             }
                   12147:             close($config);
                   12148:         }
                   12149:     }
                   12150: }
                   12151: 
1.1079    raeburn  12152: {
                   12153:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12154:     if (-e $file) {
                   12155:         my $parser = HTML::LCParser->new($file);
                   12156:         while (my $token = $parser->get_token()) {
                   12157:             if ($token->[0] eq 'S') {
                   12158:                 my $item = $token->[1];
                   12159:                 my $name = $token->[2]{'name'};
                   12160:                 my $value = $token->[2]{'value'};
                   12161:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12162:                     my $release = $parser->get_text();
                   12163:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12164:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12165:                 }
                   12166:             }
                   12167:         }
                   12168:     }
1.1073    raeburn  12169: }
                   12170: 
1.1138    raeburn  12171: # ---------------------------------------------------------- Read managers table
                   12172: {
                   12173:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12174:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12175:             while (my $configline=<$config>) {
                   12176:                 chomp($configline);
                   12177:                 next if ($configline =~ /^\#/);
                   12178:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12179:                     $managerstab{$configline} = 1;
                   12180:                 }
                   12181:             }
                   12182:             close($config);
                   12183:         }
                   12184:     }
                   12185: }
                   12186: 
1.329     matthew  12187: # ------------- set up temporary directory
                   12188: {
1.1117    foxr     12189:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12190: 
1.11      www      12191: }
                   12192: 
1.794     albertel 12193: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12194: 				'compress_threshold'=> 20_000,
                   12195:  			        });
1.185     www      12196: 
1.281     www      12197: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12198: $dumpcount=0;
1.958     www      12199: $locknum=0;
1.22      www      12200: 
1.163     harris41 12201: &logtouch();
1.672     albertel 12202: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12203: $readit=1;
1.564     albertel 12204:     {
                   12205: 	use integer;
                   12206: 	my $test=(2**32)+1;
1.568     albertel 12207: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12208: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12209:     }
1.1214    raeburn  12210: 
                   12211:     {
                   12212:         eval {
                   12213:             ($apache) =
                   12214:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12215:         };
                   12216:         if ($@) {
                   12217:            $apache = 1.3;
1.1213    raeburn  12218:         }
                   12219:     }
1.1214    raeburn  12220: 
1.195     www      12221: }
1.1       albertel 12222: }
1.179     www      12223: 
1.1       albertel 12224: 1;
1.191     harris41 12225: __END__
                   12226: 
1.243     albertel 12227: =pod
                   12228: 
1.191     harris41 12229: =head1 NAME
                   12230: 
1.243     albertel 12231: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12232: 
                   12233: =head1 SYNOPSIS
                   12234: 
1.243     albertel 12235: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12236: 
                   12237:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12238: 
1.243     albertel 12239: Common parameters:
                   12240: 
                   12241: =over 4
                   12242: 
                   12243: =item *
                   12244: 
                   12245: $uname : an internal username (if $cname expecting a course Id specifically)
                   12246: 
                   12247: =item *
                   12248: 
                   12249: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12250: 
                   12251: =item *
                   12252: 
                   12253: $symb : a resource instance identifier
                   12254: 
                   12255: =item *
                   12256: 
                   12257: $namespace : the name of a .db file that contains the data needed or
                   12258: being set.
                   12259: 
                   12260: =back
                   12261: 
1.394     bowersj2 12262: =head1 OVERVIEW
1.191     harris41 12263: 
1.394     bowersj2 12264: lonnet provides subroutines which interact with the
                   12265: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12266: about classes, users, and resources.
1.243     albertel 12267: 
                   12268: For many of these objects you can also use this to store data about
                   12269: them or modify them in various ways.
1.191     harris41 12270: 
1.394     bowersj2 12271: =head2 Symbs
1.191     harris41 12272: 
1.394     bowersj2 12273: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12274: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12275: map, the resource number of the resource in the map, and the URL of
                   12276: the resource itself. The latter is somewhat redundant, but might help
                   12277: if maps change.
                   12278: 
                   12279: An example is
                   12280: 
                   12281:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12282: 
                   12283: The respective map entry is
                   12284: 
                   12285:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12286:   title="Problem 2">
                   12287:  </resource>
                   12288: 
                   12289: Symbs are used by the random number generator, as well as to store and
                   12290: restore data specific to a certain instance of for example a problem.
                   12291: 
                   12292: =head2 Storing And Retrieving Data
                   12293: 
                   12294: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12295: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12296: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12297: is is the non-critical message twin of cstore. These functions are for
                   12298: handlers to store a perl hash to a user's permanent data space in an
                   12299: easy manner, and to retrieve it again on another call. It is expected
                   12300: that a handler would use this once at the beginning to retrieve data,
                   12301: and then again once at the end to send only the new data back.
                   12302: 
                   12303: The data is stored in the user's data directory on the user's
                   12304: homeserver under the ID of the course.
                   12305: 
                   12306: The hash that is returned by restore will have all of the previous
                   12307: value for all of the elements of the hash.
                   12308: 
                   12309: Example:
                   12310: 
                   12311:  #creating a hash
                   12312:  my %hash;
                   12313:  $hash{'foo'}='bar';
                   12314: 
                   12315:  #storing it
                   12316:  &Apache::lonnet::cstore(\%hash);
                   12317: 
                   12318:  #changing a value
                   12319:  $hash{'foo'}='notbar';
                   12320: 
                   12321:  #adding a new value
                   12322:  $hash{'bar'}='foo';
                   12323:  &Apache::lonnet::cstore(\%hash);
                   12324: 
                   12325:  #retrieving the hash
                   12326:  my %history=&Apache::lonnet::restore();
                   12327: 
                   12328:  #print the hash
                   12329:  foreach my $key (sort(keys(%history))) {
                   12330:    print("\%history{$key} = $history{$key}");
                   12331:  }
                   12332: 
                   12333: Will print out:
1.191     harris41 12334: 
1.394     bowersj2 12335:  %history{1:foo} = bar
                   12336:  %history{1:keys} = foo:timestamp
                   12337:  %history{1:timestamp} = 990455579
                   12338:  %history{2:bar} = foo
                   12339:  %history{2:foo} = notbar
                   12340:  %history{2:keys} = foo:bar:timestamp
                   12341:  %history{2:timestamp} = 990455580
                   12342:  %history{bar} = foo
                   12343:  %history{foo} = notbar
                   12344:  %history{timestamp} = 990455580
                   12345:  %history{version} = 2
                   12346: 
                   12347: Note that the special hash entries C<keys>, C<version> and
                   12348: C<timestamp> were added to the hash. C<version> will be equal to the
                   12349: total number of versions of the data that have been stored. The
                   12350: C<timestamp> attribute will be the UNIX time the hash was
                   12351: stored. C<keys> is available in every historical section to list which
                   12352: keys were added or changed at a specific historical revision of a
                   12353: hash.
                   12354: 
                   12355: B<Warning>: do not store the hash that restore returns directly. This
                   12356: will cause a mess since it will restore the historical keys as if the
                   12357: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12358: 
1.394     bowersj2 12359: Calling convention:
1.191     harris41 12360: 
1.394     bowersj2 12361:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12362:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12363: 
1.394     bowersj2 12364: For more detailed information, see lonnet specific documentation.
1.191     harris41 12365: 
1.394     bowersj2 12366: =head1 RETURN MESSAGES
1.191     harris41 12367: 
1.394     bowersj2 12368: =over 4
1.191     harris41 12369: 
1.394     bowersj2 12370: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12371: 
1.394     bowersj2 12372: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12373: when the connection is brought back up
1.191     harris41 12374: 
1.394     bowersj2 12375: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12376: for later delivery
1.191     harris41 12377: 
1.967     bisitz   12378: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12379: 
1.394     bowersj2 12380: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12381: that was requested
1.191     harris41 12382: 
1.243     albertel 12383: =back
1.191     harris41 12384: 
1.243     albertel 12385: =head1 PUBLIC SUBROUTINES
1.191     harris41 12386: 
1.243     albertel 12387: =head2 Session Environment Functions
1.191     harris41 12388: 
1.243     albertel 12389: =over 4
1.191     harris41 12390: 
1.394     bowersj2 12391: =item * 
                   12392: X<appenv()>
1.949     raeburn  12393: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12394: the user envirnoment file, and will be restored for each access this
1.620     albertel 12395: user makes during this session, also modifies the %env for the current
1.949     raeburn  12396: process. Optional rolesarrayref - if defined contains a reference to an array
                   12397: of roles which are exempt from the restriction on modifying user.role entries 
                   12398: in the user's environment.db and in %env.    
1.191     harris41 12399: 
                   12400: =item *
1.394     bowersj2 12401: X<delenv()>
1.987     raeburn  12402: B<delenv($delthis,$regexp)>: removes all items from the session
                   12403: environment file that begin with $delthis. If the 
                   12404: optional second arg - $regexp - is true, $delthis is treated as a 
                   12405: regular expression, otherwise \Q$delthis\E is used. 
                   12406: The values are also deleted from the current processes %env.
1.191     harris41 12407: 
1.795     albertel 12408: =item * get_env_multiple($name) 
                   12409: 
                   12410: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12411: values may be defined and end up as an array ref.
                   12412: 
                   12413: returns an array of values
                   12414: 
1.243     albertel 12415: =back
                   12416: 
                   12417: =head2 User Information
1.191     harris41 12418: 
1.243     albertel 12419: =over 4
1.191     harris41 12420: 
                   12421: =item *
1.394     bowersj2 12422: X<queryauthenticate()>
                   12423: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12424: authentication scheme
                   12425: 
                   12426: =item *
1.394     bowersj2 12427: X<authenticate()>
1.1073    raeburn  12428: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12429: authenticate user from domain's lib servers (first use the current
                   12430: one). C<$upass> should be the users password.
1.1073    raeburn  12431: $checkdefauth is optional (value is 1 if a check should be made to
                   12432:    authenticate user using default authentication method, and allow
                   12433:    account creation if username does not have account in the domain).
                   12434: $clientcancheckhost is optional (value is 1 if checking whether the
                   12435:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12436: 
                   12437: =item *
1.394     bowersj2 12438: X<homeserver()>
                   12439: B<homeserver($uname,$udom)>: find the server which has
                   12440: the user's directory and files (there must be only one), this caches
                   12441: the answer, and also caches if there is a borken connection.
1.191     harris41 12442: 
                   12443: =item *
1.394     bowersj2 12444: X<idget()>
                   12445: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12446: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12447: username, and only 1 username per ID in a specific domain) (returns
                   12448: hash: id=>name,id=>name)
1.191     harris41 12449: 
                   12450: =item *
1.394     bowersj2 12451: X<idrget()>
                   12452: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12453: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12454: 
                   12455: =item *
1.394     bowersj2 12456: X<idput()>
                   12457: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12458: 
                   12459: =item *
1.394     bowersj2 12460: X<rolesinit()>
1.1169    droeschl 12461: B<rolesinit($udom,$username)>: get user privileges.
                   12462: returns user role, first access and timer interval hashes
1.243     albertel 12463: 
                   12464: =item *
1.1171    droeschl 12465: X<privileged()>
                   12466: B<privileged($username,$domain)>: returns a true if user has a
                   12467: privileged and active role (i.e. su or dc), false otherwise.
                   12468: 
                   12469: =item *
1.551     albertel 12470: X<getsection()>
                   12471: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12472: course $cname, return section name/number or '' for "not in course"
                   12473: and '-1' for "no section"
                   12474: 
                   12475: =item *
1.394     bowersj2 12476: X<userenvironment()>
                   12477: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12478: passed in @what from the requested user's environment, returns a hash
                   12479: 
1.858     raeburn  12480: =item * 
                   12481: X<userlog_query()>
1.859     albertel 12482: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12483: activity.log file. %filters defines filters applied when parsing the
                   12484: log file. These can be start or end timestamps, or the type of action
                   12485: - log to look for Login or Logout events, check for Checkin or
                   12486: Checkout, role for role selection. The response is in the form
                   12487: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12488: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12489: 
1.243     albertel 12490: =back
                   12491: 
                   12492: =head2 User Roles
                   12493: 
                   12494: =over 4
                   12495: 
                   12496: =item *
                   12497: 
1.810     raeburn  12498: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12499:  F: full access
                   12500:  U,I,K: authentication modes (cxx only)
                   12501:  '': forbidden
                   12502:  1: user needs to choose course
                   12503:  2: browse allowed
1.766     albertel 12504:  A: passphrase authentication needed
1.243     albertel 12505: 
                   12506: =item *
                   12507: 
1.1192    raeburn  12508: constructaccess($url,$setpriv) : check for access to construction space URL
                   12509: 
                   12510: See if the owner domain and name in the URL match those in the
                   12511: expected environment.  If so, return three element list
                   12512: ($ownername,$ownerdomain,$ownerhome).
                   12513: 
                   12514: Otherwise return the null string.
                   12515: 
                   12516: If second argument 'setpriv' is true, it assigns the privileges,
                   12517: and returns the same three element list, unless the owner has
                   12518: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12519: in which case the null string is returned.
                   12520: 
                   12521: =item *
                   12522: 
1.243     albertel 12523: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12524: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12525: and course level
                   12526: 
                   12527: =item *
                   12528: 
1.988     raeburn  12529: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12530: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12531: $type is Course (default) or Community.
1.988     raeburn  12532: If $forcedefault evaluates to true, text returned will be default 
                   12533: text for $type. Otherwise, if this is a course, the text returned 
                   12534: will be a custom name for the role (if defined in the course's 
                   12535: environment).  If no custom name is defined the default is returned.
                   12536:    
1.832     raeburn  12537: =item *
                   12538: 
1.935     raeburn  12539: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12540: All arguments are optional. Returns a hash of a roles, either for
                   12541: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12542: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12543: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12544: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12545: For each key, value is set to colon-separated start and end times for
                   12546: the role.  If no username and domain are specified, will default to
1.934     raeburn  12547: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12548: of role statuses (active, future or previous), roles 
                   12549: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12550: to restrict the list of roles reported. If no array ref is 
                   12551: provided for types, will default to return only active roles.
1.834     albertel 12552: 
1.1195    raeburn  12553: =item *
                   12554: 
                   12555: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12556: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12557: 
                   12558: Additional optional arguments are: $type (if role checking is to be restricted 
                   12559: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12560: available roles) or future (roles available in the future), and
                   12561: $hideprivileged -- if true will not report course roles for users who
                   12562: have active Domain Coordinator or Super User roles.
                   12563: 
1.243     albertel 12564: =back
                   12565: 
                   12566: =head2 User Modification
                   12567: 
                   12568: =over 4
                   12569: 
                   12570: =item *
                   12571: 
1.957     raeburn  12572: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12573: user for the level given by URL.  Optional start and end dates (leave empty
                   12574: string or zero for "no date")
1.191     harris41 12575: 
                   12576: =item *
                   12577: 
1.243     albertel 12578: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12579: change a users, password, possible return values are: ok,
                   12580: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12581: refused
1.191     harris41 12582: 
                   12583: =item *
                   12584: 
1.243     albertel 12585: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12586: 
                   12587: =item *
                   12588: 
1.1058    raeburn  12589: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12590:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12591: 
                   12592: will update user information (firstname,middlename,lastname,generation,
                   12593: permanentemail), and if forceid is true, student/employee ID also.
                   12594: A user's institutional affiliation(s) can also be updated.
                   12595: User information fields will not be overwritten with empty entries 
                   12596: unless the field is included in the $candelete array reference.
                   12597: This array is included when a single user is modified via "Manage Users",
                   12598: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12599: 
                   12600: =item *
                   12601: 
1.286     matthew  12602: modifystudent
                   12603: 
1.957     raeburn  12604: modify a student's enrollment and identification information.
1.286     matthew  12605: The course id is resolved based on the current users environment.  
                   12606: This means the envoking user must be a course coordinator or otherwise
                   12607: associated with a course.
                   12608: 
1.297     matthew  12609: This call is essentially a wrapper for lonnet::modifyuser and
                   12610: lonnet::modify_student_enrollment
1.286     matthew  12611: 
                   12612: Inputs: 
                   12613: 
                   12614: =over 4
                   12615: 
1.957     raeburn  12616: =item B<$udom> Student's loncapa domain
1.286     matthew  12617: 
1.957     raeburn  12618: =item B<$uname> Student's loncapa login name
1.286     matthew  12619: 
1.964     bisitz   12620: =item B<$uid> Student/Employee ID
1.286     matthew  12621: 
1.957     raeburn  12622: =item B<$umode> Student's authentication mode
1.286     matthew  12623: 
1.957     raeburn  12624: =item B<$upass> Student's password
1.286     matthew  12625: 
1.957     raeburn  12626: =item B<$first> Student's first name
1.286     matthew  12627: 
1.957     raeburn  12628: =item B<$middle> Student's middle name
1.286     matthew  12629: 
1.957     raeburn  12630: =item B<$last> Student's last name
1.286     matthew  12631: 
1.957     raeburn  12632: =item B<$gene> Student's generation
1.286     matthew  12633: 
1.957     raeburn  12634: =item B<$usec> Student's section in course
1.286     matthew  12635: 
                   12636: =item B<$end> Unix time of the roles expiration
                   12637: 
                   12638: =item B<$start> Unix time of the roles start date
                   12639: 
                   12640: =item B<$forceid> If defined, allow $uid to be changed
                   12641: 
                   12642: =item B<$desiredhome> server to use as home server for student
                   12643: 
1.957     raeburn  12644: =item B<$email> Student's permanent e-mail address
                   12645: 
                   12646: =item B<$type> Type of enrollment (auto or manual)
                   12647: 
1.963     raeburn  12648: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12649: 
                   12650: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12651: 
1.963     raeburn  12652: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12653: 
1.963     raeburn  12654: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12655: 
1.1216    raeburn  12656: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12657: 
                   12658: =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  12659: 
1.286     matthew  12660: =back
1.297     matthew  12661: 
                   12662: =item *
                   12663: 
                   12664: modify_student_enrollment
                   12665: 
                   12666: Change a students enrollment status in a class.  The environment variable
                   12667: 'role.request.course' must be defined for this function to proceed.
                   12668: 
                   12669: Inputs:
                   12670: 
                   12671: =over 4
                   12672: 
                   12673: =item $udom, students domain
                   12674: 
                   12675: =item $uname, students name
                   12676: 
                   12677: =item $uid, students user id
                   12678: 
                   12679: =item $first, students first name
                   12680: 
                   12681: =item $middle
                   12682: 
                   12683: =item $last
                   12684: 
                   12685: =item $gene
                   12686: 
                   12687: =item $usec
                   12688: 
                   12689: =item $end
                   12690: 
                   12691: =item $start
                   12692: 
1.957     raeburn  12693: =item $type
                   12694: 
                   12695: =item $locktype
                   12696: 
                   12697: =item $cid
                   12698: 
                   12699: =item $selfenroll
                   12700: 
                   12701: =item $context
                   12702: 
1.1216    raeburn  12703: =item $credits, number of credits student will earn from this class
                   12704: 
1.297     matthew  12705: =back
                   12706: 
1.191     harris41 12707: 
                   12708: =item *
                   12709: 
1.243     albertel 12710: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12711: custom role; give a custom role to a user for the level given by URL.  Specify
                   12712: name and domain of role author, and role name
1.191     harris41 12713: 
                   12714: =item *
                   12715: 
1.243     albertel 12716: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12717: 
                   12718: =item *
                   12719: 
1.243     albertel 12720: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12721: 
                   12722: =back
                   12723: 
                   12724: =head2 Course Infomation
                   12725: 
                   12726: =over 4
1.191     harris41 12727: 
                   12728: =item *
                   12729: 
1.1118    foxr     12730: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12731: specified course id, including all environment settings for the
                   12732: course, the description of the course will be in the hash under the
                   12733: key 'description'
1.191     harris41 12734: 
1.1118    foxr     12735: $options is an optional parameter that if supplied is a hash reference that controls
                   12736: what how this function works.  It has the following key/values:
                   12737: 
                   12738: =over 4
                   12739: 
                   12740: =item freshen_cache
                   12741: 
                   12742: If defined, and the environment cache for the course is valid, it is 
                   12743: returned in the returned hash.
                   12744: 
                   12745: =item one_time
                   12746: 
                   12747: If defined, the last cache time is set to _now_
                   12748: 
                   12749: =item user
                   12750: 
                   12751: If defined, the supplied username is used instead of the current user.
                   12752: 
                   12753: 
                   12754: =back
                   12755: 
1.191     harris41 12756: =item *
                   12757: 
1.624     albertel 12758: resdata($name,$domain,$type,@which) : request for current parameter
                   12759: setting for a specific $type, where $type is either 'course' or 'user',
                   12760: @what should be a list of parameters to ask about. This routine caches
                   12761: answers for 5 minutes.
1.243     albertel 12762: 
1.877     foxr     12763: =item *
                   12764: 
                   12765: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12766: data base, returning a hash that is keyed by the resource name and has
                   12767: values that are the resource value.  I believe that the timestamps and
                   12768: versions are also returned.
                   12769: 
1.243     albertel 12770: =back
                   12771: 
                   12772: =head2 Course Modification
                   12773: 
                   12774: =over 4
1.191     harris41 12775: 
                   12776: =item *
                   12777: 
1.243     albertel 12778: writecoursepref($courseid,%prefs) : write preferences (environment
                   12779: database) for a course
1.191     harris41 12780: 
                   12781: =item *
                   12782: 
1.1011    raeburn  12783: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12784: 
                   12785: =item *
                   12786: 
1.1038    raeburn  12787: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12788: 
1.1167    droeschl 12789: =item *
                   12790: 
                   12791: is_course($courseid), is_course($cdom, $cnum)
                   12792: 
                   12793: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12794: two component version $cdom, $cnum. It checks if the specified course exists.
                   12795: 
                   12796: Returns:
                   12797:     undef if the course doesn't exist, otherwise
                   12798:     in scalar context the combined courseid.
                   12799:     in list context the two components of the course identifier, domain and 
                   12800:     courseid.    
                   12801: 
1.243     albertel 12802: =back
                   12803: 
                   12804: =head2 Resource Subroutines
                   12805: 
                   12806: =over 4
1.191     harris41 12807: 
                   12808: =item *
                   12809: 
1.243     albertel 12810: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12811: 
                   12812: =item *
                   12813: 
1.243     albertel 12814: repcopy($filename) : subscribes to the requested file, and attempts to
                   12815: replicate from the owning library server, Might return
1.607     raeburn  12816: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12817: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12818: resource. Expects the local filesystem pathname
                   12819: (/home/httpd/html/res/....)
                   12820: 
                   12821: =back
                   12822: 
                   12823: =head2 Resource Information
                   12824: 
                   12825: =over 4
1.191     harris41 12826: 
                   12827: =item *
                   12828: 
1.243     albertel 12829: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12830: a vairety of different possible values, $varname should be a request
                   12831: string, and the other parameters can be used to specify who and what
                   12832: one is asking about.
                   12833: 
                   12834: Possible values for $varname are environment.lastname (or other item
                   12835: from the envirnment hash), user.name (or someother aspect about the
                   12836: user), resource.0.maxtries (or some other part and parameter of a
                   12837: resource)
1.204     albertel 12838: 
                   12839: =item *
                   12840: 
1.243     albertel 12841: directcondval($number) : get current value of a condition; reads from a state
                   12842: string
1.204     albertel 12843: 
                   12844: =item *
                   12845: 
1.243     albertel 12846: condval($condidx) : value of condition index based on state
1.204     albertel 12847: 
                   12848: =item *
                   12849: 
1.243     albertel 12850: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12851: resource's metadata, $what should be either a specific key, or either
                   12852: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12853: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12854: 
                   12855: this function automatically caches all requests
1.191     harris41 12856: 
                   12857: =item *
                   12858: 
1.243     albertel 12859: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12860: network of library servers; returns file handle of where SQL and regex results
                   12861: will be stored for query
1.191     harris41 12862: 
                   12863: =item *
                   12864: 
1.243     albertel 12865: symbread($filename) : return symbolic list entry (filename argument optional);
                   12866: returns the data handle
1.191     harris41 12867: 
                   12868: =item *
                   12869: 
1.1190    raeburn  12870: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12871: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12872: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12873: on failure, user must be in a course, as it assumes the existence of
                   12874: the course initial hash, and uses $env('request.course.id'}.  The third
                   12875: arg is an optional reference to a scalar.  If this arg is passed in the 
                   12876: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12877: encrypted; otherwise it will be null.  
1.191     harris41 12878: 
                   12879: =item *
                   12880: 
1.243     albertel 12881: symbclean($symb) : removes versions numbers from a symb, returns the
                   12882: cleaned symb
1.191     harris41 12883: 
                   12884: =item *
                   12885: 
1.243     albertel 12886: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12887: course map, user must be in a course for it to work.
1.191     harris41 12888: 
                   12889: =item *
                   12890: 
1.243     albertel 12891: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12892: 
                   12893: =item *
                   12894: 
1.243     albertel 12895: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12896: a random seed, all arguments are optional, if they aren't sent it uses the
                   12897: environment to derive them. Note: if symb isn't sent and it can't get one
                   12898: from &symbread it will use the current time as its return value
1.191     harris41 12899: 
                   12900: =item *
                   12901: 
1.243     albertel 12902: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12903: unfakeable, receipt
1.191     harris41 12904: 
                   12905: =item *
                   12906: 
1.620     albertel 12907: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12908: 
                   12909: =item *
                   12910: 
1.243     albertel 12911: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12912: 
                   12913: =item *
                   12914: 
1.243     albertel 12915: 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 12916: 
                   12917: =item *
                   12918: 
1.243     albertel 12919: 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 12920: 
                   12921: =item *
                   12922: 
1.243     albertel 12923: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12924: 
                   12925: =item *
                   12926: 
1.243     albertel 12927: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12928: forcing spreadsheet to reevaluate the resource scores next time.
                   12929: 
1.1195    raeburn  12930: =item * 
                   12931: 
1.1196    raeburn  12932: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12933: when viewing in course context.
1.1195    raeburn  12934: 
1.1196    raeburn  12935:  input: six args -- filename (decluttered), course number, course domain,
                   12936:                     url, symb (if registered) and group (if this is a 
                   12937:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  12938: 
1.1196    raeburn  12939:  output: array of five scalars --
1.1195    raeburn  12940:          $cfile -- url for file editing if editable on current server
                   12941:          $home -- homeserver of resource (i.e., for author if published,
                   12942:                                           or course if uploaded.).
                   12943:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  12944:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   12945:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  12946: 
                   12947: =item *
                   12948: 
                   12949: is_course_upload($file,$cnum,$cdom)
                   12950: 
                   12951: Used in course context to determine if current file was uploaded to 
                   12952: the course (i.e., would be found in /userfiles/docs on the course's 
                   12953: homeserver.
                   12954: 
                   12955:   input: 3 args -- filename (decluttered), course number and course domain.
                   12956:   output: boolean -- 1 if file was uploaded.
                   12957: 
1.243     albertel 12958: =back
                   12959: 
                   12960: =head2 Storing/Retreiving Data
                   12961: 
                   12962: =over 4
1.191     harris41 12963: 
                   12964: =item *
                   12965: 
1.243     albertel 12966: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12967: for this url; hashref needs to be given and should be a \%hashname; the
                   12968: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12969: be derived from the env
1.191     harris41 12970: 
                   12971: =item *
                   12972: 
1.243     albertel 12973: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12974: uses critical subroutine
1.191     harris41 12975: 
                   12976: =item *
                   12977: 
1.243     albertel 12978: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12979: all args are optional
1.191     harris41 12980: 
                   12981: =item *
                   12982: 
1.717     albertel 12983: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12984: dumps the complete (or key matching regexp) namespace into a hash
                   12985: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12986: normally &store()ed into
                   12987: 
                   12988: $range should be either an integer '100' (give me the first 100
                   12989:                                            matching records)
                   12990:               or be  two integers sperated by a - with no spaces
                   12991:                  '30-50' (give me the 30th through the 50th matching
                   12992:                           records)
                   12993: 
                   12994: 
                   12995: =item *
                   12996: 
                   12997: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12998: replaces a &store() version of data with a replacement set of data
                   12999: for a particular resource in a namespace passed in the $storehash hash 
                   13000: reference
                   13001: 
                   13002: =item *
                   13003: 
1.243     albertel 13004: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13005: works very similar to store/cstore, but all data is stored in a
                   13006: temporary location and can be reset using tmpreset, $storehash should
                   13007: be a hash reference, returns nothing on success
1.191     harris41 13008: 
                   13009: =item *
                   13010: 
1.243     albertel 13011: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13012: similar to restore, but all data is stored in a temporary location and
                   13013: can be reset using tmpreset. Returns a hash of values on success,
                   13014: error string otherwise.
1.191     harris41 13015: 
                   13016: =item *
                   13017: 
1.243     albertel 13018: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13019: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13020: 
                   13021: =item *
                   13022: 
1.243     albertel 13023: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13024: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13025: 
                   13026: =item *
                   13027: 
1.243     albertel 13028: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13029: namesp ($udom and $uname are optional)
1.191     harris41 13030: 
                   13031: =item *
                   13032: 
1.702     albertel 13033: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13034: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13035: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13036: 
1.702     albertel 13037: $range should be either an integer '100' (give me the first 100
                   13038:                                            matching records)
                   13039:               or be  two integers sperated by a - with no spaces
                   13040:                  '30-50' (give me the 30th through the 50th matching
                   13041:                           records)
1.449     matthew  13042: =item *
                   13043: 
                   13044: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13045: $store can be a scalar, an array reference, or if the amount to be 
                   13046: incremented is > 1, a hash reference.
                   13047: 
                   13048: ($udom and $uname are optional)
1.191     harris41 13049: 
                   13050: =item *
                   13051: 
1.243     albertel 13052: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13053: ($udom and $uname are optional)
1.191     harris41 13054: 
                   13055: =item *
                   13056: 
1.243     albertel 13057: cput($namespace,$storehash,$udom,$uname) : critical put
                   13058: ($udom and $uname are optional)
1.191     harris41 13059: 
                   13060: =item *
                   13061: 
1.748     albertel 13062: newput($namespace,$storehash,$udom,$uname) :
                   13063: 
                   13064: Attempts to store the items in the $storehash, but only if they don't
                   13065: currently exist, if this succeeds you can be certain that you have 
                   13066: successfully created a new key value pair in the $namespace db.
                   13067: 
                   13068: 
                   13069: Args:
                   13070:  $namespace: name of database to store values to
                   13071:  $storehash: hashref to store to the db
                   13072:  $udom: (optional) domain of user containing the db
                   13073:  $uname: (optional) name of user caontaining the db
                   13074: 
                   13075: Returns:
                   13076:  'ok' -> succeeded in storing all keys of $storehash
                   13077:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13078:                         least <key> already existed in the db (other
                   13079:                         requested keys may also already exist)
1.967     bisitz   13080:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13081:  'con_lost' -> unable to contact request server
                   13082:  'refused' -> action was not allowed by remote machine
                   13083: 
                   13084: 
                   13085: =item *
                   13086: 
1.243     albertel 13087: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13088: reference filled in from namesp (encrypts the return communication)
                   13089: ($udom and $uname are optional)
1.191     harris41 13090: 
                   13091: =item *
                   13092: 
1.243     albertel 13093: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13094: critical subroutine
                   13095: 
1.806     raeburn  13096: =item *
                   13097: 
1.860     raeburn  13098: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13099: array reference filled in from namespace found in domain level on either
                   13100: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13101: 
                   13102: =item *
                   13103: 
1.860     raeburn  13104: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13105: domain level either on specified domain server ($uhome) or primary domain 
                   13106: server ($udom and $uhome are optional)
1.806     raeburn  13107: 
1.943     raeburn  13108: =item * 
                   13109: 
                   13110: get_domain_defaults($target_domain) : returns hash with defaults for
                   13111: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13112: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13113: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13114: Values are retrieved from cache (if current), or from domain's configuration.db
                   13115: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13116: or lonTabs/domain.tab. 
                   13117: 
                   13118: %domdefaults = &get_auth_defaults($target_domain);
                   13119: 
1.243     albertel 13120: =back
                   13121: 
                   13122: =head2 Network Status Functions
                   13123: 
                   13124: =over 4
1.191     harris41 13125: 
                   13126: =item *
                   13127: 
1.1137    raeburn  13128: dirlist() : return directory list based on URI (first arg).
                   13129: 
                   13130: Inputs: 1 required, 5 optional.
                   13131: 
                   13132: =over
                   13133: 
                   13134: =item 
                   13135: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13136: 
                   13137: =item
                   13138: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13139: 
                   13140: =item
                   13141: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13142: 
                   13143: =item
                   13144: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13145: 
                   13146: =item
                   13147: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13148: 
                   13149: =item 
                   13150: $alternateRoot - path to prepend in place of path from $uri.
                   13151: 
                   13152: =back
                   13153: 
                   13154: Returns: Array of up to two items.
                   13155: 
                   13156: =over
                   13157: 
                   13158: a reference to an array of files/subdirectories
                   13159: 
                   13160: =over
                   13161: 
                   13162: Each element in the array of files/subdirectories is a & separated list of
                   13163: item name and the result of running stat on the item.  If dirlist was requested
                   13164: for a file instead of a directory, the item name will be ''. For a directory 
                   13165: listing, if the item is a metadata file, the element will end &N&M 
                   13166: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13167: default copyright set (1).  
                   13168: 
                   13169: =back
                   13170: 
                   13171: a scalar containing error condition (if encountered).
                   13172: 
                   13173: =over
                   13174: 
                   13175: =item 
                   13176: no_host (no homeserver identified for $username:$domain).
                   13177: 
                   13178: =item 
                   13179: no_such_host (server contacted for listing not identified as valid host).
                   13180: 
                   13181: =item 
                   13182: con_lost (connection to remote server failed).
                   13183: 
                   13184: =item 
                   13185: refused (invalid $username:$domain received on lond side).
                   13186: 
                   13187: =item 
                   13188: no_such_dir (directory at specified path on lond side does not exist). 
                   13189: 
                   13190: =item 
                   13191: empty (directory at specified path on lond side is empty).
                   13192: 
                   13193: =over
                   13194: 
                   13195: This is currently not encountered because the &ls3, &ls2, 
                   13196: &ls (_handler) routines on the lond side do not filter out
                   13197: . and .. from a directory listing. 
                   13198: 
                   13199: =back
                   13200: 
                   13201: =back
                   13202: 
                   13203: =back
1.191     harris41 13204: 
                   13205: =item *
                   13206: 
1.243     albertel 13207: spareserver() : find server with least workload from spare.tab
                   13208: 
1.986     foxr     13209: 
                   13210: =item *
                   13211: 
                   13212: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13213: if there is no corresponding loncapa host.
                   13214: 
1.243     albertel 13215: =back
                   13216: 
1.986     foxr     13217: 
1.243     albertel 13218: =head2 Apache Request
                   13219: 
                   13220: =over 4
1.191     harris41 13221: 
                   13222: =item *
                   13223: 
1.243     albertel 13224: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13225: localhost, posts hash
                   13226: 
                   13227: =back
                   13228: 
                   13229: =head2 Data to String to Data
                   13230: 
                   13231: =over 4
1.191     harris41 13232: 
                   13233: =item *
                   13234: 
1.243     albertel 13235: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13236: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13237: 
                   13238: =item *
                   13239: 
1.243     albertel 13240: hashref2str($hashref) : convert a hashref into a string complete with
                   13241: escaping and '=' and '&' separators, supports elements that are
                   13242: arrayrefs and hashrefs
1.191     harris41 13243: 
                   13244: =item *
                   13245: 
1.243     albertel 13246: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13247: with escaping and '&' separators, supports elements that are arrayrefs
                   13248: and hashrefs
1.191     harris41 13249: 
                   13250: =item *
                   13251: 
1.243     albertel 13252: str2hash($string) : convert string to hash using unescaping and
                   13253: splitting on '=' and '&', supports elements that are arrayrefs and
                   13254: hashrefs
1.191     harris41 13255: 
                   13256: =item *
                   13257: 
1.243     albertel 13258: str2array($string) : convert string to hash using unescaping and
                   13259: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13260: 
                   13261: =back
                   13262: 
                   13263: =head2 Logging Routines
                   13264: 
                   13265: 
                   13266: These routines allow one to make log messages in the lonnet.log and
                   13267: lonnet.perm logfiles.
1.191     harris41 13268: 
1.1119    foxr     13269: =over 4
                   13270: 
1.191     harris41 13271: =item *
                   13272: 
1.243     albertel 13273: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13274: 
                   13275: =item *
                   13276: 
1.243     albertel 13277: logthis() : append message to the normal lonnet.log file, it gets
                   13278: preiodically rolled over and deleted.
1.191     harris41 13279: 
                   13280: =item *
                   13281: 
1.243     albertel 13282: logperm() : append a permanent message to lonnet.perm.log, this log
                   13283: file never gets deleted by any automated portion of the system, only
                   13284: messages of critical importance should go in here.
                   13285: 
1.1119    foxr     13286: 
1.243     albertel 13287: =back
                   13288: 
                   13289: =head2 General File Helper Routines
                   13290: 
                   13291: =over 4
1.191     harris41 13292: 
                   13293: =item *
                   13294: 
1.481     raeburn  13295: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13296: (a) files in /uploaded
                   13297:   (i) If a local copy of the file exists - 
                   13298:       compares modification date of local copy with last-modified date for 
                   13299:       definitive version stored on home server for course. If local copy is 
                   13300:       stale, requests a new version from the home server and stores it. 
                   13301:       If the original has been removed from the home server, then local copy 
                   13302:       is unlinked.
                   13303:   (ii) If local copy does not exist -
                   13304:       requests the file from the home server and stores it. 
                   13305:   
                   13306:   If $caller is 'uploadrep':  
                   13307:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13308:     for request for files originally uploaded via DOCS. 
                   13309:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13310:   
                   13311:   Otherwise:
                   13312:      This indicates a call from the content generation phase of the request.
                   13313:      -  returns the entire contents of the file or -1.
                   13314:      
                   13315: (b) files in /res
                   13316:    - returns the entire contents of a file or -1; 
                   13317:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13318: 
1.712     albertel 13319: 
                   13320: =item *
                   13321: 
                   13322: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13323:                   reference
                   13324: 
                   13325: returns either a stat() list of data about the file or an empty list
                   13326: if the file doesn't exist or couldn't find out about it (connection
                   13327: problems or user unknown)
                   13328: 
1.191     harris41 13329: =item *
                   13330: 
1.243     albertel 13331: filelocation($dir,$file) : returns file system location of a file
                   13332: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13333: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13334: and a file of ../bob will become /a/bob)
1.191     harris41 13335: 
                   13336: =item *
                   13337: 
                   13338: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13339: filelocation except for hrefs
                   13340: 
                   13341: =item *
                   13342: 
                   13343: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13344: 
1.243     albertel 13345: =back
                   13346: 
1.608     albertel 13347: =head2 Usererfile file routines (/uploaded*)
                   13348: 
                   13349: =over 4
                   13350: 
                   13351: =item *
                   13352: 
                   13353: userfileupload(): main rotine for putting a file in a user or course's
                   13354:                   filespace, arguments are,
                   13355: 
1.620     albertel 13356:  formname - required - this is the name of the element in $env where the
1.608     albertel 13357:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13358:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13359:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13360:  context - if coursedoc, store the file in the course of the active role
                   13361:              of the current user; 
                   13362:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13363:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13364:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13365:          if undefined, it will be placed in "unknown"
                   13366: 
                   13367:  (This routine calls clean_filename() to remove any dangerous
                   13368:  characters from the filename, and then calls finuserfileupload() to
                   13369:  complete the transaction)
                   13370: 
                   13371:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13372:  and /adm/notfound.html if unsuccessful
                   13373: 
                   13374: =item *
                   13375: 
                   13376: clean_filename(): routine for cleaing a filename up for storage in
                   13377:                  userfile space, argument is:
                   13378: 
                   13379:  filename - proposed filename
                   13380: 
                   13381: returns: the new clean filename
                   13382: 
                   13383: =item *
                   13384: 
1.1090    raeburn  13385: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13386: userspace, probably shouldn't be called directly
                   13387: 
                   13388:   docuname: username or courseid of destination for the file
                   13389:   docudom: domain of user/course of destination for the file
                   13390:   formname: same as for userfileupload()
1.1090    raeburn  13391:   fname: filename (including subdirectories) for the file
                   13392:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13393:   allfiles: reference to hash used to store objects found by parser
                   13394:   codebase: reference to hash used for codebases of java objects found by parser
                   13395:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13396:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13397:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13398:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13399:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13400:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13401:   mimetype: reference to scalar to accommodate mime type determined
                   13402:             from File::MMagic if $parser = parse.
1.608     albertel 13403: 
                   13404:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13405:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13406:  was 'overwrite').
                   13407:  
1.608     albertel 13408: 
                   13409: =item *
                   13410: 
                   13411: renameuserfile(): renames an existing userfile to a new name
                   13412: 
                   13413:   Args:
                   13414:    docuname: username or courseid of destination for the file
                   13415:    docudom: domain of user/course of destination for the file
                   13416:    old: current file name (including any subdirs under userfiles)
                   13417:    new: desired file name (including any subdirs under userfiles)
                   13418: 
                   13419: =item *
                   13420: 
                   13421: mkdiruserfile(): creates a directory is a userfiles dir
                   13422: 
                   13423:   Args:
                   13424:    docuname: username or courseid of destination for the file
                   13425:    docudom: domain of user/course of destination for the file
                   13426:    dir: dir to create (including any subdirs under userfiles)
                   13427: 
                   13428: =item *
                   13429: 
                   13430: removeuserfile(): removes a file that exists in userfiles
                   13431: 
                   13432:   Args:
                   13433:    docuname: username or courseid of destination for the file
                   13434:    docudom: domain of user/course of destination for the file
                   13435:    fname: filname to delete (including any subdirs under userfiles)
                   13436: 
                   13437: =item *
                   13438: 
                   13439: removeuploadedurl(): convience function for removeuserfile()
                   13440: 
                   13441:   Args:
                   13442:    url:  a full /uploaded/... url to delete
                   13443: 
1.747     albertel 13444: =item * 
                   13445: 
                   13446: get_portfile_permissions():
                   13447:   Args:
                   13448:     domain: domain of user or course contain the portfolio files
                   13449:     user: name of user or num of course contain the portfolio files
                   13450:   Returns:
                   13451:     hashref of a dump of the proper file_permissions.db
                   13452:    
                   13453: 
                   13454: =item * 
                   13455: 
                   13456: get_access_controls():
                   13457: 
                   13458: Args:
                   13459:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13460:   group: (optional) the group you want the files associated with
                   13461:   file: (optional) the file you want access info on
                   13462: 
                   13463: Returns:
1.749     raeburn  13464:     a hash (keys are file names) of hashes containing
                   13465:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13466:         values are XML containing access control settings (see below) 
1.747     albertel 13467: 
                   13468: Internal notes:
                   13469: 
1.749     raeburn  13470:  access controls are stored in file_permissions.db as key=value pairs.
                   13471:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13472:         where scope -> public,guest,course,group,domains or users.
                   13473:               end -> UNIX time for end of access (0 -> no end date)
                   13474:               start -> UNIX time for start of access
                   13475: 
                   13476:     value -> XML description of access control
                   13477:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13478:             <start></start>
                   13479:             <end></end>
                   13480: 
                   13481:             <password></password>  for scope type = guest
                   13482: 
                   13483:             <domain></domain>     for scope type = course or group
                   13484:             <number></number>
                   13485:             <roles id="">
                   13486:              <role></role>
                   13487:              <access></access>
                   13488:              <section></section>
                   13489:              <group></group>
                   13490:             </roles>
                   13491: 
                   13492:             <dom></dom>         for scope type = domains
                   13493: 
                   13494:             <users>             for scope type = users
                   13495:              <user>
                   13496:               <uname></uname>
                   13497:               <udom></udom>
                   13498:              </user>
                   13499:             </users>
                   13500:            </scope> 
                   13501:               
                   13502:  Access data is also aggregated for each file in an additional key=value pair:
                   13503:  key -> path to file/file_name\0accesscontrol 
                   13504:  value -> reference to hash
                   13505:           hash contains key = value pairs
                   13506:           where key = uniqueID:scope_end_start
                   13507:                 value = UNIX time record was last updated
                   13508: 
                   13509:           Used to improve speed of look-ups of access controls for each file.  
                   13510:  
                   13511:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13512: 
1.1198    raeburn  13513: =item *
                   13514: 
1.749     raeburn  13515: modify_access_controls():
                   13516: 
                   13517: Modifies access controls for a portfolio file
                   13518: Args
                   13519: 1. file name
                   13520: 2. reference to hash of required changes,
                   13521: 3. domain
                   13522: 4. username
                   13523:   where domain,username are the domain of the portfolio owner 
                   13524:   (either a user or a course) 
                   13525: 
                   13526: Returns:
                   13527: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13528: 2. result of deletions ('ok' or 'error', with error message).
                   13529: 3. reference to hash of any new or updated access controls.
                   13530: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13531:    key = integer (inbound ID)
1.1198    raeburn  13532:    value = uniqueID
                   13533: 
                   13534: =item *
                   13535: 
                   13536: get_timebased_id():
                   13537: 
                   13538: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13539: course via the Course Editor (e.g., folders, composite pages, 
                   13540: group bulletin boards).
                   13541: 
                   13542: Args: (first three required; six others optional)
                   13543: 
                   13544: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13545:    docssequence, or name of group
                   13546: 
                   13547: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13548:    e.g., num, boardids
                   13549: 
                   13550: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   13551:    file will be named nohist_namespace.db
                   13552: 
                   13553: 4. cdom: domain of course; default is current course domain from %env
                   13554: 
                   13555: 5. cnum: course number; default is current course number from %env
                   13556: 
                   13557: 6. idtype: set to concat if an additional digit is to be appended to the 
                   13558:    unix timestamp to form the suffix, if the plain timestamp is already
                   13559:    in use.  Default is to not do this, but simply increment the unix 
                   13560:    timestamp by 1 until a unique key is obtained.
                   13561: 
                   13562: 7. who: holder of locking key; defaults to user:domain for user.
                   13563: 
                   13564: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   13565:    retrying); default is 3.
                   13566: 
                   13567: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   13568: 
                   13569: Returns:
                   13570: 
                   13571: 1. suffix obtained (numeric)
                   13572: 
                   13573: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13574: 
                   13575: 3. error: contains (localized) error message if an error occurred.
                   13576: 
1.747     albertel 13577: 
1.608     albertel 13578: =back
                   13579: 
1.243     albertel 13580: =head2 HTTP Helper Routines
                   13581: 
                   13582: =over 4
                   13583: 
1.191     harris41 13584: =item *
                   13585: 
                   13586: escape() : unpack non-word characters into CGI-compatible hex codes
                   13587: 
                   13588: =item *
                   13589: 
                   13590: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13591: 
1.243     albertel 13592: =back
                   13593: 
                   13594: =head1 PRIVATE SUBROUTINES
                   13595: 
                   13596: =head2 Underlying communication routines (Shouldn't call)
                   13597: 
                   13598: =over 4
                   13599: 
                   13600: =item *
                   13601: 
                   13602: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13603: 
                   13604: =item *
                   13605: 
                   13606: reply() : uses subreply to send a message to remote machine, logs all failures
                   13607: 
                   13608: =item *
                   13609: 
                   13610: critical() : passes a critical message to another server; if cannot
                   13611: get through then place message in connection buffer directory and
                   13612: returns con_delayed, if incapable of saving message, returns
                   13613: con_failed
                   13614: 
                   13615: =item *
                   13616: 
                   13617: reconlonc() : tries to reconnect lonc client processes.
                   13618: 
                   13619: =back
                   13620: 
                   13621: =head2 Resource Access Logging
                   13622: 
                   13623: =over 4
                   13624: 
                   13625: =item *
                   13626: 
                   13627: flushcourselogs() : flush (save) buffer logs and access logs
                   13628: 
                   13629: =item *
                   13630: 
                   13631: courselog($what) : save message for course in hash
                   13632: 
                   13633: =item *
                   13634: 
                   13635: courseacclog($what) : save message for course using &courselog().  Perform
                   13636: special processing for specific resource types (problems, exams, quizzes, etc).
                   13637: 
1.191     harris41 13638: =item *
                   13639: 
                   13640: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13641: as a PerlChildExitHandler
1.243     albertel 13642: 
                   13643: =back
                   13644: 
                   13645: =head2 Other
                   13646: 
                   13647: =over 4
                   13648: 
                   13649: =item *
                   13650: 
                   13651: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13652: 
                   13653: =back
                   13654: 
                   13655: =cut
1.877     foxr     13656: 

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