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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1212  ! raeburn     4: # $Id: lonnet.pm,v 1.1211 2013/02/02 03:29:33 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.871     albertel   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.539     albertel   95: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.550     foxr      108: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.993     raeburn   232: sub get_server_loncaparev {
1.1073    raeburn   233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   234:     if (defined($lonhost)) {
                    235:         if (!defined(&hostname($lonhost))) {
                    236:             undef($lonhost);
                    237:         }
                    238:     }
                    239:     if (!defined($lonhost)) {
                    240:         if (defined(&domain($dom,'primary'))) {
                    241:             $lonhost=&domain($dom,'primary');
                    242:             if ($lonhost eq 'no_host') {
                    243:                 undef($lonhost);
                    244:             }
                    245:         }
                    246:     }
                    247:     if (defined($lonhost)) {
1.1073    raeburn   248:         my $cachetime = 12*3600;
                    249:         if (!$ignore_cache) {
                    250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    251:             if (defined($cached)) {
                    252:                 return $loncaparev;
                    253:             }
                    254:         }
                    255:         my ($answer,$loncaparev);
                    256:         my @ids=&current_machine_ids();
                    257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    258:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   260:                 $loncaparev = $1;
                    261:             }
                    262:         } else {
                    263:             $answer = &reply('serverloncaparev',$lonhost);
                    264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    265:                 if ($caller eq 'loncron') {
                    266:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   267:                     $ua->timeout(4);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
                    270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
                    359:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   361:     return $response;
                    362: }
                    363: 
1.1       albertel  364: # -------------------------------------------------- Non-critical communication
                    365: sub subreply {
                    366:     my ($cmd,$server)=@_;
1.838     albertel  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      368:     #
                    369:     #  With loncnew process trimming, there's a timing hole between lonc server
                    370:     #  process exit and the master server picking up the listen on the AF_UNIX
                    371:     #  socket.  In that time interval, a lock file will exist:
                    372: 
                    373:     my $lockfile=$peerfile.".lock";
                    374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    375: 	sleep(1);
                    376:     }
                    377:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      378:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      379:     #
1.550     foxr      380:     #   We'll give the connection a few tries before abandoning it.  If
                    381:     #   connection is not possible, we'll con_lost back to the client.
                    382:     #   
                    383:     my $client;
                    384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    386: 				      Type    => SOCK_STREAM,
                    387: 				      Timeout => 10);
1.869     albertel  388: 	if ($client) {
1.550     foxr      389: 	    last;		# Connected!
1.850     albertel  390: 	} else {
1.853     albertel  391: 	    &create_connection(&hostname($server),$server);
1.550     foxr      392: 	}
1.850     albertel  393:         sleep(1);		# Try again later if failed connection.
1.550     foxr      394:     }
                    395:     my $answer;
                    396:     if ($client) {
1.704     albertel  397: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      398: 	$answer=<$client>;
                    399: 	if (!$answer) { $answer="con_lost"; }
                    400: 	chomp($answer);
                    401:     } else {
                    402: 	$answer = 'con_lost';	# Failed connection.
                    403:     }
1.1       albertel  404:     return $answer;
                    405: }
                    406: 
                    407: sub reply {
                    408:     my ($cmd,$server)=@_;
1.838     albertel  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  410:     my $answer=subreply($cmd,$server);
1.65      www       411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  412:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       413:                 " $cmd to $server returned $answer</font>");
                    414:     }
1.1       albertel  415:     return $answer;
                    416: }
                    417: 
                    418: # ----------------------------------------------------------- Send USR1 to lonc
                    419: 
                    420: sub reconlonc {
1.891     albertel  421:     my ($lonid) = @_;
                    422:     my $hostname = &hostname($lonid);
                    423:     if ($lonid) {
                    424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    425: 	if ($hostname && -e $peerfile) {
                    426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    428: 					     Type    => SOCK_STREAM,
                    429: 					     Timeout => 10);
                    430: 	    if ($client) {
                    431: 		print $client ("reset_retries\n");
                    432: 		my $answer=<$client>;
                    433: 		#reset just this one.
                    434: 	    }
                    435: 	}
                    436: 	return;
                    437:     }
                    438: 
1.836     www       439:     &logthis("Trying to reconnect lonc");
1.1       albertel  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  441:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  442: 	my $loncpid=<$fh>;
                    443:         chomp($loncpid);
                    444:         if (kill 0 => $loncpid) {
                    445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    446:             kill USR1 => $loncpid;
                    447:             sleep 1;
1.836     www       448:          } else {
1.12      www       449: 	    &logthis(
1.672     albertel  450:                "<font color=\"blue\">WARNING:".
1.12      www       451:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  452:         }
                    453:     } else {
1.836     www       454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  455:     }
                    456: }
                    457: 
                    458: # ------------------------------------------------------ Critical communication
1.12      www       459: 
1.1       albertel  460: sub critical {
                    461:     my ($cmd,$server)=@_;
1.838     albertel  462:     unless (&hostname($server)) {
1.672     albertel  463:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       464:                " Critical message to unknown server ($server)</font>");
                    465:         return 'no_such_host';
                    466:     }
1.1       albertel  467:     my $answer=reply($cmd,$server);
                    468:     if ($answer eq 'con_lost') {
                    469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  470: 	my $answer=reply($cmd,$server);
1.1       albertel  471:         if ($answer eq 'con_lost') {
                    472:             my $now=time;
                    473:             my $middlename=$cmd;
1.5       www       474:             $middlename=substr($middlename,0,16);
1.1       albertel  475:             $middlename=~s/\W//g;
                    476:             my $dfilename=
1.305     www       477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    478:             $dumpcount++;
1.1       albertel  479:             {
1.448     albertel  480: 		my $dfh;
                    481: 		if (open($dfh,">$dfilename")) {
                    482: 		    print $dfh "$cmd\n"; 
                    483: 		    close($dfh);
                    484: 		}
1.1       albertel  485:             }
                    486:             sleep 2;
                    487:             my $wcmd='';
                    488:             {
1.448     albertel  489: 		my $dfh;
                    490: 		if (open($dfh,"<$dfilename")) {
                    491: 		    $wcmd=<$dfh>; 
                    492: 		    close($dfh);
                    493: 		}
1.1       albertel  494:             }
                    495:             chomp($wcmd);
1.7       www       496:             if ($wcmd eq $cmd) {
1.672     albertel  497: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       498:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  499:                 &logperm("D:$server:$cmd");
                    500: 	        return 'con_delayed';
                    501:             } else {
1.672     albertel  502:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       503:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  504:                 &logperm("F:$server:$cmd");
                    505:                 return 'con_failed';
                    506:             }
                    507:         }
                    508:     }
                    509:     return $answer;
1.405     albertel  510: }
                    511: 
1.755     albertel  512: # ------------------------------------------- check if return value is an error
                    513: 
                    514: sub error {
                    515:     my ($result) = @_;
1.756     albertel  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  517: 	if ($2 == 2) { return undef; }
                    518: 	return $1;
                    519:     }
                    520:     return undef;
                    521: }
                    522: 
1.783     albertel  523: sub convert_and_load_session_env {
                    524:     my ($lonidsdir,$handle)=@_;
                    525:     my @profile;
                    526:     {
1.917     albertel  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    528: 	if (!$opened) {
1.915     albertel  529: 	    return 0;
                    530: 	}
1.783     albertel  531: 	flock($idf,LOCK_SH);
                    532: 	@profile=<$idf>;
                    533: 	close($idf);
                    534:     }
                    535:     my %temp_env;
                    536:     foreach my $line (@profile) {
1.786     albertel  537: 	if ($line !~ m/=/) {
                    538: 	    return 0;
                    539: 	}
1.783     albertel  540: 	chomp($line);
                    541: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    543:     }
                    544:     unlink("$lonidsdir/$handle.id");
                    545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    546: 	    0640)) {
                    547: 	%disk_env = %temp_env;
                    548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    549: 	untie(%disk_env);
                    550:     }
1.786     albertel  551:     return 1;
1.783     albertel  552: }
                    553: 
1.374     www       554: # ------------------------------------------- Transfer profile into environment
1.780     albertel  555: my $env_loaded;
                    556: sub transfer_profile_to_env {
1.788     albertel  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    558:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       559: 
1.720     albertel  560:     if (!defined($lonidsdir)) {
                    561: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    562:     }
                    563:     if (!defined($handle)) {
                    564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    565:     }
                    566: 
1.786     albertel  567:     my $convert;
                    568:     {
1.917     albertel  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    570: 	if (!$opened) {
1.915     albertel  571: 	    return;
                    572: 	}
1.786     albertel  573: 	flock($idf,LOCK_SH);
                    574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    575: 		&GDBM_READER(),0640)) {
                    576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    577: 	    untie(%disk_env);
                    578: 	} else {
                    579: 	    $convert = 1;
                    580: 	}
                    581:     }
                    582:     if ($convert) {
                    583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    584: 	    &logthis("Failed to load session, or convert session.");
                    585: 	}
1.374     www       586:     }
1.783     albertel  587: 
1.786     albertel  588:     my %remove;
1.783     albertel  589:     while ( my $envname = each(%env) ) {
1.433     matthew   590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    591:             if ($time < time-300) {
1.783     albertel  592:                 $remove{$key}++;
1.433     matthew   593:             }
                    594:         }
                    595:     }
1.783     albertel  596: 
1.619     albertel  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  598:     $env_loaded=1;
1.783     albertel  599:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   600:         &delenv($expired_key);
1.374     www       601:     }
1.1       albertel  602: }
                    603: 
1.916     albertel  604: # ---------------------------------------------------- Check for valid session 
                    605: sub check_for_valid_session {
1.1155    raeburn   606:     my ($r,$name) = @_;
1.916     albertel  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   608:     if ($name eq '') {
                    609:         $name = 'lonID';
                    610:     }
                    611:     my $lonid=$cookies{$name};
1.916     albertel  612:     return undef if (!$lonid);
                    613: 
                    614:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   615:     my $lonidsdir;
                    616:     if ($name eq 'lonDAV') {
                    617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    618:     } else {
                    619:         $lonidsdir=$r->dir_config('lonIDsDir');
                    620:     }
1.916     albertel  621:     return undef if (!-e "$lonidsdir/$handle.id");
                    622: 
1.917     albertel  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    624:     return undef if (!$opened);
1.916     albertel  625: 
                    626:     flock($idf,LOCK_SH);
                    627:     my %disk_env;
                    628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    629: 	    &GDBM_READER(),0640)) {
                    630: 	return undef;	
                    631:     }
                    632: 
                    633:     if (!defined($disk_env{'user.name'})
                    634: 	|| !defined($disk_env{'user.domain'})) {
                    635: 	return undef;
                    636:     }
1.1212  ! raeburn   637:     if ($r->user() eq '') {
        !           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:         }
                   2013:     }
1.1073    raeburn  2014:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2015:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2016:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2017:         }
                   2018:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2019:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2020:         }
                   2021:     }
1.943     raeburn  2022:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   2023:                                   $cachetime);
                   2024:     return %domdefaults;
                   2025: }
                   2026: 
1.344     www      2027: # --------------------------------------------------- Assign a key to a student
                   2028: 
                   2029: sub assign_access_key {
1.364     www      2030: #
                   2031: # a valid key looks like uname:udom#comments
                   2032: # comments are being appended
                   2033: #
1.498     www      2034:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2035:     $kdom=
1.620     albertel 2036:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2037:     $knum=
1.620     albertel 2038:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2039:     $cdom=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2041:     $cnum=
1.620     albertel 2042:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2043:     $udom=$env{'user.name'} unless (defined($udom));
                   2044:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2045:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2046:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2047:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2048:                                                   # assigned to this person
                   2049:                                                   # - this should not happen,
1.345     www      2050:                                                   # unless something went wrong
                   2051:                                                   # the first time around
                   2052: # ready to assign
1.364     www      2053:         $logentry=$1.'; '.$logentry;
1.496     www      2054:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2055:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2056: # key now belongs to user
1.346     www      2057: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2058:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2059:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2060:                 return 'ok';
                   2061:             } else {
                   2062:                 return 
                   2063:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2064: 	    }
                   2065:         } else {
                   2066:             return 'error: Could not assign key, try again later.';
                   2067:         }
1.364     www      2068:     } elsif (!$existing{$ckey}) {
1.345     www      2069: # the key does not exist
                   2070: 	return 'error: The key does not exist';
                   2071:     } else {
                   2072: # the key is somebody else's
                   2073: 	return 'error: The key is already in use';
                   2074:     }
1.344     www      2075: }
                   2076: 
1.364     www      2077: # ------------------------------------------ put an additional comment on a key
                   2078: 
                   2079: sub comment_access_key {
                   2080: #
                   2081: # a valid key looks like uname:udom#comments
                   2082: # comments are being appended
                   2083: #
                   2084:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2085:     $cdom=
1.620     albertel 2086:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2087:     $cnum=
1.620     albertel 2088:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2089:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2090:     if ($existing{$ckey}) {
                   2091:         $existing{$ckey}.='; '.$logentry;
                   2092: # ready to assign
1.367     www      2093:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2094:                                                  $cdom,$cnum) eq 'ok') {
                   2095: 	    return 'ok';
                   2096:         } else {
                   2097: 	    return 'error: Count not store comment.';
                   2098:         }
                   2099:     } else {
                   2100: # the key does not exist
                   2101: 	return 'error: The key does not exist';
                   2102:     }
                   2103: }
                   2104: 
1.344     www      2105: # ------------------------------------------------------ Generate a set of keys
                   2106: 
                   2107: sub generate_access_keys {
1.364     www      2108:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2109:     $cdom=
1.620     albertel 2110:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2111:     $cnum=
1.620     albertel 2112:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2113:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2114:     unless (($cdom) && ($cnum)) { return 0; }
                   2115:     if ($number>10000) { return 0; }
                   2116:     sleep(2); # make sure don't get same seed twice
                   2117:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2118:     my $total=0;
                   2119:     for (my $i=1;$i<=$number;$i++) {
                   2120:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2121:                   sprintf("%lx",int(100000*rand)).'-'.
                   2122:                   sprintf("%lx",int(100000*rand));
                   2123:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2124:        $newkey=~s/0/h/g; # and also 0 and O
                   2125:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2126:        if ($existing{$newkey}) {
                   2127:            $i--;
                   2128:        } else {
1.364     www      2129: 	  if (&put('accesskeys',
                   2130:               { $newkey => '# generated '.localtime().
1.620     albertel 2131:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2132:                            '; '.$logentry },
                   2133: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2134:               $total++;
                   2135: 	  }
                   2136:        }
                   2137:     }
1.620     albertel 2138:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2139:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2140:     return $total;
                   2141: }
                   2142: 
                   2143: # ------------------------------------------------------- Validate an accesskey
                   2144: 
                   2145: sub validate_access_key {
                   2146:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2147:     $cdom=
1.620     albertel 2148:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2149:     $cnum=
1.620     albertel 2150:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2151:     $udom=$env{'user.domain'} unless (defined($udom));
                   2152:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2153:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2154:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2155: }
                   2156: 
                   2157: # ------------------------------------- Find the section of student in a course
1.652     albertel 2158: sub devalidate_getsection_cache {
                   2159:     my ($udom,$unam,$courseid)=@_;
                   2160:     my $hashid="$udom:$unam:$courseid";
                   2161:     &devalidate_cache_new('getsection',$hashid);
                   2162: }
1.298     matthew  2163: 
1.815     albertel 2164: sub courseid_to_courseurl {
                   2165:     my ($courseid) = @_;
                   2166:     #already url style courseid
                   2167:     return $courseid if ($courseid =~ m{^/});
                   2168: 
                   2169:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2170: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2171: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2172: 	return "/$cdom/$cnum";
                   2173:     }
                   2174: 
                   2175:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2176:     if (exists($courseinfo{'num'})) {
                   2177: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2178:     }
                   2179: 
                   2180:     return undef;
                   2181: }
                   2182: 
1.298     matthew  2183: sub getsection {
                   2184:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2185:     my $cachetime=1800;
1.551     albertel 2186: 
                   2187:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2188:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2189:     if (defined($cached)) { return $result; }
                   2190: 
1.298     matthew  2191:     my %Pending; 
                   2192:     my %Expired;
                   2193:     #
                   2194:     # Each role can either have not started yet (pending), be active, 
                   2195:     #    or have expired.
                   2196:     #
                   2197:     # If there is an active role, we are done.
                   2198:     #
                   2199:     # If there is more than one role which has not started yet, 
                   2200:     #     choose the one which will start sooner
                   2201:     # If there is one role which has not started yet, return it.
                   2202:     #
                   2203:     # If there is more than one expired role, choose the one which ended last.
                   2204:     # If there is a role which has expired, return it.
                   2205:     #
1.815     albertel 2206:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2207:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2208:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2209:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2210:         my $section=$1;
                   2211:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2212:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2213:         my $now=time;
1.548     albertel 2214:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2215:             $Expired{$end}=$section;
                   2216:             next;
                   2217:         }
1.548     albertel 2218:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2219:             $Pending{$start}=$section;
                   2220:             next;
                   2221:         }
1.599     albertel 2222:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2223:     }
                   2224:     #
                   2225:     # Presumedly there will be few matching roles from the above
                   2226:     # loop and the sorting time will be negligible.
                   2227:     if (scalar(keys(%Pending))) {
                   2228:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2229:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2230:     } 
                   2231:     if (scalar(keys(%Expired))) {
                   2232:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2233:         my $time = pop(@sorted);
1.599     albertel 2234:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2235:     }
1.599     albertel 2236:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2237: }
1.70      www      2238: 
1.599     albertel 2239: sub save_cache {
                   2240:     &purge_remembered();
1.722     albertel 2241:     #&Apache::loncommon::validate_page();
1.620     albertel 2242:     undef(%env);
1.780     albertel 2243:     undef($env_loaded);
1.599     albertel 2244: }
1.452     albertel 2245: 
1.599     albertel 2246: my $to_remember=-1;
                   2247: my %remembered;
                   2248: my %accessed;
                   2249: my $kicks=0;
                   2250: my $hits=0;
1.849     albertel 2251: sub make_key {
                   2252:     my ($name,$id) = @_;
1.872     albertel 2253:     if (length($id) > 65 
                   2254: 	&& length(&escape($id)) > 200) {
                   2255: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2256:     }
1.849     albertel 2257:     return &escape($name.':'.$id);
                   2258: }
                   2259: 
1.599     albertel 2260: sub devalidate_cache_new {
                   2261:     my ($name,$id,$debug) = @_;
                   2262:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2263:     $id=&make_key($name,$id);
1.599     albertel 2264:     $memcache->delete($id);
                   2265:     delete($remembered{$id});
                   2266:     delete($accessed{$id});
                   2267: }
                   2268: 
                   2269: sub is_cached_new {
                   2270:     my ($name,$id,$debug) = @_;
1.849     albertel 2271:     $id=&make_key($name,$id);
1.599     albertel 2272:     if (exists($remembered{$id})) {
1.1133    foxr     2273: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2274: 	$accessed{$id}=[&gettimeofday()];
                   2275: 	$hits++;
                   2276: 	return ($remembered{$id},1);
                   2277:     }
                   2278:     my $value = $memcache->get($id);
                   2279:     if (!(defined($value))) {
                   2280: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2281: 	return (undef,undef);
1.416     albertel 2282:     }
1.599     albertel 2283:     if ($value eq '__undef__') {
                   2284: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2285: 	$value=undef;
                   2286:     }
                   2287:     &make_room($id,$value,$debug);
                   2288:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2289:     return ($value,1);
                   2290: }
                   2291: 
                   2292: sub do_cache_new {
                   2293:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2294:     $id=&make_key($name,$id);
1.599     albertel 2295:     my $setvalue=$value;
                   2296:     if (!defined($setvalue)) {
                   2297: 	$setvalue='__undef__';
                   2298:     }
1.623     albertel 2299:     if (!defined($time) ) {
                   2300: 	$time=600;
                   2301:     }
1.599     albertel 2302:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2303:     my $result = $memcache->set($id,$setvalue,$time);
                   2304:     if (! $result) {
1.872     albertel 2305: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2306: 	$memcache->disconnect_all();
1.872     albertel 2307:     }
1.600     albertel 2308:     # need to make a copy of $value
1.919     albertel 2309:     &make_room($id,$value,$debug);
1.599     albertel 2310:     return $value;
                   2311: }
                   2312: 
                   2313: sub make_room {
                   2314:     my ($id,$value,$debug)=@_;
1.919     albertel 2315: 
                   2316:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2317:                                     : $value;
1.599     albertel 2318:     if ($to_remember<0) { return; }
                   2319:     $accessed{$id}=[&gettimeofday()];
                   2320:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2321:     my $to_kick;
                   2322:     my $max_time=0;
                   2323:     foreach my $other (keys(%accessed)) {
                   2324: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2325: 	    $to_kick=$other;
                   2326: 	    $max_time=&tv_interval($accessed{$other});
                   2327: 	}
                   2328:     }
                   2329:     delete($remembered{$to_kick});
                   2330:     delete($accessed{$to_kick});
                   2331:     $kicks++;
                   2332:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2333:     return;
                   2334: }
                   2335: 
1.599     albertel 2336: sub purge_remembered {
1.604     albertel 2337:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2338:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2339:     undef(%remembered);
                   2340:     undef(%accessed);
1.428     albertel 2341: }
1.70      www      2342: # ------------------------------------- Read an entry from a user's environment
                   2343: 
                   2344: sub userenvironment {
                   2345:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2346:     my $items;
                   2347:     foreach my $item (@what) {
                   2348:         $items.=&escape($item).'&';
                   2349:     }
                   2350:     $items=~s/\&$//;
1.70      www      2351:     my %returnhash=();
1.1009    raeburn  2352:     my $uhome = &homeserver($unam,$udom);
                   2353:     unless ($uhome eq 'no_host') {
                   2354:         my @answer=split(/\&/, 
                   2355:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2356:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2357:             return %returnhash;
                   2358:         }
1.1009    raeburn  2359:         my $i;
                   2360:         for ($i=0;$i<=$#what;$i++) {
                   2361: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2362:         }
1.70      www      2363:     }
                   2364:     return %returnhash;
1.1       albertel 2365: }
                   2366: 
1.617     albertel 2367: # ---------------------------------------------------------- Get a studentphoto
                   2368: sub studentphoto {
                   2369:     my ($udom,$unam,$ext) = @_;
                   2370:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2371:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2372:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2373:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2374:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2375:             } else {
                   2376:                 my ($result,$perm_reqd)=
1.707     albertel 2377: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2378:                 if ($result eq 'ok') {
                   2379:                     if (!($perm_reqd eq 'yes')) {
                   2380:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2381:                     }
                   2382:                 }
                   2383:             }
                   2384:         }
                   2385:     } else {
                   2386:         my ($result,$perm_reqd) = 
1.707     albertel 2387: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2388:         if ($result eq 'ok') {
                   2389:             if (!($perm_reqd eq 'yes')) {
                   2390:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2391:             }
                   2392:         }
                   2393:     }
                   2394:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2395: }
                   2396: 
                   2397: sub retrievestudentphoto {
                   2398:     my ($udom,$unam,$ext,$type) = @_;
                   2399:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2400:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2401:     if ($ret eq 'ok') {
                   2402:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2403:         if ($type eq 'thumbnail') {
                   2404:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2405:         }
                   2406:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2407:         return $tokenurl;
                   2408:     } else {
                   2409:         if ($type eq 'thumbnail') {
                   2410:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2411:         } else { 
                   2412:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2413:         }
1.617     albertel 2414:     }
                   2415: }
                   2416: 
1.263     www      2417: # -------------------------------------------------------------------- New chat
                   2418: 
                   2419: sub chatsend {
1.724     raeburn  2420:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2421:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2422:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2423:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2424:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2425: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2426: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2427: }
                   2428: 
                   2429: # ------------------------------------------ Find current version of a resource
                   2430: 
                   2431: sub getversion {
                   2432:     my $fname=&clutter(shift);
1.1189    raeburn  2433:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2434:     return &currentversion(&filelocation('',$fname));
                   2435: }
                   2436: 
                   2437: sub currentversion {
                   2438:     my $fname=shift;
                   2439:     my $author=$fname;
                   2440:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2441:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2442:     my $home=&homeserver($uname,$udom);
1.292     www      2443:     if ($home eq 'no_host') { 
                   2444:         return -1; 
                   2445:     }
1.1112    www      2446:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2447:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2448: 	return -1;
                   2449:     }
1.1112    www      2450:     return $answer;
1.263     www      2451: }
                   2452: 
1.1111    www      2453: #
                   2454: # Return special version number of resource if set by override, empty otherwise
                   2455: #
                   2456: sub usedversion {
                   2457:     my $fname=shift;
                   2458:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2459:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2460:     if ($urlversion) { return $urlversion; }
                   2461:     return '';
                   2462: }
                   2463: 
1.1       albertel 2464: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2465: 
1.1       albertel 2466: sub subscribe {
                   2467:     my $fname=shift;
1.761     raeburn  2468:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2469:     $fname=~s/[\n\r]//g;
1.1       albertel 2470:     my $author=$fname;
                   2471:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2472:     my ($udom,$uname)=split(/\//,$author);
                   2473:     my $home=homeserver($uname,$udom);
1.335     albertel 2474:     if ($home eq 'no_host') {
                   2475:         return 'not_found';
1.1       albertel 2476:     }
                   2477:     my $answer=reply("sub:$fname",$home);
1.64      www      2478:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2479: 	$answer.=' by '.$home;
                   2480:     }
1.1       albertel 2481:     return $answer;
                   2482: }
                   2483:     
1.8       www      2484: # -------------------------------------------------------------- Replicate file
                   2485: 
                   2486: sub repcopy {
                   2487:     my $filename=shift;
1.23      www      2488:     $filename=~s/\/+/\//g;
1.1142    raeburn  2489:     my $londocroot = $perlvar{'lonDocRoot'};
                   2490:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2491:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2492:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2493: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2494: 	return &repcopy_userfile($filename);
                   2495:     }
1.532     albertel 2496:     $filename=~s/[\n\r]//g;
1.8       www      2497:     my $transname="$filename.in.transfer";
1.828     www      2498: # FIXME: this should flock
1.607     raeburn  2499:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2500:     my $remoteurl=subscribe($filename);
1.64      www      2501:     if ($remoteurl =~ /^con_lost by/) {
                   2502: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2503:            return 'unavailable';
1.8       www      2504:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2505: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2506: 	   return 'not_found';
1.64      www      2507:     } elsif ($remoteurl =~ /^rejected by/) {
                   2508: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2509:            return 'forbidden';
1.20      www      2510:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2511:            return 'ok';
1.8       www      2512:     } else {
1.290     www      2513:         my $author=$filename;
                   2514:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2515:         my ($udom,$uname)=split(/\//,$author);
                   2516:         my $home=homeserver($uname,$udom);
                   2517:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2518:            my @parts=split(/\//,$filename);
                   2519:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2520:            if ($path ne "$londocroot/res") {
1.8       www      2521:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2522: 	       return 'bad_request';
1.8       www      2523:            }
                   2524:            my $count;
                   2525:            for ($count=5;$count<$#parts;$count++) {
                   2526:                $path.="/$parts[$count]";
                   2527:                if ((-e $path)!=1) {
                   2528: 		   mkdir($path,0777);
                   2529:                }
                   2530:            }
                   2531:            my $ua=new LWP::UserAgent;
                   2532:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2533:            my $response=$ua->request($request,$transname);
                   2534:            if ($response->is_error()) {
                   2535: 	       unlink($transname);
                   2536:                my $message=$response->status_line;
1.672     albertel 2537:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2538:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2539:                return 'unavailable';
1.8       www      2540:            } else {
1.16      www      2541: 	       if ($remoteurl!~/\.meta$/) {
                   2542:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2543:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2544:                   if ($mresponse->is_error()) {
                   2545: 		      unlink($filename.'.meta');
                   2546:                       &logthis(
1.672     albertel 2547:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2548:                   }
                   2549: 	       }
1.8       www      2550:                rename($transname,$filename);
1.607     raeburn  2551:                return 'ok';
1.8       www      2552:            }
1.290     www      2553:        }
1.8       www      2554:     }
1.330     www      2555: }
                   2556: 
                   2557: # ------------------------------------------------ Get server side include body
                   2558: sub ssi_body {
1.381     albertel 2559:     my ($filelink,%form)=@_;
1.606     matthew  2560:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2561:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2562:     }
1.953     www      2563:     my $output='';
                   2564:     my $response;
1.980     raeburn  2565:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2566:        ($output,$response)=&externalssi($filelink);
1.953     www      2567:     } else {
1.1004    droeschl 2568:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2569:        $filelink .= 'inhibitmenu=yes';
1.953     www      2570:        ($output,$response)=&ssi($filelink,%form);
                   2571:     }
1.778     albertel 2572:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2573:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2574:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2575:     if (wantarray) {
                   2576:         return ($output, $response);
                   2577:     } else {
                   2578:         return $output;
                   2579:     }
1.8       www      2580: }
                   2581: 
1.15      www      2582: # --------------------------------------------------------- Server Side Include
                   2583: 
1.782     albertel 2584: sub absolute_url {
                   2585:     my ($host_name) = @_;
                   2586:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2587:     if ($host_name eq '') {
                   2588: 	$host_name = $ENV{'SERVER_NAME'};
                   2589:     }
                   2590:     return $protocol.$host_name;
                   2591: }
                   2592: 
1.942     foxr     2593: #
                   2594: #   Server side include.
                   2595: # Parameters:
                   2596: #  fn     Possibly encrypted resource name/id.
                   2597: #  form   Hash that describes how the rendering should be done
                   2598: #         and other things.
1.944     foxr     2599: # Returns:
1.950     raeburn  2600: #   Scalar context: The content of the response.
                   2601: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2602: #     
1.15      www      2603: sub ssi {
                   2604: 
1.944     foxr     2605:     my ($fn,%form)=@_;
1.15      www      2606:     my $ua=new LWP::UserAgent;
1.23      www      2607:     my $request;
1.711     albertel 2608: 
                   2609:     $form{'no_update_last_known'}=1;
1.895     albertel 2610:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2611:     if (%form) {
1.782     albertel 2612:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2613:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2614:     } else {
1.782     albertel 2615:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2616:     }
                   2617: 
1.15      www      2618:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2619:     my $response= $ua->request($request);
1.1182    foxr     2620:     my $content = $response->content;
                   2621: 
                   2622: 
1.944     foxr     2623:     if (wantarray) {
1.1173    foxr     2624: 	return ($content, $response);
1.944     foxr     2625:     } else {
1.1173    foxr     2626: 	return $content;
1.942     foxr     2627:     }
1.324     www      2628: }
                   2629: 
                   2630: sub externalssi {
                   2631:     my ($url)=@_;
                   2632:     my $ua=new LWP::UserAgent;
                   2633:     my $request=new HTTP::Request('GET',$url);
                   2634:     my $response=$ua->request($request);
1.954     raeburn  2635:     if (wantarray) {
                   2636:         return ($response->content, $response);
                   2637:     } else {
                   2638:         return $response->content;
                   2639:     }
1.15      www      2640: }
1.254     www      2641: 
1.492     albertel 2642: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2643: 
                   2644: sub allowuploaded {
                   2645:     my ($srcurl,$url)=@_;
                   2646:     $url=&clutter(&declutter($url));
                   2647:     my $dir=$url;
                   2648:     $dir=~s/\/[^\/]+$//;
                   2649:     my %httpref=();
                   2650:     my $httpurl=&hreflocation('',$url);
                   2651:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2652:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2653: }
1.477     raeburn  2654: 
1.1193    raeburn  2655: #
                   2656: # Determine if the current user should be able to edit a particular resource,
                   2657: # when viewing in course context.
                   2658: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2659: #     Functions.
                   2660: # (b) When displaying folder contents in course editor, used to determine if
                   2661: #     "Edit" link will be displayed alongside resource.
                   2662: #
1.1196    raeburn  2663: #  input: six args -- filename (decluttered), course number, course domain,
                   2664: #                   url, symb (if registered) and group (if this is a group
                   2665: #                   item -- e.g., bulletin board, group page etc.).
                   2666: #  output: array of five scalars -- 
1.1193    raeburn  2667: #          $cfile -- url for file editing if editable on current server
                   2668: #          $home -- homeserver of resource (i.e., for author if published,
                   2669: #                                           or course if uploaded.).
                   2670: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2671: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2672: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2673: #
                   2674: 
                   2675: sub can_edit_resource {
1.1194    raeburn  2676:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2677:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2678: #
                   2679: # For aboutme pages user can only edit his/her own.
                   2680: #
1.1199    raeburn  2681:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2682:         my ($sdom,$sname) = ($1,$2);
                   2683:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2684:             $home = $env{'user.home'};
                   2685:             $cfile = $resurl;
                   2686:             if ($env{'form.forceedit'}) {
                   2687:                 $forceview = 1;
                   2688:             } else {
                   2689:                 $forceedit = 1;
                   2690:             }
                   2691:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2692:         } else {
                   2693:             return;
                   2694:         }
                   2695:     }
                   2696: 
                   2697:     if ($env{'request.course.id'}) {
                   2698:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2699:         if ($group ne '') {
                   2700: # if this is a group homepage or group bulletin board, check group privs
                   2701:             my $allowed = 0;
1.1197    raeburn  2702:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2703:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2704:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2705:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2706:                     $allowed = 1;
                   2707:                 }
1.1197    raeburn  2708:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2709:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2710:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2711:                     $allowed = 1;
                   2712:                 }
                   2713:             }
                   2714:             if ($allowed) {
                   2715:                 $home=&homeserver($cnum,$cdom);
                   2716:                 if ($env{'form.forceedit'}) {
                   2717:                     $forceview = 1;
                   2718:                 } else {
                   2719:                     $forceedit = 1;
                   2720:                 }
                   2721:                 $cfile = $resurl;
                   2722:             } else {
                   2723:                 return;
                   2724:             }
                   2725:         } else {
1.1208    raeburn  2726:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2727:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2728:                     return;
                   2729:                 }
                   2730:             } elsif (!$crsedit) {
1.1194    raeburn  2731: #
                   2732: # No edit allowed where CC has switched to student role.
                   2733: #
                   2734:                 return;
                   2735:             }
                   2736:         }
                   2737:     }
                   2738: 
1.1193    raeburn  2739:     if ($file ne '') {
                   2740:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2741:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2742:                 $uploaded = 1;
                   2743:                 $incourse = 1;
1.1193    raeburn  2744:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2745:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2746:                     if ($env{'form.forceedit'}) {
                   2747:                         $forceview = 1;
                   2748:                     } else {
                   2749:                         $forceedit = 1;
                   2750:                     }
1.1194    raeburn  2751:                 }
                   2752:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2753:                 $incourse = 1;
                   2754:                 if ($env{'form.forceedit'}) {
                   2755:                     $forceview = 1;
                   2756:                 } else {
                   2757:                     $forceedit = 1;
                   2758:                 }
                   2759:                 $cfile = $resurl;
                   2760:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2761:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2762:                     $incourse = 1;
                   2763:                     if ($env{'form.forceedit'}) {
                   2764:                         $forceview = 1;
                   2765:                     } else {
                   2766:                         $forceedit = 1;
                   2767:                     }
                   2768:                     $cfile = $resurl;
1.1199    raeburn  2769:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2770:                     $incourse = 1;
                   2771:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2772:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2773:                     $incourse = 1;
1.1199    raeburn  2774:                     if ($env{'form.forceedit'}) {
                   2775:                         $forceview = 1;
                   2776:                     } else {
                   2777:                         $forceedit = 1;
                   2778:                     }
                   2779:                     $cfile = $resurl;
1.1208    raeburn  2780:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2781:                     $incourse = 1;
                   2782:                     if ($env{'form.forceedit'}) {
                   2783:                         $forceview = 1;
                   2784:                     } else {
                   2785:                         $forceedit = 1;
                   2786:                     }
                   2787:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2788:                 }
                   2789:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2790:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2791:                 if (&is_on_map($template)) { 
                   2792:                     $incourse = 1;
                   2793:                     $forceview = 1;
                   2794:                     $cfile = $template;
1.1193    raeburn  2795:                 }
1.1199    raeburn  2796:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2797:                     $incourse = 1;
                   2798:                     if ($env{'form.forceedit'}) {
                   2799:                         $forceview = 1;
                   2800:                     } else {
                   2801:                         $forceedit = 1;
                   2802:                     }
                   2803:                     $cfile = $resurl;
                   2804:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2805:                 $incourse = 1;
                   2806:                 $forceview = 1;
                   2807:                 if ($symb) {
                   2808:                     my ($map,$id,$res)=&decode_symb($symb);
                   2809:                     $env{'request.symb'} = $symb;
                   2810:                     $cfile = &clutter($res);
                   2811:                 } else {
                   2812:                     $cfile = $env{'form.suppurl'};
                   2813:                     $cfile =~ s{^http://}{};
                   2814:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2815:                 }
1.1193    raeburn  2816:             }
                   2817:         }
1.1194    raeburn  2818:         if ($uploaded || $incourse) {
                   2819:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2820:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2821:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2822:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2823:             # Check that the user has permission to edit this resource
                   2824:             my $setpriv = 1;
                   2825:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2826:             if (defined($cfudom)) {
                   2827:                 $home=&homeserver($cfuname,$cfudom);
                   2828:                 $cfile=$file;
                   2829:             }
                   2830:         }
1.1194    raeburn  2831:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2832:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2833:             my @ids=&current_machine_ids();
                   2834:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2835:                 $switchserver=1;
                   2836:             }
                   2837:         }
                   2838:     }
1.1194    raeburn  2839:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2840: }
                   2841: 
                   2842: sub is_course_upload {
                   2843:     my ($file,$cnum,$cdom) = @_;
                   2844:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2845:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2846:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2847:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2848:         return 1;
                   2849:     }
                   2850:     return;
                   2851: }
                   2852: 
1.1194    raeburn  2853: sub in_course {
1.1195    raeburn  2854:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2855:     if ($hideprivileged) {
                   2856:         my $skipuser;
                   2857:         if (&privileged($uname,$udom)) {
                   2858:             $skipuser = 1;
                   2859:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2860:             if ($coursehash{'nothideprivileged'}) {
                   2861:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2862:                     my $user;
                   2863:                     if ($item =~ /:/) {
                   2864:                         $user = $item;
                   2865:                     } else {
                   2866:                         $user = join(':',split(/[\@]/,$item));
                   2867:                     }
                   2868:                     if ($user eq $uname.':'.$udom) {
                   2869:                         undef($skipuser);
                   2870:                         last;
                   2871:                     }
                   2872:                 }
                   2873:             }
                   2874:             if ($skipuser) {
                   2875:                 return 0;
                   2876:             }
                   2877:         }
                   2878:     }
1.1194    raeburn  2879:     $type ||= 'any';
                   2880:     if (!defined($cdom) || !defined($cnum)) {
                   2881:         my $cid  = $env{'request.course.id'};
                   2882:         $cdom = $env{'course.'.$cid.'.domain'};
                   2883:         $cnum = $env{'course.'.$cid.'.num'};
                   2884:     }
                   2885:     my $typesref;
1.1195    raeburn  2886:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  2887:         $typesref = ['active','previous','future'];
                   2888:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2889:         $typesref = [$type];
                   2890:     }
                   2891:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2892:                               $typesref,undef,[$cdom]);
                   2893:     my ($tmp) = keys(%roles);
                   2894:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2895:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2896:     if (@course_roles > 0) {
                   2897:         return 1;
                   2898:     }
                   2899:     return 0;
                   2900: }
                   2901: 
1.478     albertel 2902: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2903: # input: action, courseID, current domain, intended
1.637     raeburn  2904: #        path to file, source of file, instruction to parse file for objects,
                   2905: #        ref to hash for embedded objects,
                   2906: #        ref to hash for codebase of java objects.
1.1095    raeburn  2907: #        reference to scalar to accommodate mime type determined
                   2908: #          from File::MMagic if $parser = parse.
1.637     raeburn  2909: #
1.485     raeburn  2910: # output: url to file (if action was uploaddoc), 
                   2911: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2912: #
1.478     albertel 2913: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2914: # course.
1.477     raeburn  2915: #
1.478     albertel 2916: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2917: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2918: #          course's home server.
1.477     raeburn  2919: #
1.478     albertel 2920: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2921: #          be copied from $source (current location) to 
                   2922: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2923: #         and will then be copied to
                   2924: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2925: #         course's home server.
1.485     raeburn  2926: #
1.481     raeburn  2927: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2928: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2929: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2930: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2931: #         in course's home server.
1.637     raeburn  2932: #
1.477     raeburn  2933: 
                   2934: sub process_coursefile {
1.1095    raeburn  2935:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2936:         $mimetype)=@_;
1.477     raeburn  2937:     my $fetchresult;
1.638     albertel 2938:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2939:     if ($action eq 'propagate') {
1.638     albertel 2940:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2941: 			     $home);
1.481     raeburn  2942:     } else {
1.477     raeburn  2943:         my $fpath = '';
                   2944:         my $fname = $file;
1.478     albertel 2945:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2946:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2947:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2948:         if ($action eq 'copy') {
                   2949:             if ($source eq '') {
                   2950:                 $fetchresult = 'no source file';
                   2951:                 return $fetchresult;
                   2952:             } else {
                   2953:                 my $destination = $filepath.'/'.$fname;
                   2954:                 rename($source,$destination);
                   2955:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2956:                                  $home);
1.481     raeburn  2957:             }
                   2958:         } elsif ($action eq 'uploaddoc') {
                   2959:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2960:             print $fh $env{'form.'.$source};
1.481     raeburn  2961:             close($fh);
1.637     raeburn  2962:             if ($parser eq 'parse') {
1.1024    raeburn  2963:                 my $mm = new File::MMagic;
1.1095    raeburn  2964:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2965:                 if ($type eq 'text/html') {
1.1024    raeburn  2966:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2967:                     unless ($parse_result eq 'ok') {
                   2968:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2969:                     }
1.637     raeburn  2970:                 }
1.1095    raeburn  2971:                 if (ref($mimetype)) {
                   2972:                     $$mimetype = $type;
                   2973:                 } 
1.637     raeburn  2974:             }
1.477     raeburn  2975:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2976:                                  $home);
1.481     raeburn  2977:             if ($fetchresult eq 'ok') {
                   2978:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2979:             } else {
                   2980:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2981:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2982:                 return '/adm/notfound.html';
                   2983:             }
1.477     raeburn  2984:         }
                   2985:     }
1.485     raeburn  2986:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2987:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2988:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2989:     }
                   2990:     return $fetchresult;
                   2991: }
                   2992: 
1.637     raeburn  2993: sub build_filepath {
                   2994:     my ($fpath) = @_;
                   2995:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2996:     unless ($fpath eq '') {
                   2997:         my @parts=split('/',$fpath);
                   2998:         foreach my $part (@parts) {
                   2999:             $filepath.= '/'.$part;
                   3000:             if ((-e $filepath)!=1) {
                   3001:                 mkdir($filepath,0777);
                   3002:             }
                   3003:         }
                   3004:     }
                   3005:     return $filepath;
                   3006: }
                   3007: 
                   3008: sub store_edited_file {
1.638     albertel 3009:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3010:     my $file = $primary_url;
                   3011:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3012:     my $fpath = '';
                   3013:     my $fname = $file;
                   3014:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3015:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3016:     my $filepath = &build_filepath($fpath);
                   3017:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3018:     print $fh $content;
                   3019:     close($fh);
1.638     albertel 3020:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3021:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3022: 			  $home);
1.637     raeburn  3023:     if ($$fetchresult eq 'ok') {
                   3024:         return '/uploaded/'.$fpath.'/'.$fname;
                   3025:     } else {
1.638     albertel 3026:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3027: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3028:         return '/adm/notfound.html';
                   3029:     }
                   3030: }
                   3031: 
1.531     albertel 3032: sub clean_filename {
1.831     albertel 3033:     my ($fname,$args)=@_;
1.315     www      3034: # Replace Windows backslashes by forward slashes
1.257     www      3035:     $fname=~s/\\/\//g;
1.831     albertel 3036:     if (!$args->{'keep_path'}) {
                   3037:         # Get rid of everything but the actual filename
                   3038: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3039:     }
1.315     www      3040: # Replace spaces by underscores
                   3041:     $fname=~s/\s+/\_/g;
                   3042: # Replace all other weird characters by nothing
1.831     albertel 3043:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3044: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3045: # numbers
                   3046:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3047:     return $fname;
                   3048: }
1.1051    raeburn  3049: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3050: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3051: # image with the same aspect ratio as the original, but with dimensions which do 
                   3052: # not exceed $resizewidth and $resizeheight.
                   3053:  
1.984     neumanie 3054: sub resizeImage {
1.1051    raeburn  3055:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3056:     my $ima = Image::Magick->new;
                   3057:     my $resized;
                   3058:     if (-e $img_path) {
                   3059:         $ima->Read($img_path);
                   3060:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3061:             my $width = $ima->Get('width');
                   3062:             my $height = $ima->Get('height');
                   3063:             if ($width > $resizewidth) {
                   3064: 	        my $factor = $width/$resizewidth;
                   3065:                 my $newheight = $height/$factor;
                   3066:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3067:                 $resized = 1;
                   3068:             }
                   3069:         }
                   3070:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3071:             my $width = $ima->Get('width');
                   3072:             my $height = $ima->Get('height');
                   3073:             if ($height > $resizeheight) {
                   3074:                 my $factor = $height/$resizeheight;
                   3075:                 my $newwidth = $width/$factor;
                   3076:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3077:                 $resized = 1;
                   3078:             }
                   3079:         }
                   3080:         if ($resized) {
                   3081:             $ima->Write($img_path);
                   3082:         }
                   3083:     }
                   3084:     return;
1.977     amueller 3085: }
                   3086: 
1.608     albertel 3087: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3088: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3089: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3090: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3091: #                                    canceloverwrite, or ''. 
                   3092: #                   if 'coursedoc': upload to the current course
                   3093: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3094: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3095: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3096: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3097: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3098: #        $allfiles - reference to hash for embedded objects
                   3099: #        $codebase - reference to hash for codebase of java objects
                   3100: #        $desuname - username for permanent storage of uploaded file
                   3101: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3102: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3103: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3104: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3105: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3106: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3107: #                    from File::MMagic.
1.858     raeburn  3108: # 
1.686     albertel 3109: # output: url of file in userspace, or error: <message> 
                   3110: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3111: 
1.531     albertel 3112: sub userfileupload {
1.1090    raeburn  3113:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3114:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3115:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3116:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3117:     $fname=&clean_filename($fname);
1.1090    raeburn  3118:     # See if there is anything left
1.257     www      3119:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3120:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3121:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3122:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3123:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3124:         my $now = time;
1.1090    raeburn  3125:         my $filepath;
1.1095    raeburn  3126:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3127:              $filepath = 'tmp/helprequests/'.$now;
                   3128:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3129:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3130:                          '_'.$env{'user.domain'}.'/pending';
                   3131:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3132:             my ($docuname,$docudom);
                   3133:             if ($destudom) {
                   3134:                 $docudom = $destudom;
                   3135:             } else {
                   3136:                 $docudom = $env{'user.domain'};
                   3137:             }
                   3138:             if ($destuname) {
                   3139:                 $docuname = $destuname;
                   3140:             } else {
                   3141:                 $docuname = $env{'user.name'};
                   3142:             }
                   3143:             if (exists($env{'form.group'})) {
                   3144:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3145:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3146:             }
                   3147:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3148:             if ($context eq 'canceloverwrite') {
                   3149:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3150:                 if (-e  $tempfile) {
                   3151:                     my @info = stat($tempfile);
                   3152:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3153:                         unlink($tempfile);
                   3154:                     }
                   3155:                 }
                   3156:                 return;
1.523     raeburn  3157:             }
                   3158:         }
1.1090    raeburn  3159:         # Create the directory if not present
1.741     raeburn  3160:         my @parts=split(/\//,$filepath);
                   3161:         my $fullpath = $perlvar{'lonDaemons'};
                   3162:         for (my $i=0;$i<@parts;$i++) {
                   3163:             $fullpath .= '/'.$parts[$i];
                   3164:             if ((-e $fullpath)!=1) {
                   3165:                 mkdir($fullpath,0777);
                   3166:             }
                   3167:         }
                   3168:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3169:         print $fh $env{'form.'.$formname};
                   3170:         close($fh);
1.1090    raeburn  3171:         if ($context eq 'existingfile') {
                   3172:             my @info = stat($fullpath.'/'.$fname);
                   3173:             return ($fullpath.'/'.$fname,$info[9]);
                   3174:         } else {
                   3175:             return $fullpath.'/'.$fname;
                   3176:         }
1.523     raeburn  3177:     }
1.995     raeburn  3178:     if ($subdir eq 'scantron') {
                   3179:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3180:     } else {
1.995     raeburn  3181:         $fname="$subdir/$fname";
                   3182:     }
1.1090    raeburn  3183:     if ($context eq 'coursedoc') {
1.638     albertel 3184: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3185: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3186:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3187:             return &finishuserfileupload($docuname,$docudom,
                   3188: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3189: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3190:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3191:         } else {
1.620     albertel 3192:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 3193:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3194: 				       $fname,$formname,$parser,
1.1095    raeburn  3195: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3196:         }
1.719     banghart 3197:     } elsif (defined($destuname)) {
                   3198:         my $docuname=$destuname;
                   3199:         my $docudom=$destudom;
1.860     raeburn  3200: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3201: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3202:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3203:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3204:     } else {
1.638     albertel 3205:         my $docuname=$env{'user.name'};
                   3206:         my $docudom=$env{'user.domain'};
1.714     raeburn  3207:         if (exists($env{'form.group'})) {
                   3208:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3209:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3210:         }
1.860     raeburn  3211: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3212: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3213:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3214:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3215:     }
1.271     www      3216: }
                   3217: 
                   3218: sub finishuserfileupload {
1.860     raeburn  3219:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3220:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3221:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3222:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3223:   
1.860     raeburn  3224:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3225:     $file=$fname;
                   3226:     if ($fname=~m|/|) {
                   3227:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3228: 	$path.=$fnamepath.'/';
                   3229:     }
1.259     www      3230:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3231:     my $count;
                   3232:     for ($count=4;$count<=$#parts;$count++) {
                   3233:         $filepath.="/$parts[$count]";
                   3234:         if ((-e $filepath)!=1) {
                   3235: 	    mkdir($filepath,0777);
                   3236:         }
                   3237:     }
1.984     neumanie 3238: 
1.258     www      3239: # Save the file
                   3240:     {
1.701     albertel 3241: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3242: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3243: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3244: 	    return '/adm/notfound.html';
                   3245: 	}
1.1090    raeburn  3246:         if ($context eq 'overwrite') {
1.1117    foxr     3247:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3248:             my $target = $filepath.'/'.$file;
                   3249:             if (-e $source) {
                   3250:                 my @info = stat($source);
                   3251:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3252:                     unless (&File::Copy::move($source,$target)) {
                   3253:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3254:                         return "Moving from $source failed";
                   3255:                     }
                   3256:                 } else {
                   3257:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3258:                 }
                   3259:             } else {
                   3260:                 return "Temporary file: $source missing";
                   3261:             }
                   3262:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3263: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3264: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3265: 	    return '/adm/notfound.html';
                   3266: 	}
1.570     albertel 3267: 	close(FH);
1.1051    raeburn  3268:         if ($resizewidth && $resizeheight) {
                   3269:             my $mm = new File::MMagic;
                   3270:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3271:             if ($mime_type =~ m{^image/}) {
                   3272: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3273:             }  
1.977     amueller 3274: 	}
1.258     www      3275:     }
1.1152    raeburn  3276:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3277:         if (ref($mimetype)) {
                   3278:             if ($$mimetype eq '') {
                   3279:                 my $mm = new File::MMagic;
                   3280:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3281:                 $$mimetype = $type;
                   3282:             }
                   3283:         }
                   3284:     }
1.637     raeburn  3285:     if ($parser eq 'parse') {
1.1152    raeburn  3286:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3287:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3288:                                                        $allfiles,$codebase);
                   3289:             unless ($parse_result eq 'ok') {
                   3290:                 &logthis('Failed to parse '.$filepath.$file.
                   3291: 	   	         ' for embedded media: '.$parse_result); 
                   3292:             }
1.637     raeburn  3293:         }
                   3294:     }
1.860     raeburn  3295:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3296:         my $input = $filepath.'/'.$file;
                   3297:         my $output = $filepath.'/'.'tn-'.$file;
                   3298:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3299:         system("convert -sample $thumbsize $input $output");
                   3300:         if (-e $filepath.'/'.'tn-'.$file) {
                   3301:             $fetchthumb  = 1; 
                   3302:         }
                   3303:     }
1.858     raeburn  3304:  
1.259     www      3305: # Notify homeserver to grep it
                   3306: #
1.984     neumanie 3307:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3308:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3309:     if ($fetchresult eq 'ok') {
1.860     raeburn  3310:         if ($fetchthumb) {
                   3311:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3312:             if ($thumbresult ne 'ok') {
                   3313:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3314:                          $docuhome.': '.$thumbresult);
                   3315:             }
                   3316:         }
1.259     www      3317: #
1.258     www      3318: # Return the URL to it
1.494     albertel 3319:         return '/uploaded/'.$path.$file;
1.263     www      3320:     } else {
1.494     albertel 3321:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3322: 		 ': '.$fetchresult);
1.263     www      3323:         return '/adm/notfound.html';
1.858     raeburn  3324:     }
1.493     albertel 3325: }
                   3326: 
1.637     raeburn  3327: sub extract_embedded_items {
1.961     raeburn  3328:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3329:     my @state = ();
1.1164    raeburn  3330:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3331:     my %javafiles = (
                   3332:                       codebase => '',
                   3333:                       code => '',
                   3334:                       archive => ''
                   3335:                     );
                   3336:     my %mediafiles = (
                   3337:                       src => '',
                   3338:                       movie => '',
                   3339:                      );
1.648     raeburn  3340:     my $p;
                   3341:     if ($content) {
                   3342:         $p = HTML::LCParser->new($content);
                   3343:     } else {
1.961     raeburn  3344:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3345:     }
1.641     albertel 3346:     while (my $t=$p->get_token()) {
1.640     albertel 3347: 	if ($t->[0] eq 'S') {
                   3348: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3349: 	    push(@state, $tagname);
1.648     raeburn  3350:             if (lc($tagname) eq 'allow') {
                   3351:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3352:             }
1.640     albertel 3353: 	    if (lc($tagname) eq 'img') {
                   3354: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3355: 	    }
1.886     albertel 3356: 	    if (lc($tagname) eq 'a') {
                   3357: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3358: 	    }
1.645     raeburn  3359:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3360:                 my $src;
1.645     raeburn  3361:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3362:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3363:                 } else {
1.1164    raeburn  3364:                     if ($attr->{'src'} ne '') {
                   3365:                         $src = $attr->{'src'};
                   3366:                         &add_filetype($allfiles,$src,'src');
                   3367:                     }
                   3368:                 }
                   3369:                 my $text = $p->get_trimmed_text();
                   3370:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3371:                     my @swfargs = split(/,/,$1);
                   3372:                     foreach my $item (@swfargs) {
                   3373:                         $item =~ s/["']//g;
                   3374:                         $item =~ s/^\s+//;
                   3375:                         $item =~ s/\s+$//;
                   3376:                     }
                   3377:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3378:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3379:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3380:                         } else {
                   3381:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3382:                         }
                   3383:                     }
1.645     raeburn  3384:                 }
                   3385:             }
                   3386:             if (lc($tagname) eq 'link') {
                   3387:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3388:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3389:                 }
                   3390:             }
1.640     albertel 3391: 	    if (lc($tagname) eq 'object' ||
                   3392: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3393: 		foreach my $item (keys(%javafiles)) {
                   3394: 		    $javafiles{$item} = '';
                   3395: 		}
1.1164    raeburn  3396:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3397:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3398:                 }
1.640     albertel 3399: 	    }
                   3400: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3401: 		my $name = lc($attr->{'name'});
                   3402: 		foreach my $item (keys(%javafiles)) {
                   3403: 		    if ($name eq $item) {
                   3404: 			$javafiles{$item} = $attr->{'value'};
                   3405: 			last;
                   3406: 		    }
                   3407: 		}
1.1164    raeburn  3408:                 my $pathfrom;
1.640     albertel 3409: 		foreach my $item (keys(%mediafiles)) {
                   3410: 		    if ($name eq $item) {
1.1164    raeburn  3411:                         $pathfrom = $attr->{'value'};
                   3412:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3413: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3414: 			last;
                   3415: 		    }
                   3416: 		}
1.1164    raeburn  3417:                 if ($name eq 'flashvars') {
                   3418:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3419:                 }
                   3420:                 if ($pathfrom ne '') {
                   3421:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3422:                                          $pathfrom);
                   3423:                 }
1.640     albertel 3424: 	    }
                   3425: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3426: 		foreach my $item (keys(%javafiles)) {
                   3427: 		    if ($attr->{$item}) {
                   3428: 			$javafiles{$item} = $attr->{$item};
                   3429: 			last;
                   3430: 		    }
                   3431: 		}
                   3432: 		foreach my $item (keys(%mediafiles)) {
                   3433: 		    if ($attr->{$item}) {
                   3434: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3435: 			last;
                   3436: 		    }
                   3437: 		}
1.1164    raeburn  3438:                 if (lc($tagname) eq 'embed') {
                   3439:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3440:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3441:                                              $attr->{'src'});
                   3442:                     }
                   3443:                 }
1.640     albertel 3444: 	    }
1.1164    raeburn  3445:             if ($t->[4] =~ m{/>$}) {
                   3446:                 pop(@state);  
                   3447:             }
1.640     albertel 3448: 	} elsif ($t->[0] eq 'E') {
                   3449: 	    my ($tagname) = ($t->[1]);
                   3450: 	    if ($javafiles{'codebase'} ne '') {
                   3451: 		$javafiles{'codebase'} .= '/';
                   3452: 	    }  
                   3453: 	    if (lc($tagname) eq 'applet' ||
                   3454: 		lc($tagname) eq 'object' ||
                   3455: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3456: 		) {
                   3457: 		foreach my $item (keys(%javafiles)) {
                   3458: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3459: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3460: 			&add_filetype($allfiles,$file,$item);
                   3461: 		    }
                   3462: 		}
                   3463: 	    } 
                   3464: 	    pop @state;
                   3465: 	}
                   3466:     }
1.1164    raeburn  3467:     foreach my $id (sort(keys(%flashvars))) {
                   3468:         if ($shockwave{$id} ne '') {
                   3469:             my @pairs = split(/\&/,$flashvars{$id});
                   3470:             foreach my $pair (@pairs) {
                   3471:                 my ($key,$value) = split(/\=/,$pair);
                   3472:                 if ($key eq 'thumb') {
                   3473:                     &add_filetype($allfiles,$value,$key);
                   3474:                 } elsif ($key eq 'content') {
                   3475:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3476:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3477:                     if ($ext ne '') {
                   3478:                         &add_filetype($allfiles,$path.$value,$ext);
                   3479:                     }
                   3480:                 }
                   3481:             }
                   3482:         }
                   3483:     }
1.637     raeburn  3484:     return 'ok';
                   3485: }
                   3486: 
1.639     albertel 3487: sub add_filetype {
                   3488:     my ($allfiles,$file,$type)=@_;
                   3489:     if (exists($allfiles->{$file})) {
                   3490: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3491: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3492: 	}
                   3493:     } else {
                   3494: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3495:     }
                   3496: }
                   3497: 
1.1164    raeburn  3498: sub embedded_dependency {
                   3499:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3500:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3501:         if (($identifier ne '') &&
                   3502:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3503:             ($pathfrom ne '')) {
                   3504:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3505:             foreach my $dep (@{$related->{$identifier}}) {
                   3506:                 &add_filetype($allfiles,$path.$dep,'object');
                   3507:             }
                   3508:         }
                   3509:     }
                   3510:     return;
                   3511: }
                   3512: 
1.493     albertel 3513: sub removeuploadedurl {
1.984     neumanie 3514:     my ($url)=@_;	
                   3515:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3516:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3517: }
                   3518: 
                   3519: sub removeuserfile {
                   3520:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3521:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3522:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3523:     if ($result eq 'ok') {	
1.798     raeburn  3524:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3525:             my $metafile = $fname.'.meta';
                   3526:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3527: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3528:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3529:             my $sqlresult = 
1.823     albertel 3530:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3531:                                         'portfolio_metadata',$group,
                   3532:                                         'delete');
1.798     raeburn  3533:         }
                   3534:     }
                   3535:     return $result;
1.257     www      3536: }
1.15      www      3537: 
1.530     albertel 3538: sub mkdiruserfile {
                   3539:     my ($docuname,$docudom,$dir)=@_;
                   3540:     my $home=&homeserver($docuname,$docudom);
                   3541:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3542: }
                   3543: 
1.531     albertel 3544: sub renameuserfile {
                   3545:     my ($docuname,$docudom,$old,$new)=@_;
                   3546:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3547:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3548:                         &escape("$old").':'.&escape("$new"),$home);
                   3549:     if ($result eq 'ok') {
                   3550:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3551:             my $oldmeta = $old.'.meta';
                   3552:             my $newmeta = $new.'.meta';
                   3553:             my $metaresult = 
                   3554:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3555: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3556:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3557:             my $sqlresult = 
1.823     albertel 3558:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3559:                                         'portfolio_metadata',$group,
                   3560:                                         'delete');
1.798     raeburn  3561:         }
                   3562:     }
                   3563:     return $result;
1.531     albertel 3564: }
                   3565: 
1.14      www      3566: # ------------------------------------------------------------------------- Log
                   3567: 
                   3568: sub log {
                   3569:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3570:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3571: }
                   3572: 
                   3573: # ------------------------------------------------------------------ Course Log
1.352     www      3574: #
                   3575: # This routine flushes several buffers of non-mission-critical nature
                   3576: #
1.157     www      3577: 
                   3578: sub flushcourselogs {
1.352     www      3579:     &logthis('Flushing log buffers');
                   3580: #
                   3581: # course logs
                   3582: # This is a log of all transactions in a course, which can be used
                   3583: # for data mining purposes
                   3584: #
                   3585: # It also collects the courseid database, which lists last transaction
                   3586: # times and course titles for all courseids
                   3587: #
                   3588:     my %courseidbuffer=();
1.921     raeburn  3589:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3590:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3591: 		          &escape($courselogs{$crsid}),
                   3592: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3593: 	    delete $courselogs{$crsid};
                   3594:         } else {
                   3595:             &logthis('Failed to flush log buffer for '.$crsid);
                   3596:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3597:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3598:                         " exceeded maximum size, deleting.</font>");
                   3599:                delete $courselogs{$crsid};
                   3600:             }
1.352     www      3601:         }
1.920     raeburn  3602:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3603:             'description' => $coursedescrbuf{$crsid},
                   3604:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3605:             'type'        => $coursetypebuf{$crsid},
                   3606:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3607:         };
1.191     harris41 3608:     }
1.352     www      3609: #
                   3610: # Write course id database (reverse lookup) to homeserver of courses 
                   3611: # Is used in pickcourse
                   3612: #
1.840     albertel 3613:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3614:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3615:                                     $courseidbuffer{$crs_home},
                   3616:                                     $crs_home,'timeonly');
1.352     www      3617:     }
                   3618: #
                   3619: # File accesses
                   3620: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3621: #
1.449     matthew  3622:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3623:         if ($entry =~ /___count$/) {
                   3624:             my ($dom,$name);
1.807     albertel 3625:             ($dom,$name,undef)=
1.811     albertel 3626: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3627:             if (! defined($dom) || $dom eq '' || 
                   3628:                 ! defined($name) || $name eq '') {
1.620     albertel 3629:                 my $cid = $env{'request.course.id'};
                   3630:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3631:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3632:             }
1.450     matthew  3633:             my $value = $accesshash{$entry};
                   3634:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3635:             my %temphash=($url => $value);
1.449     matthew  3636:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3637:             if ($result eq 'ok') {
                   3638:                 delete $accesshash{$entry};
                   3639:             }
                   3640:         } else {
1.811     albertel 3641:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3642:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3643:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3644:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3645:                 delete $accesshash{$entry};
                   3646:             }
1.185     www      3647:         }
1.191     harris41 3648:     }
1.352     www      3649: #
                   3650: # Roles
                   3651: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3652: #
1.800     albertel 3653:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3654:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3655: 	    split(/\:/,$entry);
                   3656:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3657:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3658:                 $rudom,$runame) eq 'ok') {
                   3659: 	    delete $userrolehash{$entry};
                   3660:         }
                   3661:     }
1.662     raeburn  3662: #
                   3663: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3664: #
                   3665:     my %domrolebuffer = ();
1.1000    raeburn  3666:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3667:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3668:         if ($domrolebuffer{$rudom}) {
                   3669:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3670:                       '='.&escape($domainrolehash{$entry});
                   3671:         } else {
                   3672:             $domrolebuffer{$rudom}.=&escape($entry).
                   3673:                       '='.&escape($domainrolehash{$entry});
                   3674:         }
                   3675:         delete $domainrolehash{$entry};
                   3676:     }
                   3677:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3678: 	my %servers = &get_servers($dom,'library');
                   3679: 	foreach my $tryserver (keys(%servers)) {
                   3680: 	    unless (&reply('domroleput:'.$dom.':'.
                   3681: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3682: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3683: 	    }
1.662     raeburn  3684:         }
                   3685:     }
1.186     www      3686:     $dumpcount++;
1.157     www      3687: }
                   3688: 
                   3689: sub courselog {
                   3690:     my $what=shift;
1.158     www      3691:     $what=time.':'.$what;
1.620     albertel 3692:     unless ($env{'request.course.id'}) { return ''; }
                   3693:     $coursedombuf{$env{'request.course.id'}}=
                   3694:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3695:     $coursenumbuf{$env{'request.course.id'}}=
                   3696:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3697:     $coursehombuf{$env{'request.course.id'}}=
                   3698:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3699:     $coursedescrbuf{$env{'request.course.id'}}=
                   3700:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3701:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3702:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3703:     $courseownerbuf{$env{'request.course.id'}}=
                   3704:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3705:     $coursetypebuf{$env{'request.course.id'}}=
                   3706:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3707:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3708: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3709:     } else {
1.620     albertel 3710: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3711:     }
1.620     albertel 3712:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3713: 	&flushcourselogs();
                   3714:     }
1.158     www      3715: }
                   3716: 
                   3717: sub courseacclog {
                   3718:     my $fnsymb=shift;
1.620     albertel 3719:     unless ($env{'request.course.id'}) { return ''; }
                   3720:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3721:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3722:         $what.=':POST';
1.583     matthew  3723:         # FIXME: Probably ought to escape things....
1.800     albertel 3724: 	foreach my $key (keys(%env)) {
                   3725:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3726:                 my $formitem = $1;
                   3727:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3728:                     $what.=':'.$formitem.'='.$env{$key};
                   3729:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3730:                     $what.=':'.$formitem.'='.$env{$key};
                   3731:                 }
1.158     www      3732:             }
1.191     harris41 3733:         }
1.583     matthew  3734:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3735:         # FIXME: We should not be depending on a form parameter that someone
                   3736:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3737:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3738:             $what.= ':POST';
                   3739:             # FIXME: Probably ought to escape things....
                   3740:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3741:                                  'crsdiscuss') {
1.620     albertel 3742:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3743:             }
                   3744:         }
1.158     www      3745:     }
                   3746:     &courselog($what);
1.149     www      3747: }
                   3748: 
1.185     www      3749: sub countacc {
                   3750:     my $url=&declutter(shift);
1.458     matthew  3751:     return if (! defined($url) || $url eq '');
1.620     albertel 3752:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3753: #
                   3754: # Mark that this url was used in this course
                   3755: #
1.620     albertel 3756:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3757: #
                   3758: # Increase the access count for this resource in this child process
                   3759: #
1.281     www      3760:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3761:     $accesshash{$key}++;
1.185     www      3762: }
1.349     www      3763: 
1.361     www      3764: sub linklog {
                   3765:     my ($from,$to)=@_;
                   3766:     $from=&declutter($from);
                   3767:     $to=&declutter($to);
                   3768:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3769:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3770: }
1.1160    www      3771: 
                   3772: sub statslog {
                   3773:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3774:     if ($users<2) { return; }
                   3775:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3776:             'course'       => $env{'request.course.id'},
                   3777:             'sections'     => '"all"',
                   3778:             'num_students' => $users,
                   3779:             'part'         => $part,
                   3780:             'symb'         => $symb,
                   3781:             'mean_tries'   => $av_attempts,
                   3782:             'deg_of_diff'  => $degdiff});
                   3783:     foreach my $key (keys(%dynstore)) {
                   3784:         $accesshash{$key}=$dynstore{$key};
                   3785:     }
                   3786: }
1.361     www      3787:   
1.349     www      3788: sub userrolelog {
                   3789:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3790:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3791:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3792:        $userrolehash
                   3793:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3794:                     =$tend.':'.$tstart;
1.662     raeburn  3795:     }
1.1169    droeschl 3796:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3797:        $userrolehash
                   3798:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3799:                     =$tend.':'.$tstart;
                   3800:     }
1.1169    droeschl 3801:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3802:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3803:        $domainrolehash
                   3804:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3805:                     = $tend.':'.$tstart;
                   3806:     }
1.351     www      3807: }
                   3808: 
1.957     raeburn  3809: sub courserolelog {
                   3810:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3811:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3812:         my $cdom = $1;
                   3813:         my $cnum = $2;
                   3814:         my $sec = $3;
                   3815:         my $namespace = 'rolelog';
                   3816:         my %storehash = (
                   3817:                            role    => $trole,
                   3818:                            start   => $tstart,
                   3819:                            end     => $tend,
                   3820:                            selfenroll => $selfenroll,
                   3821:                            context    => $context,
                   3822:                         );
                   3823:         if ($trole eq 'gr') {
                   3824:             $namespace = 'groupslog';
                   3825:             $storehash{'group'} = $sec;
                   3826:         } else {
                   3827:             $storehash{'section'} = $sec;
                   3828:         }
1.1188    raeburn  3829:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3830:                    $domain,$cnum,$cdom);
1.1184    raeburn  3831:         if (($trole ne 'st') || ($sec ne '')) {
                   3832:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3833:         }
                   3834:     }
                   3835:     return;
                   3836: }
                   3837: 
1.1184    raeburn  3838: sub domainrolelog {
                   3839:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3840:     if ($area =~ m{^/($match_domain)/$}) {
                   3841:         my $cdom = $1;
                   3842:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3843:         my $namespace = 'rolelog';
                   3844:         my %storehash = (
                   3845:                            role    => $trole,
                   3846:                            start   => $tstart,
                   3847:                            end     => $tend,
                   3848:                            context => $context,
                   3849:                         );
1.1188    raeburn  3850:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3851:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3852:     }
                   3853:     return;
                   3854: 
                   3855: }
                   3856: 
                   3857: sub coauthorrolelog {
                   3858:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3859:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3860:         my $audom = $1;
                   3861:         my $auname = $2;
                   3862:         my $namespace = 'rolelog';
                   3863:         my %storehash = (
                   3864:                            role    => $trole,
                   3865:                            start   => $tstart,
                   3866:                            end     => $tend,
                   3867:                            context => $context,
                   3868:                         );
1.1188    raeburn  3869:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3870:                    $domain,$auname,$audom);
1.1184    raeburn  3871:     }
                   3872:     return;
                   3873: }
                   3874: 
1.351     www      3875: sub get_course_adv_roles {
1.948     raeburn  3876:     my ($cid,$codes) = @_;
1.620     albertel 3877:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3878:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3879:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3880:     my %nothide=();
1.800     albertel 3881:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3882:         if ($user !~ /:/) {
                   3883: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3884:         } else {
                   3885:             $nothide{$user}=1;
                   3886:         }
1.470     www      3887:     }
1.351     www      3888:     my %returnhash=();
                   3889:     my %dumphash=
                   3890:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3891:     my $now=time;
1.997     raeburn  3892:     my %privileged;
1.1000    raeburn  3893:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3894: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3895:         if (($tstart) && ($tstart<0)) { next; }
                   3896:         if (($tend) && ($tend<$now)) { next; }
                   3897:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3898:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3899: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3900:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3901:             my %dompersonnel =
1.998     raeburn  3902:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3903:             $privileged{$domain} = {};
                   3904:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3905:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3906:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3907:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3908:                         $privileged{$udom}{$uname} = 1;
                   3909:                     }
                   3910:                 }
                   3911:             }
                   3912:         }
                   3913:         if ((exists($privileged{$domain}{$username})) && 
                   3914:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3915: 	if ($role eq 'cr') { next; }
1.948     raeburn  3916:         if ($codes) {
                   3917:             if ($section) { $role .= ':'.$section; }
                   3918:             if ($returnhash{$role}) {
                   3919:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3920:             } else {
                   3921:                 $returnhash{$role}=$username.':'.$domain;
                   3922:             }
1.351     www      3923:         } else {
1.988     raeburn  3924:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3925:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3926:             if ($returnhash{$key}) {
                   3927: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3928:             } else {
                   3929:                 $returnhash{$key}=$username.':'.$domain;
                   3930:             }
1.351     www      3931:         }
1.948     raeburn  3932:     }
1.400     www      3933:     return %returnhash;
                   3934: }
                   3935: 
                   3936: sub get_my_roles {
1.937     raeburn  3937:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3938:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3939:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3940:     my (%dumphash,%nothide);
1.1086    raeburn  3941:     if ($context eq 'userroles') {
1.1166    raeburn  3942:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3943:     } else {
                   3944:         %dumphash=
1.400     www      3945:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3946:         if ($hidepriv) {
                   3947:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3948:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3949:                 if ($user !~ /:/) {
                   3950:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3951:                 } else {
                   3952:                     $nothide{$user} = 1;
                   3953:                 }
                   3954:             }
                   3955:         }
1.858     raeburn  3956:     }
1.400     www      3957:     my %returnhash=();
                   3958:     my $now=time;
1.999     raeburn  3959:     my %privileged;
1.800     albertel 3960:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3961:         my ($role,$tend,$tstart);
                   3962:         if ($context eq 'userroles') {
1.1149    raeburn  3963:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3964: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3965:         } else {
                   3966:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3967:         }
1.400     www      3968:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3969:         my $status = 'active';
1.939     raeburn  3970:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3971:             $status = 'previous';
                   3972:         } 
                   3973:         if (($tstart) && ($now<$tstart)) {
                   3974:             $status = 'future';
                   3975:         }
                   3976:         if (ref($types) eq 'ARRAY') {
                   3977:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3978:                 next;
                   3979:             } 
                   3980:         } else {
                   3981:             if ($status ne 'active') {
                   3982:                 next;
                   3983:             }
                   3984:         }
1.867     raeburn  3985:         my ($rolecode,$username,$domain,$section,$area);
                   3986:         if ($context eq 'userroles') {
1.1186    raeburn  3987:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3988:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3989:         } else {
                   3990:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3991:         }
1.832     raeburn  3992:         if (ref($roledoms) eq 'ARRAY') {
                   3993:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3994:                 next;
                   3995:             }
                   3996:         }
                   3997:         if (ref($roles) eq 'ARRAY') {
                   3998:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3999:                 if ($role =~ /^cr\//) {
                   4000:                     if (!grep(/^cr$/,@{$roles})) {
                   4001:                         next;
                   4002:                     }
1.1104    raeburn  4003:                 } elsif ($role =~ /^gr\//) {
                   4004:                     if (!grep(/^gr$/,@{$roles})) {
                   4005:                         next;
                   4006:                     }
1.922     raeburn  4007:                 } else {
                   4008:                     next;
                   4009:                 }
1.832     raeburn  4010:             }
1.867     raeburn  4011:         }
1.937     raeburn  4012:         if ($hidepriv) {
1.999     raeburn  4013:             if ($context eq 'userroles') {
                   4014:                 if ((&privileged($username,$domain)) &&
                   4015:                     (!$nothide{$username.':'.$domain})) {
                   4016:                     next;
                   4017:                 }
                   4018:             } else {
                   4019:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   4020:                     my %dompersonnel =
                   4021:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   4022:                     $privileged{$domain} = {};
                   4023:                     if (keys(%dompersonnel)) {
                   4024:                         foreach my $server (keys(%dompersonnel)) {
                   4025:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   4026:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   4027:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   4028:                                     $privileged{$udom}{$uname} = $trole;
                   4029:                                 }
                   4030:                             }
                   4031:                         }
                   4032:                     }
                   4033:                 }
                   4034:                 if (exists($privileged{$domain}{$username})) {
                   4035:                     if (!$nothide{$username.':'.$domain}) {
                   4036:                         next;
                   4037:                     }
                   4038:                 }
1.937     raeburn  4039:             }
                   4040:         }
1.933     raeburn  4041:         if ($withsec) {
                   4042:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4043:                 $tstart.':'.$tend;
                   4044:         } else {
                   4045:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4046:         }
1.832     raeburn  4047:     }
1.373     www      4048:     return %returnhash;
1.399     www      4049: }
                   4050: 
                   4051: # ----------------------------------------------------- Frontpage Announcements
                   4052: #
                   4053: #
                   4054: 
                   4055: sub postannounce {
                   4056:     my ($server,$text)=@_;
1.844     albertel 4057:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4058:     unless ($text=~/\w/) { $text=''; }
                   4059:     return &reply('setannounce:'.&escape($text),$server);
                   4060: }
                   4061: 
                   4062: sub getannounce {
1.448     albertel 4063: 
                   4064:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4065: 	my $announcement='';
1.800     albertel 4066: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4067: 	close($fh);
1.399     www      4068: 	if ($announcement=~/\w/) { 
                   4069: 	    return 
                   4070:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4071:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4072: 	} else {
                   4073: 	    return '';
                   4074: 	}
                   4075:     } else {
                   4076: 	return '';
                   4077:     }
1.351     www      4078: }
1.353     www      4079: 
                   4080: # ---------------------------------------------------------- Course ID routines
                   4081: # Deal with domain's nohist_courseid.db files
                   4082: #
                   4083: 
                   4084: sub courseidput {
1.921     raeburn  4085:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4086:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4087:     my $outcome;
                   4088:     if ($caller eq 'timeonly') {
                   4089:         my $cids = '';
                   4090:         foreach my $item (keys(%$storehash)) {
                   4091:             $cids.=&escape($item).'&';
                   4092:         }
                   4093:         $cids=~s/\&$//;
                   4094:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4095:                           $coursehome);       
                   4096:     } else {
                   4097:         my $items = '';
                   4098:         foreach my $item (keys(%$storehash)) {
                   4099:             $items.= &escape($item).'='.
                   4100:                      &freeze_escape($$storehash{$item}).'&';
                   4101:         }
                   4102:         $items=~s/\&$//;
                   4103:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4104:                           $coursehome);
1.918     raeburn  4105:     }
                   4106:     if ($outcome eq 'unknown_cmd') {
                   4107:         my $what;
                   4108:         foreach my $cid (keys(%$storehash)) {
                   4109:             $what .= &escape($cid).'=';
1.921     raeburn  4110:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4111:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4112:             }
                   4113:             $what =~ s/\:$/&/;
                   4114:         }
                   4115:         $what =~ s/\&$//;  
                   4116:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4117:     } else {
                   4118:         return $outcome;
                   4119:     }
1.353     www      4120: }
                   4121: 
                   4122: sub courseiddump {
1.921     raeburn  4123:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4124:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4125:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4126:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4127:     my $as_hash = 1;
                   4128:     my %returnhash;
                   4129:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4130:     my %libserv = &all_library();
                   4131:     foreach my $tryserver (keys(%libserv)) {
                   4132:         if ( (  $hostidflag == 1 
                   4133: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4134: 	     || (!defined($hostidflag)) ) {
                   4135: 
1.918     raeburn  4136: 	    if (($domfilter eq '') ||
                   4137: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4138:                 my $rep;
                   4139:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4140:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4141:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4142:                                 &escape($descfilter), &escape($instcodefilter), 
                   4143:                                 &escape($ownerfilter), &escape($coursefilter),
                   4144:                                 &escape($typefilter), &escape($regexp_ok), 
                   4145:                                 $as_hash, &escape($selfenrollonly), 
                   4146:                                 &escape($catfilter), $showhidden, $caller, 
                   4147:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4148:                                 &escape($createdbefore), &escape($createdafter), 
                   4149:                                 &escape($creationcontext), $domcloner)));
                   4150:                 } else {
                   4151:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4152:                              $sincefilter.':'.&escape($descfilter).':'.
                   4153:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4154:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4155:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4156:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4157:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4158:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4159:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4160:                              &escape($creationcontext).':'.$domcloner,
                   4161:                              $tryserver);
                   4162:                 }
                   4163:                      
1.918     raeburn  4164:                 my @pairs=split(/\&/,$rep);
                   4165:                 foreach my $item (@pairs) {
                   4166:                     my ($key,$value)=split(/\=/,$item,2);
                   4167:                     $key = &unescape($key);
                   4168:                     next if ($key =~ /^error: 2 /);
                   4169:                     my $result = &thaw_unescape($value);
                   4170:                     if (ref($result) eq 'HASH') {
                   4171:                         $returnhash{$key}=$result;
                   4172:                     } else {
1.921     raeburn  4173:                         my @responses = split(/:/,$value);
                   4174:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4175:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4176:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4177:                         }
1.1008    raeburn  4178:                     }
1.353     www      4179:                 }
                   4180:             }
                   4181:         }
                   4182:     }
                   4183:     return %returnhash;
                   4184: }
                   4185: 
1.1055    raeburn  4186: sub courselastaccess {
                   4187:     my ($cdom,$cnum,$hostidref) = @_;
                   4188:     my %returnhash;
                   4189:     if ($cdom && $cnum) {
                   4190:         my $chome = &homeserver($cnum,$cdom);
                   4191:         if ($chome ne 'no_host') {
                   4192:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4193:             &extract_lastaccess(\%returnhash,$rep);
                   4194:         }
                   4195:     } else {
                   4196:         if (!$cdom) { $cdom=''; }
                   4197:         my %libserv = &all_library();
                   4198:         foreach my $tryserver (keys(%libserv)) {
                   4199:             if (ref($hostidref) eq 'ARRAY') {
                   4200:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4201:             } 
                   4202:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4203:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4204:                 &extract_lastaccess(\%returnhash,$rep);
                   4205:             }
                   4206:         }
                   4207:     }
                   4208:     return %returnhash;
                   4209: }
                   4210: 
                   4211: sub extract_lastaccess {
                   4212:     my ($returnhash,$rep) = @_;
                   4213:     if (ref($returnhash) eq 'HASH') {
                   4214:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4215:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4216:                  $rep eq '') {
                   4217:             my @pairs=split(/\&/,$rep);
                   4218:             foreach my $item (@pairs) {
                   4219:                 my ($key,$value)=split(/\=/,$item,2);
                   4220:                 $key = &unescape($key);
                   4221:                 next if ($key =~ /^error: 2 /);
                   4222:                 $returnhash->{$key} = &thaw_unescape($value);
                   4223:             }
                   4224:         }
                   4225:     }
                   4226:     return;
                   4227: }
                   4228: 
1.658     raeburn  4229: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4230: 
                   4231: sub dcmailput {
1.685     raeburn  4232:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4233:     my $status = &Apache::lonnet::critical(
1.740     www      4234:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4235:        &escape($message),$server);
1.662     raeburn  4236:     return $status;
                   4237: }
                   4238: 
1.658     raeburn  4239: sub dcmaildump {
                   4240:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4241:     my %returnhash=();
1.846     albertel 4242: 
                   4243:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4244:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4245:                                                          &escape($enddate).':';
                   4246: 	my @esc_senders=map { &escape($_)} @$senders;
                   4247: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4248: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4249:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4250:             if (($key) && ($value)) {
                   4251:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4252:             }
                   4253:         }
                   4254:     }
                   4255:     return %returnhash;
                   4256: }
1.662     raeburn  4257: # ---------------------------------------------------------- Domain roles
                   4258: 
                   4259: sub get_domain_roles {
                   4260:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4261:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4262:         $startdate = '.';
                   4263:     }
1.1018    raeburn  4264:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4265:         $enddate = '.';
                   4266:     }
1.922     raeburn  4267:     my $rolelist;
                   4268:     if (ref($roles) eq 'ARRAY') {
                   4269:         $rolelist = join(':',@{$roles});
                   4270:     }
1.662     raeburn  4271:     my %personnel = ();
1.841     albertel 4272: 
                   4273:     my %servers = &get_servers($dom,'library');
                   4274:     foreach my $tryserver (keys(%servers)) {
                   4275: 	%{$personnel{$tryserver}}=();
                   4276: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4277: 					    &escape($startdate).':'.
                   4278: 					    &escape($enddate).':'.
                   4279: 					    &escape($rolelist), $tryserver))) {
                   4280: 	    my ($key,$value) = split(/\=/,$line,2);
                   4281: 	    if (($key) && ($value)) {
                   4282: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4283: 	    }
                   4284: 	}
1.662     raeburn  4285:     }
                   4286:     return %personnel;
                   4287: }
1.658     raeburn  4288: 
1.1057    www      4289: # ----------------------------------------------------------- Interval timing 
1.149     www      4290: 
1.1153    www      4291: {
                   4292: # Caches needed for speedup of navmaps
                   4293: # We don't want to cache this for very long at all (5 seconds at most)
                   4294: # 
                   4295: # The user for whom we cache
                   4296: my $cachedkey='';
                   4297: # The cached times for this user
                   4298: my %cachedtimes=();
                   4299: # When this was last done
                   4300: my $cachedtime=();
                   4301: 
                   4302: sub load_all_first_access {
1.1154    raeburn  4303:     my ($uname,$udom)=@_;
1.1156    www      4304:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4305:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4306:         return;
                   4307:     }
                   4308:     $cachedtime=time;
                   4309:     $cachedkey=$uname.':'.$udom;
                   4310:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4311: }
                   4312: 
1.504     albertel 4313: sub get_first_access {
1.1162    raeburn  4314:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4315:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4316:     if ($argsymb) { $symb=$argsymb; }
                   4317:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4318:     if ($argmap) { $map = $argmap; }
1.926     albertel 4319:     if ($type eq 'course') {
                   4320: 	$res='course';
                   4321:     } elsif ($type eq 'map') {
1.588     albertel 4322: 	$res=&symbread($map);
                   4323:     } else {
                   4324: 	$res=$symb;
                   4325:     }
1.1153    www      4326:     &load_all_first_access($uname,$udom);
                   4327:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4328: }
                   4329: 
                   4330: sub set_first_access {
1.1162    raeburn  4331:     my ($type,$interval)=@_;
1.790     albertel 4332:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4333:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4334:     if ($type eq 'course') {
                   4335: 	$res='course';
                   4336:     } elsif ($type eq 'map') {
1.588     albertel 4337: 	$res=&symbread($map);
                   4338:     } else {
                   4339: 	$res=$symb;
                   4340:     }
1.1153    www      4341:     $cachedkey='';
1.1162    raeburn  4342:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4343:     if (!$firstaccess) {
1.1162    raeburn  4344:         my $start = time;
                   4345: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4346:                           $udom,$uname);
                   4347:         if ($putres eq 'ok') {
                   4348:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4349:                  $udom,$uname); 
                   4350:             &appenv(
                   4351:                      {
                   4352:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4353:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4354:                      }
                   4355:                   );
                   4356:         }
                   4357:         return $putres;
1.505     albertel 4358:     }
                   4359:     return 'already_set';
1.504     albertel 4360: }
1.1153    www      4361: }
1.110     www      4362: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4363: 
                   4364: sub expirespread {
                   4365:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4366:     my $cid=$env{'request.course.id'}; 
1.110     www      4367:     if ($cid) {
                   4368:        my $now=time;
                   4369:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4370:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4371:                             $env{'course.'.$cid.'.num'}.
1.110     www      4372: 	        	    ':nohist_expirationdates:'.
                   4373:                             &escape($key).'='.$now,
1.620     albertel 4374:                             $env{'course.'.$cid.'.home'})
1.110     www      4375:     }
                   4376:     return 'ok';
1.14      www      4377: }
                   4378: 
1.109     www      4379: # ----------------------------------------------------- Devalidate Spreadsheets
                   4380: 
                   4381: sub devalidate {
1.325     www      4382:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4383:     my $cid=$env{'request.course.id'}; 
1.109     www      4384:     if ($cid) {
1.391     matthew  4385:         # delete the stored spreadsheets for
                   4386:         # - the student level sheet of this user in course's homespace
                   4387:         # - the assessment level sheet for this resource 
                   4388:         #   for this user in user's homespace
1.553     albertel 4389: 	# - current conditional state info
1.325     www      4390: 	my $key=$uname.':'.$udom.':';
1.109     www      4391:         my $status=
1.299     matthew  4392: 	    &del('nohist_calculatedsheets',
1.391     matthew  4393: 		 [$key.'studentcalc:'],
1.620     albertel 4394: 		 $env{'course.'.$cid.'.domain'},
                   4395: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4396: 		.' '.
                   4397: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4398: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4399:         unless ($status eq 'ok ok') {
                   4400:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4401:                     $uname.' at '.$udom.' for '.
1.109     www      4402: 		    $symb.': '.$status);
1.133     albertel 4403:         }
1.553     albertel 4404: 	&delenv('user.state.'.$cid);
1.109     www      4405:     }
                   4406: }
                   4407: 
1.265     albertel 4408: sub get_scalar {
                   4409:     my ($string,$end) = @_;
                   4410:     my $value;
                   4411:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4412: 	$value = $1;
                   4413:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4414: 	$value = $1;
                   4415:     }
                   4416:     return &unescape($value);
                   4417: }
                   4418: 
                   4419: sub array2str {
                   4420:   my (@array) = @_;
                   4421:   my $result=&arrayref2str(\@array);
                   4422:   $result=~s/^__ARRAY_REF__//;
                   4423:   $result=~s/__END_ARRAY_REF__$//;
                   4424:   return $result;
                   4425: }
                   4426: 
1.204     albertel 4427: sub arrayref2str {
                   4428:   my ($arrayref) = @_;
1.265     albertel 4429:   my $result='__ARRAY_REF__';
1.204     albertel 4430:   foreach my $elem (@$arrayref) {
1.265     albertel 4431:     if(ref($elem) eq 'ARRAY') {
                   4432:       $result.=&arrayref2str($elem).'&';
                   4433:     } elsif(ref($elem) eq 'HASH') {
                   4434:       $result.=&hashref2str($elem).'&';
                   4435:     } elsif(ref($elem)) {
                   4436:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4437:     } else {
                   4438:       $result.=&escape($elem).'&';
                   4439:     }
                   4440:   }
                   4441:   $result=~s/\&$//;
1.265     albertel 4442:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4443:   return $result;
                   4444: }
                   4445: 
1.168     albertel 4446: sub hash2str {
1.204     albertel 4447:   my (%hash) = @_;
                   4448:   my $result=&hashref2str(\%hash);
1.265     albertel 4449:   $result=~s/^__HASH_REF__//;
                   4450:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4451:   return $result;
                   4452: }
                   4453: 
                   4454: sub hashref2str {
                   4455:   my ($hashref)=@_;
1.265     albertel 4456:   my $result='__HASH_REF__';
1.800     albertel 4457:   foreach my $key (sort(keys(%$hashref))) {
                   4458:     if (ref($key) eq 'ARRAY') {
                   4459:       $result.=&arrayref2str($key).'=';
                   4460:     } elsif (ref($key) eq 'HASH') {
                   4461:       $result.=&hashref2str($key).'=';
                   4462:     } elsif (ref($key)) {
1.265     albertel 4463:       $result.='=';
1.800     albertel 4464:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4465:     } else {
1.1132    raeburn  4466: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4467:     }
                   4468: 
1.800     albertel 4469:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4470:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4471:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4472:       $result.=&hashref2str($hashref->{$key}).'&';
                   4473:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4474:        $result.='&';
1.800     albertel 4475:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4476:     } else {
1.800     albertel 4477:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4478:     }
                   4479:   }
1.168     albertel 4480:   $result=~s/\&$//;
1.265     albertel 4481:   $result .= '__END_HASH_REF__';
1.168     albertel 4482:   return $result;
                   4483: }
                   4484: 
                   4485: sub str2hash {
1.265     albertel 4486:     my ($string)=@_;
                   4487:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4488:     return %$hash;
                   4489: }
                   4490: 
                   4491: sub str2hashref {
1.168     albertel 4492:   my ($string) = @_;
1.265     albertel 4493: 
                   4494:   my %hash;
                   4495: 
                   4496:   if($string !~ /^__HASH_REF__/) {
                   4497:       if (! ($string eq '' || !defined($string))) {
                   4498: 	  $hash{'error'}='Not hash reference';
                   4499:       }
                   4500:       return (\%hash, $string);
                   4501:   }
                   4502: 
                   4503:   $string =~ s/^__HASH_REF__//;
                   4504: 
                   4505:   while($string !~ /^__END_HASH_REF__/) {
                   4506:       #key
                   4507:       my $key='';
                   4508:       if($string =~ /^__HASH_REF__/) {
                   4509:           ($key, $string)=&str2hashref($string);
                   4510:           if(defined($key->{'error'})) {
                   4511:               $hash{'error'}='Bad data';
                   4512:               return (\%hash, $string);
                   4513:           }
                   4514:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4515:           ($key, $string)=&str2arrayref($string);
                   4516:           if($key->[0] eq 'Array reference error') {
                   4517:               $hash{'error'}='Bad data';
                   4518:               return (\%hash, $string);
                   4519:           }
                   4520:       } else {
                   4521:           $string =~ s/^(.*?)=//;
1.267     albertel 4522: 	  $key=&unescape($1);
1.265     albertel 4523:       }
                   4524:       $string =~ s/^=//;
                   4525: 
                   4526:       #value
                   4527:       my $value='';
                   4528:       if($string =~ /^__HASH_REF__/) {
                   4529:           ($value, $string)=&str2hashref($string);
                   4530:           if(defined($value->{'error'})) {
                   4531:               $hash{'error'}='Bad data';
                   4532:               return (\%hash, $string);
                   4533:           }
                   4534:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4535:           ($value, $string)=&str2arrayref($string);
                   4536:           if($value->[0] eq 'Array reference error') {
                   4537:               $hash{'error'}='Bad data';
                   4538:               return (\%hash, $string);
                   4539:           }
                   4540:       } else {
                   4541: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4542:       }
                   4543:       $string =~ s/^&//;
                   4544: 
                   4545:       $hash{$key}=$value;
1.204     albertel 4546:   }
1.265     albertel 4547: 
                   4548:   $string =~ s/^__END_HASH_REF__//;
                   4549: 
                   4550:   return (\%hash, $string);
1.204     albertel 4551: }
                   4552: 
                   4553: sub str2array {
1.265     albertel 4554:     my ($string)=@_;
                   4555:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4556:     return @$array;
                   4557: }
                   4558: 
                   4559: sub str2arrayref {
1.204     albertel 4560:   my ($string) = @_;
1.265     albertel 4561:   my @array;
                   4562: 
                   4563:   if($string !~ /^__ARRAY_REF__/) {
                   4564:       if (! ($string eq '' || !defined($string))) {
                   4565: 	  $array[0]='Array reference error';
                   4566:       }
                   4567:       return (\@array, $string);
                   4568:   }
                   4569: 
                   4570:   $string =~ s/^__ARRAY_REF__//;
                   4571: 
                   4572:   while($string !~ /^__END_ARRAY_REF__/) {
                   4573:       my $value='';
                   4574:       if($string =~ /^__HASH_REF__/) {
                   4575:           ($value, $string)=&str2hashref($string);
                   4576:           if(defined($value->{'error'})) {
                   4577:               $array[0] ='Array reference error';
                   4578:               return (\@array, $string);
                   4579:           }
                   4580:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4581:           ($value, $string)=&str2arrayref($string);
                   4582:           if($value->[0] eq 'Array reference error') {
                   4583:               $array[0] ='Array reference error';
                   4584:               return (\@array, $string);
                   4585:           }
                   4586:       } else {
                   4587: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4588:       }
                   4589:       $string =~ s/^&//;
                   4590: 
                   4591:       push(@array, $value);
1.191     harris41 4592:   }
1.265     albertel 4593: 
                   4594:   $string =~ s/^__END_ARRAY_REF__//;
                   4595: 
                   4596:   return (\@array, $string);
1.168     albertel 4597: }
                   4598: 
1.167     albertel 4599: # -------------------------------------------------------------------Temp Store
                   4600: 
1.168     albertel 4601: sub tmpreset {
                   4602:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4603:   if (!$symb) {
                   4604:     $symb=&symbread();
1.620     albertel 4605:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4606:   }
                   4607:   $symb=escape($symb);
                   4608: 
1.620     albertel 4609:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4610:   $namespace=~s/\//\_/g;
                   4611:   $namespace=~s/\W//g;
                   4612: 
1.620     albertel 4613:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4614:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4615:   if ($domain eq 'public' && $stuname eq 'public') {
                   4616:       $stuname=$ENV{'REMOTE_ADDR'};
                   4617:   }
1.1117    foxr     4618:   my $path=LONCAPA::tempdir();
1.168     albertel 4619:   my %hash;
                   4620:   if (tie(%hash,'GDBM_File',
                   4621: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4622: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4623:     foreach my $key (keys(%hash)) {
1.180     albertel 4624:       if ($key=~ /:$symb/) {
1.168     albertel 4625: 	delete($hash{$key});
                   4626:       }
                   4627:     }
                   4628:   }
                   4629: }
                   4630: 
1.167     albertel 4631: sub tmpstore {
1.168     albertel 4632:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4633: 
                   4634:   if (!$symb) {
                   4635:     $symb=&symbread();
1.620     albertel 4636:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4637:   }
                   4638:   $symb=escape($symb);
                   4639: 
                   4640:   if (!$namespace) {
                   4641:     # I don't think we would ever want to store this for a course.
                   4642:     # it seems this will only be used if we don't have a course.
1.620     albertel 4643:     #$namespace=$env{'request.course.id'};
1.168     albertel 4644:     #if (!$namespace) {
1.620     albertel 4645:       $namespace=$env{'request.state'};
1.168     albertel 4646:     #}
                   4647:   }
                   4648:   $namespace=~s/\//\_/g;
                   4649:   $namespace=~s/\W//g;
1.620     albertel 4650:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4651:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4652:   if ($domain eq 'public' && $stuname eq 'public') {
                   4653:       $stuname=$ENV{'REMOTE_ADDR'};
                   4654:   }
1.168     albertel 4655:   my $now=time;
                   4656:   my %hash;
1.1117    foxr     4657:   my $path=LONCAPA::tempdir();
1.168     albertel 4658:   if (tie(%hash,'GDBM_File',
                   4659: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4660: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4661:     $hash{"version:$symb"}++;
                   4662:     my $version=$hash{"version:$symb"};
                   4663:     my $allkeys=''; 
                   4664:     foreach my $key (keys(%$storehash)) {
                   4665:       $allkeys.=$key.':';
1.591     albertel 4666:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4667:     }
                   4668:     $hash{"$version:$symb:timestamp"}=$now;
                   4669:     $allkeys.='timestamp';
                   4670:     $hash{"$version:keys:$symb"}=$allkeys;
                   4671:     if (untie(%hash)) {
                   4672:       return 'ok';
                   4673:     } else {
                   4674:       return "error:$!";
                   4675:     }
                   4676:   } else {
                   4677:     return "error:$!";
                   4678:   }
                   4679: }
1.167     albertel 4680: 
1.168     albertel 4681: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4682: 
1.168     albertel 4683: sub tmprestore {
                   4684:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4685: 
1.168     albertel 4686:   if (!$symb) {
                   4687:     $symb=&symbread();
1.620     albertel 4688:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4689:   }
                   4690:   $symb=escape($symb);
                   4691: 
1.620     albertel 4692:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4693: 
1.620     albertel 4694:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4695:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4696:   if ($domain eq 'public' && $stuname eq 'public') {
                   4697:       $stuname=$ENV{'REMOTE_ADDR'};
                   4698:   }
1.168     albertel 4699:   my %returnhash;
                   4700:   $namespace=~s/\//\_/g;
                   4701:   $namespace=~s/\W//g;
                   4702:   my %hash;
1.1117    foxr     4703:   my $path=LONCAPA::tempdir();
1.168     albertel 4704:   if (tie(%hash,'GDBM_File',
                   4705: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4706: 	  &GDBM_READER(),0640)) {
1.168     albertel 4707:     my $version=$hash{"version:$symb"};
                   4708:     $returnhash{'version'}=$version;
                   4709:     my $scope;
                   4710:     for ($scope=1;$scope<=$version;$scope++) {
                   4711:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4712:       my @keys=split(/:/,$vkeys);
                   4713:       my $key;
                   4714:       $returnhash{"$scope:keys"}=$vkeys;
                   4715:       foreach $key (@keys) {
1.591     albertel 4716: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4717: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4718:       }
                   4719:     }
1.168     albertel 4720:     if (!(untie(%hash))) {
                   4721:       return "error:$!";
                   4722:     }
                   4723:   } else {
                   4724:     return "error:$!";
                   4725:   }
                   4726:   return %returnhash;
1.167     albertel 4727: }
                   4728: 
1.9       www      4729: # ----------------------------------------------------------------------- Store
                   4730: 
                   4731: sub store {
1.124     www      4732:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4733:     my $home='';
                   4734: 
1.168     albertel 4735:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4736: 
1.213     www      4737:     $symb=&symbclean($symb);
1.122     albertel 4738:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4739: 
1.620     albertel 4740:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4741:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4742: 
                   4743:     &devalidate($symb,$stuname,$domain);
1.109     www      4744: 
                   4745:     $symb=escape($symb);
1.187     www      4746:     if (!$namespace) { 
1.620     albertel 4747:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4748:           return ''; 
                   4749:        } 
                   4750:     }
1.620     albertel 4751:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4752: 
                   4753:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4754:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4755: 
1.12      www      4756:     my $namevalue='';
1.800     albertel 4757:     foreach my $key (keys(%$storehash)) {
                   4758:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4759:     }
1.12      www      4760:     $namevalue=~s/\&$//;
1.187     www      4761:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4762:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4763: }
                   4764: 
1.47      www      4765: # -------------------------------------------------------------- Critical Store
                   4766: 
                   4767: sub cstore {
1.124     www      4768:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4769:     my $home='';
                   4770: 
1.168     albertel 4771:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4772: 
1.213     www      4773:     $symb=&symbclean($symb);
1.122     albertel 4774:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4775: 
1.620     albertel 4776:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4777:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4778: 
                   4779:     &devalidate($symb,$stuname,$domain);
1.109     www      4780: 
                   4781:     $symb=escape($symb);
1.187     www      4782:     if (!$namespace) { 
1.620     albertel 4783:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4784:           return ''; 
                   4785:        } 
                   4786:     }
1.620     albertel 4787:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4788: 
                   4789:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4790:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4791: 
1.47      www      4792:     my $namevalue='';
1.800     albertel 4793:     foreach my $key (keys(%$storehash)) {
                   4794:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4795:     }
1.47      www      4796:     $namevalue=~s/\&$//;
1.187     www      4797:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4798:     return critical
                   4799:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4800: }
                   4801: 
1.9       www      4802: # --------------------------------------------------------------------- Restore
                   4803: 
                   4804: sub restore {
1.124     www      4805:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4806:     my $home='';
                   4807: 
1.168     albertel 4808:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4809: 
1.122     albertel 4810:     if (!$symb) {
                   4811:       unless ($symb=escape(&symbread())) { return ''; }
                   4812:     } else {
1.213     www      4813:       $symb=&escape(&symbclean($symb));
1.122     albertel 4814:     }
1.188     www      4815:     if (!$namespace) { 
1.620     albertel 4816:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4817:           return ''; 
                   4818:        } 
                   4819:     }
1.620     albertel 4820:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4821:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4822:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4823:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4824: 
1.12      www      4825:     my %returnhash=();
1.800     albertel 4826:     foreach my $line (split(/\&/,$answer)) {
                   4827: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4828:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4829:     }
1.75      www      4830:     my $version;
                   4831:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4832:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4833:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4834:        }
1.75      www      4835:     }
1.13      www      4836:     return %returnhash;
1.34      www      4837: }
                   4838: 
                   4839: # ---------------------------------------------------------- Course Description
1.1118    foxr     4840: #
                   4841: #  
1.34      www      4842: 
                   4843: sub coursedescription {
1.731     albertel 4844:     my ($courseid,$args)=@_;
1.34      www      4845:     $courseid=~s/^\///;
1.49      www      4846:     $courseid=~s/\_/\//g;
1.34      www      4847:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4848:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4849:     my $normalid=$cdomain.'_'.$cnum;
                   4850:     # need to always cache even if we get errors otherwise we keep 
                   4851:     # trying and trying and trying to get the course description.
                   4852:     my %envhash=();
                   4853:     my %returnhash=();
1.731     albertel 4854:     
                   4855:     my $expiretime=600;
                   4856:     if ($env{'request.course.id'} eq $normalid) {
                   4857: 	$expiretime=120;
                   4858:     }
                   4859: 
                   4860:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4861:     if (!$args->{'freshen_cache'}
                   4862: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4863: 	foreach my $key (keys(%env)) {
                   4864: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4865: 	    my ($setting) = $1;
                   4866: 	    $returnhash{$setting} = $env{$key};
                   4867: 	}
                   4868: 	return %returnhash;
                   4869:     }
                   4870: 
1.1118    foxr     4871:     # get the data again
                   4872: 
1.731     albertel 4873:     if (!$args->{'one_time'}) {
                   4874: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4875:     }
1.811     albertel 4876: 
1.34      www      4877:     if ($chome ne 'no_host') {
1.302     albertel 4878:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4879:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4880: 	   my $username = $env{'user.name'}; # Defult username
                   4881: 	   if(defined $args->{'user'}) {
                   4882: 	       $username = $args->{'user'};
                   4883: 	   }
1.129     albertel 4884:            $returnhash{'home'}= $chome;
                   4885: 	   $returnhash{'domain'} = $cdomain;
                   4886: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4887:            if (!defined($returnhash{'type'})) {
                   4888:                $returnhash{'type'} = 'Course';
                   4889:            }
1.130     albertel 4890:            while (my ($name,$value) = each %returnhash) {
1.53      www      4891:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4892:            }
1.270     www      4893:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4894:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4895: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4896:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4897:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4898:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4899:        }
                   4900:     }
1.731     albertel 4901:     if (!$args->{'one_time'}) {
1.949     raeburn  4902: 	&appenv(\%envhash);
1.731     albertel 4903:     }
1.302     albertel 4904:     return %returnhash;
1.461     www      4905: }
                   4906: 
1.1080    raeburn  4907: sub update_released_required {
                   4908:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4909:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4910:         $cid = $env{'request.course.id'};
                   4911:         $cdom = $env{'course.'.$cid.'.domain'};
                   4912:         $cnum = $env{'course.'.$cid.'.num'};
                   4913:         $chome = $env{'course.'.$cid.'.home'};
                   4914:     }
                   4915:     if ($needsrelease) {
                   4916:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4917:         my $needsupdate;
                   4918:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4919:             $needsupdate = 1;
                   4920:         } else {
                   4921:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4922:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4923:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4924:                 $needsupdate = 1;
                   4925:             }
                   4926:         }
                   4927:         if ($needsupdate) {
                   4928:             my %needshash = (
                   4929:                              'internal.releaserequired' => $needsrelease,
                   4930:                             );
                   4931:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4932:             if ($putresult eq 'ok') {
                   4933:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4934:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4935:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4936:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4937:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4938:                 }
                   4939:             }
                   4940:         }
                   4941:     }
                   4942:     return;
                   4943: }
                   4944: 
1.461     www      4945: # -------------------------------------------------See if a user is privileged
                   4946: 
                   4947: sub privileged {
                   4948:     my ($username,$domain)=@_;
1.1170    droeschl 4949: 
                   4950:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4951:     my $now = time;
                   4952: 
                   4953:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4954:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4955:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4956:                 return 1 unless ($tend && $tend < $now) 
                   4957:                     or ($tstart && $tstart > $now);
                   4958:             }
1.461     www      4959: 	}
1.1170    droeschl 4960: 
1.461     www      4961:     return 0;
1.9       www      4962: }
1.1       albertel 4963: 
1.103     harris41 4964: # -------------------------------------------------------- Get user privileges
1.11      www      4965: 
                   4966: sub rolesinit {
1.1169    droeschl 4967:     my ($domain, $username) = @_;
                   4968:     my %userroles = ('user.login.time' => time);
                   4969:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4970: 
                   4971:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4972:     # also, blocking can be triggered by an activating timer
                   4973:     # it's saved in the user's %env.
                   4974:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4975:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4976:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4977:         %timerintchk, %timerintenv);
                   4978: 
1.1162    raeburn  4979:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4980:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4981:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4982:     }
1.1169    droeschl 4983: 
1.1162    raeburn  4984:     foreach my $key (keys(%timerinterval)) {
                   4985:         my ($cid,$rest) = split(/\0/,$key);
                   4986:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4987:     }
1.1169    droeschl 4988: 
1.11      www      4989:     my %allroles=();
1.1162    raeburn  4990:     my %allgroups=();
1.11      www      4991: 
1.1169    droeschl 4992:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4993:         my $role = $rolesdump{$area};
                   4994:         $area =~ s/\_\w\w$//;
                   4995: 
                   4996:         my ($trole, $tend, $tstart, $group_privs);
                   4997: 
                   4998:         if ($role =~ /^cr/) {
                   4999:         # Custom role, defined by a user 
                   5000:         # e.g., user.role.cr/msu/smith/mynewrole
                   5001:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5002:                 $trole = $1;
                   5003:                 ($tend, $tstart) = split('_', $2);
                   5004:             } else {
                   5005:                 $trole = $role;
                   5006:             }
                   5007:         } elsif ($role =~ m|^gr/|) {
                   5008:         # Role of member in a group, defined within a course/community
                   5009:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5010:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5011:             next if $tstart eq '-1';
                   5012:             ($trole, $group_privs) = split(/\//, $trole);
                   5013:             $group_privs = &unescape($group_privs);
                   5014:         } else {
                   5015:         # Just a normal role, defined in roles.tab
                   5016:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5017:         }
                   5018: 
                   5019:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5020:                  $username);
                   5021:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5022: 
                   5023:         # role expired or not available yet?
                   5024:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5025:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5026: 
                   5027:         next if $area eq '' or $trole eq '';
                   5028: 
                   5029:         my $spec = "$trole.$area";
                   5030:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5031: 
                   5032:         if ($trole =~ /^cr\//) {
                   5033:         # Custom role, defined by a user
                   5034:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5035:         } elsif ($trole eq 'gr') {
                   5036:         # Role of a member in a group, defined within a course/community
                   5037:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5038:             next;
                   5039:         } else {
                   5040:         # Normal role, defined in roles.tab
                   5041:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5042:         }
                   5043: 
                   5044:         my $cid = $tdomain.'_'.$trest;
                   5045:         unless ($firstaccchk{$cid}) {
                   5046:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5047:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5048:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5049:                         $coursetimerstarts{$cid}{$item}; 
                   5050:                 }
                   5051:             }
                   5052:             $firstaccchk{$cid} = 1;
                   5053:         }
                   5054:         unless ($timerintchk{$cid}) {
                   5055:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5056:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5057:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5058:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5059:                 }
1.12      www      5060:             }
1.1169    droeschl 5061:             $timerintchk{$cid} = 1;
1.191     harris41 5062:         }
1.11      www      5063:     }
1.1169    droeschl 5064: 
                   5065:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5066:         \%allroles, \%allgroups);
                   5067:     $env{'user.adv'} = $userroles{'user.adv'};
                   5068: 
1.1162    raeburn  5069:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5070: }
                   5071: 
1.567     raeburn  5072: sub set_arearole {
                   5073:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   5074: # log the associated role with the area
                   5075:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 5076:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5077: }
                   5078: 
                   5079: sub custom_roleprivs {
                   5080:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5081:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5082:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5083:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5084:         my ($rdummy,$roledef)=
                   5085:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5086:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5087:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5088:             if (defined($syspriv)) {
1.1043    raeburn  5089:                 if ($trest =~ /^$match_community$/) {
                   5090:                     $syspriv =~ s/bre\&S//; 
                   5091:                 }
1.567     raeburn  5092:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5093:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5094:             }
                   5095:             if ($tdomain ne '') {
                   5096:                 if (defined($dompriv)) {
                   5097:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5098:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5099:                 }
                   5100:                 if (($trest ne '') && (defined($coursepriv))) {
                   5101:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5102:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5103:                 }
                   5104:             }
                   5105:         }
                   5106:     }
                   5107: }
                   5108: 
1.678     raeburn  5109: sub group_roleprivs {
                   5110:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5111:     my $access = 1;
                   5112:     my $now = time;
                   5113:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5114:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5115:     if ($access) {
1.811     albertel 5116:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5117:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5118:     }
                   5119: }
1.567     raeburn  5120: 
                   5121: sub standard_roleprivs {
                   5122:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5123:     if (defined($pr{$trole.':s'})) {
                   5124:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5125:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5126:     }
                   5127:     if ($tdomain ne '') {
                   5128:         if (defined($pr{$trole.':d'})) {
                   5129:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5130:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5131:         }
                   5132:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5133:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5134:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5135:         }
                   5136:     }
                   5137: }
                   5138: 
                   5139: sub set_userprivs {
1.1064    raeburn  5140:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5141:     my $author=0;
                   5142:     my $adv=0;
1.678     raeburn  5143:     my %grouproles = ();
                   5144:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5145:         my @groupkeys; 
1.1000    raeburn  5146:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5147:             push(@groupkeys,$role);
                   5148:         }
                   5149:         if (ref($groups_roles) eq 'HASH') {
                   5150:             foreach my $key (keys(%{$groups_roles})) {
                   5151:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5152:                     push(@groupkeys,$key);
                   5153:                 }
                   5154:             }
                   5155:         }
                   5156:         if (@groupkeys > 0) {
                   5157:             foreach my $role (@groupkeys) {
                   5158:                 my ($trole,$area,$sec,$extendedarea);
                   5159:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5160:                     $trole = $1;
                   5161:                     $area = $2;
                   5162:                     $sec = $3;
                   5163:                     $extendedarea = $area.$sec;
                   5164:                     if (exists($$allgroups{$area})) {
                   5165:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5166:                             my $spec = $trole.'.'.$extendedarea;
                   5167:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5168:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5169:                         }
1.678     raeburn  5170:                     }
                   5171:                 }
                   5172:             }
                   5173:         }
                   5174:     }
1.800     albertel 5175:     foreach my $group (keys(%grouproles)) {
                   5176:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5177:     }
1.800     albertel 5178:     foreach my $role (keys(%{$allroles})) {
                   5179:         my %thesepriv;
1.941     raeburn  5180:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5181:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5182:             if ($item ne '') {
                   5183:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5184:                 if ($restrictions eq '') {
                   5185:                     $thesepriv{$privilege}='F';
                   5186:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5187:                     $thesepriv{$privilege}.=$restrictions;
                   5188:                 }
                   5189:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5190:             }
                   5191:         }
                   5192:         my $thesestr='';
1.1104    raeburn  5193:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5194: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5195: 	}
                   5196:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5197:     }
                   5198:     return ($author,$adv);
                   5199: }
                   5200: 
1.994     raeburn  5201: sub role_status {
1.1104    raeburn  5202:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5203:     my @pwhere = ();
                   5204:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5205:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5206:         unless (!defined($$role) || $$role eq '') {
                   5207:             $$where=join('.',@pwhere);
                   5208:             $$trolecode=$$role.'.'.$$where;
                   5209:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5210:             $$tstatus='is';
1.1104    raeburn  5211:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5212:                 $$tstatus='future';
1.1034    raeburn  5213:                 if ($$tstart<$now) {
                   5214:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5215:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5216:                             my (%allroles,%allgroups,$group_privs,
                   5217:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5218:                             my %userroles = (
                   5219:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5220:                             );
1.1064    raeburn  5221:                             @rolecodes = ('cm'); 
1.1002    raeburn  5222:                             my $spec=$$role.'.'.$$where;
                   5223:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5224:                             if ($$role =~ /^cr\//) {
                   5225:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5226:                                 push(@rolecodes,'cr');
1.1002    raeburn  5227:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5228:                                 push(@rolecodes,$$role);
1.1002    raeburn  5229:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5230:                                                     $env{'user.name'});
1.1064    raeburn  5231:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5232:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5233:                                 $group_privs = &unescape($group_privs);
                   5234:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5235:                                 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  5236:                                 &get_groups_roles($tdomain,$trest,
                   5237:                                                   \%course_roles,\@rolecodes,
                   5238:                                                   \%groups_roles);
1.1002    raeburn  5239:                             } else {
1.1064    raeburn  5240:                                 push(@rolecodes,$$role);
1.1002    raeburn  5241:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5242:                             }
1.1064    raeburn  5243:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5244:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5245:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5246:                         }
                   5247:                     }
1.1034    raeburn  5248:                     $$tstatus = 'is';
1.1002    raeburn  5249:                 }
1.994     raeburn  5250:             }
                   5251:             if ($$tend) {
1.1104    raeburn  5252:                 if ($$tend<$update) {
1.994     raeburn  5253:                     $$tstatus='expired';
                   5254:                 } elsif ($$tend<$now) {
                   5255:                     $$tstatus='will_not';
                   5256:                 }
                   5257:             }
                   5258:         }
                   5259:     }
                   5260: }
                   5261: 
1.1104    raeburn  5262: sub get_groups_roles {
                   5263:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5264:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5265:                   (ref($rolecodes) eq 'ARRAY') && 
                   5266:                   (ref($groups_roles) eq 'HASH')); 
                   5267:     if (keys(%{$cdom_courseroles}) > 0) {
                   5268:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5269:         if ($cdom ne '' && $cnum ne '') {
                   5270:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5271:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5272:                     my $crsrole = $1;
                   5273:                     my $crssec = $2;
                   5274:                     if ($crsrole =~ /^cr/) {
                   5275:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5276:                             push(@{$rolecodes},'cr');
                   5277:                         }
                   5278:                     } else {
                   5279:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5280:                             push(@{$rolecodes},$crsrole);
                   5281:                         }
                   5282:                     }
                   5283:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5284:                     if ($crssec ne '') {
                   5285:                         $rolekey .= "/$crssec";
                   5286:                     }
                   5287:                     $rolekey .= './';
                   5288:                     $groups_roles->{$rolekey} = $rolecodes;
                   5289:                 }
                   5290:             }
                   5291:         }
                   5292:     }
                   5293:     return;
                   5294: }
                   5295: 
                   5296: sub delete_env_groupprivs {
                   5297:     my ($where,$courseroles,$possroles) = @_;
                   5298:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5299:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5300:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5301:         %{$courseroles->{$udom}} =
                   5302:             &get_my_roles('','','userroles',['active'],
                   5303:                           $possroles,[$udom],1);
                   5304:     }
                   5305:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5306:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5307:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5308:             my $area = '/'.$cdom.'/'.$cnum;
                   5309:             my $privkey = "user.priv.$crsrole.$area";
                   5310:             if ($crssec ne '') {
                   5311:                 $privkey .= '/'.$crssec;
                   5312:             }
                   5313:             $privkey .= ".$area/$group";
                   5314:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5315:         }
                   5316:     }
                   5317:     return;
                   5318: }
                   5319: 
1.994     raeburn  5320: sub check_adhoc_privs {
1.1104    raeburn  5321:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5322:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5323:     my $setprivs;
1.994     raeburn  5324:     if ($env{$cckey}) {
                   5325:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5326:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5327:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5328:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5329:             $setprivs = 1;
1.994     raeburn  5330:         }
                   5331:     } else {
1.1088    raeburn  5332:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5333:         $setprivs = 1;
1.994     raeburn  5334:     }
1.1185    raeburn  5335:     return $setprivs;
1.994     raeburn  5336: }
                   5337: 
                   5338: sub set_adhoc_privileges {
                   5339: # role can be cc or ca
1.1088    raeburn  5340:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5341:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5342:     my $spec = $role.'.'.$area;
                   5343:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5344:                                   $env{'user.name'});
                   5345:     my %ccrole = ();
                   5346:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5347:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5348:     &appenv(\%userroles,[$role,'cm']);
                   5349:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5350:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5351:         &appenv( {'request.role'        => $spec,
                   5352:                   'request.role.domain' => $dcdom,
                   5353:                   'request.course.sec'  => ''
                   5354:                  }
                   5355:                );
                   5356:         my $tadv=0;
                   5357:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5358:         &appenv({'request.role.adv'    => $tadv});
                   5359:     }
1.994     raeburn  5360: }
                   5361: 
1.12      www      5362: # --------------------------------------------------------------- get interface
                   5363: 
                   5364: sub get {
1.131     albertel 5365:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5366:    my $items='';
1.800     albertel 5367:    foreach my $item (@$storearr) {
                   5368:        $items.=&escape($item).'&';
1.191     harris41 5369:    }
1.12      www      5370:    $items=~s/\&$//;
1.620     albertel 5371:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5372:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5373:    my $uhome=&homeserver($uname,$udomain);
                   5374: 
1.133     albertel 5375:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5376:    my @pairs=split(/\&/,$rep);
1.273     albertel 5377:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5378:      return @pairs;
                   5379:    }
1.15      www      5380:    my %returnhash=();
1.42      www      5381:    my $i=0;
1.800     albertel 5382:    foreach my $item (@$storearr) {
                   5383:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5384:       $i++;
1.191     harris41 5385:    }
1.15      www      5386:    return %returnhash;
1.27      www      5387: }
                   5388: 
                   5389: # --------------------------------------------------------------- del interface
                   5390: 
                   5391: sub del {
1.133     albertel 5392:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5393:    my $items='';
1.800     albertel 5394:    foreach my $item (@$storearr) {
                   5395:        $items.=&escape($item).'&';
1.191     harris41 5396:    }
1.984     neumanie 5397: 
1.27      www      5398:    $items=~s/\&$//;
1.620     albertel 5399:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5400:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5401:    my $uhome=&homeserver($uname,$udomain);
                   5402:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5403: }
                   5404: 
                   5405: # -------------------------------------------------------------- dump interface
                   5406: 
1.1180    droeschl 5407: sub unserialize {
                   5408:     my ($rep, $escapedkeys) = @_;
                   5409: 
                   5410:     return {} if $rep =~ /^error/;
                   5411: 
                   5412:     my %returnhash=();
                   5413: 	foreach my $item (split /\&/, $rep) {
                   5414: 	    my ($key, $value) = split(/=/, $item, 2);
                   5415: 	    $key = unescape($key) unless $escapedkeys;
                   5416: 	    next if $key =~ /^error: 2 /;
                   5417: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5418: 	}
                   5419:     #return %returnhash;
                   5420:     return \%returnhash;
                   5421: }        
                   5422: 
                   5423: # see Lond::dump_with_regexp
                   5424: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5425: sub dump {
1.1180    droeschl 5426:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5427:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5428:     if (!$uname) { $uname=$env{'user.name'}; }
                   5429:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5430: 
1.1180    droeschl 5431:     my $reply;
                   5432:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5433:         # user is hosted on this machine
                   5434:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
                   5435:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5436:         return %{unserialize($reply, $escapedkeys)};
                   5437:     }
1.755     albertel 5438:     if ($regexp) {
                   5439: 	$regexp=&escape($regexp);
                   5440:     } else {
                   5441: 	$regexp='.';
                   5442:     }
1.1166    raeburn  5443:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5444:     my @pairs=split(/\&/,$rep);
                   5445:     my %returnhash=();
1.1098    foxr     5446:     if (!($rep =~ /^error/ )) {
                   5447: 	foreach my $item (@pairs) {
                   5448: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5449:         $key = unescape($key) unless $escapedkeys;
                   5450:         #$key = &unescape($key);
1.1098    foxr     5451: 	    next if ($key =~ /^error: 2 /);
                   5452: 	    $returnhash{$key}=&thaw_unescape($value);
                   5453: 	}
1.755     albertel 5454:     }
                   5455:     return %returnhash;
1.407     www      5456: }
                   5457: 
1.1098    foxr     5458: 
1.717     albertel 5459: # --------------------------------------------------------- dumpstore interface
                   5460: 
                   5461: sub dumpstore {
                   5462:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5463:    # same as dump but keys must be escaped. They may contain colon separated
                   5464:    # lists of values that may themself contain colons (e.g. symbs).
                   5465:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5466: }
                   5467: 
1.407     www      5468: # -------------------------------------------------------------- keys interface
                   5469: 
                   5470: sub getkeys {
                   5471:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5472:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5473:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5474:    my $uhome=&homeserver($uname,$udomain);
                   5475:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5476:    my @keyarray=();
1.800     albertel 5477:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5478:       next if ($key =~ /^error: 2 /);
1.800     albertel 5479:       push(@keyarray,&unescape($key));
1.407     www      5480:    }
                   5481:    return @keyarray;
1.318     matthew  5482: }
                   5483: 
1.319     matthew  5484: # --------------------------------------------------------------- currentdump
                   5485: sub currentdump {
1.328     matthew  5486:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5487:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5488:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5489:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5490:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5491:    my $rep;
                   5492: 
                   5493:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5494:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5495:                    $courseid)));
                   5496:    } else {
                   5497:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5498:    }
                   5499: 
1.318     matthew  5500:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5501:    #
1.318     matthew  5502:    my %returnhash=();
1.319     matthew  5503:    #
                   5504:    if ($rep eq "unknown_cmd") { 
                   5505:        # an old lond will not know currentdump
                   5506:        # Do a dump and make it look like a currentdump
1.822     albertel 5507:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5508:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5509:        my %hash = @tmp;
                   5510:        @tmp=();
1.424     matthew  5511:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5512:    } else {
                   5513:        my @pairs=split(/\&/,$rep);
1.800     albertel 5514:        foreach my $pair (@pairs) {
                   5515:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5516:            my ($symb,$param) = split(/:/,$key);
                   5517:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5518:                                                         &thaw_unescape($value);
1.319     matthew  5519:        }
1.191     harris41 5520:    }
1.12      www      5521:    return %returnhash;
1.424     matthew  5522: }
                   5523: 
                   5524: sub convert_dump_to_currentdump{
                   5525:     my %hash = %{shift()};
                   5526:     my %returnhash;
                   5527:     # Code ripped from lond, essentially.  The only difference
                   5528:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5529:     # we might run in to problems with parameter names =~ /^v\./
                   5530:     while (my ($key,$value) = each(%hash)) {
                   5531:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5532: 	$symb  = &unescape($symb);
                   5533: 	$param = &unescape($param);
1.424     matthew  5534:         next if ($v eq 'version' || $symb eq 'keys');
                   5535:         next if (exists($returnhash{$symb}) &&
                   5536:                  exists($returnhash{$symb}->{$param}) &&
                   5537:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5538:         $returnhash{$symb}->{$param}=$value;
                   5539:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5540:     }
                   5541:     #
                   5542:     # Remove all of the keys in the hashes which keep track of
                   5543:     # the version of the parameter.
                   5544:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5545:         # use a foreach because we are going to delete from the hash.
                   5546:         foreach my $key (keys(%$param_hash)) {
                   5547:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5548:         }
                   5549:     }
                   5550:     return \%returnhash;
1.12      www      5551: }
                   5552: 
1.627     albertel 5553: # ------------------------------------------------------ critical inc interface
                   5554: 
                   5555: sub cinc {
                   5556:     return &inc(@_,'critical');
                   5557: }
                   5558: 
1.449     matthew  5559: # --------------------------------------------------------------- inc interface
                   5560: 
                   5561: sub inc {
1.627     albertel 5562:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5563:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5564:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5565:     my $uhome=&homeserver($uname,$udomain);
                   5566:     my $items='';
                   5567:     if (! ref($store)) {
                   5568:         # got a single value, so use that instead
                   5569:         $items = &escape($store).'=&';
                   5570:     } elsif (ref($store) eq 'SCALAR') {
                   5571:         $items = &escape($$store).'=&';        
                   5572:     } elsif (ref($store) eq 'ARRAY') {
                   5573:         $items = join('=&',map {&escape($_);} @{$store});
                   5574:     } elsif (ref($store) eq 'HASH') {
                   5575:         while (my($key,$value) = each(%{$store})) {
                   5576:             $items.= &escape($key).'='.&escape($value).'&';
                   5577:         }
                   5578:     }
                   5579:     $items=~s/\&$//;
1.627     albertel 5580:     if ($critical) {
                   5581: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5582:     } else {
                   5583: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5584:     }
1.449     matthew  5585: }
                   5586: 
1.12      www      5587: # --------------------------------------------------------------- put interface
                   5588: 
                   5589: sub put {
1.134     albertel 5590:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5591:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5592:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5593:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5594:    my $items='';
1.800     albertel 5595:    foreach my $item (keys(%$storehash)) {
                   5596:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5597:    }
1.12      www      5598:    $items=~s/\&$//;
1.134     albertel 5599:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5600: }
                   5601: 
1.631     albertel 5602: # ------------------------------------------------------------ newput interface
                   5603: 
                   5604: sub newput {
                   5605:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5606:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5607:    if (!$uname) { $uname=$env{'user.name'}; }
                   5608:    my $uhome=&homeserver($uname,$udomain);
                   5609:    my $items='';
                   5610:    foreach my $key (keys(%$storehash)) {
                   5611:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5612:    }
                   5613:    $items=~s/\&$//;
                   5614:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5615: }
                   5616: 
                   5617: # ---------------------------------------------------------  putstore interface
                   5618: 
1.524     raeburn  5619: sub putstore {
1.715     albertel 5620:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5621:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5622:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5623:    my $uhome=&homeserver($uname,$udomain);
                   5624:    my $items='';
1.715     albertel 5625:    foreach my $key (keys(%$storehash)) {
                   5626:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5627:    }
1.715     albertel 5628:    $items=~s/\&$//;
1.716     albertel 5629:    my $esc_symb=&escape($symb);
                   5630:    my $esc_v=&escape($version);
1.715     albertel 5631:    my $reply =
1.716     albertel 5632:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5633: 	      $uhome);
                   5634:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5635:        # gfall back to way things use to be done
1.715     albertel 5636:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5637: 			    $uname);
1.524     raeburn  5638:    }
1.715     albertel 5639:    return $reply;
                   5640: }
                   5641: 
                   5642: sub old_putstore {
1.716     albertel 5643:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5644:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5645:     if (!$uname) { $uname=$env{'user.name'}; }
                   5646:     my $uhome=&homeserver($uname,$udomain);
                   5647:     my %newstorehash;
1.800     albertel 5648:     foreach my $item (keys(%$storehash)) {
                   5649: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5650: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5651:     }
                   5652:     my $items='';
                   5653:     my %allitems = ();
1.800     albertel 5654:     foreach my $item (keys(%newstorehash)) {
                   5655: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5656: 	    my $key = $1.':keys:'.$2;
                   5657: 	    $allitems{$key} .= $3.':';
                   5658: 	}
1.800     albertel 5659: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5660:     }
1.800     albertel 5661:     foreach my $item (keys(%allitems)) {
                   5662: 	$allitems{$item} =~ s/\:$//;
                   5663: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5664:     }
                   5665:     $items=~s/\&$//;
                   5666:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5667: }
                   5668: 
1.47      www      5669: # ------------------------------------------------------ critical put interface
                   5670: 
                   5671: sub cput {
1.134     albertel 5672:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5673:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5674:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5675:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5676:    my $items='';
1.800     albertel 5677:    foreach my $item (keys(%$storehash)) {
                   5678:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5679:    }
1.47      www      5680:    $items=~s/\&$//;
1.134     albertel 5681:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5682: }
                   5683: 
                   5684: # -------------------------------------------------------------- eget interface
                   5685: 
                   5686: sub eget {
1.133     albertel 5687:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5688:    my $items='';
1.800     albertel 5689:    foreach my $item (@$storearr) {
                   5690:        $items.=&escape($item).'&';
1.191     harris41 5691:    }
1.12      www      5692:    $items=~s/\&$//;
1.620     albertel 5693:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5694:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5695:    my $uhome=&homeserver($uname,$udomain);
                   5696:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5697:    my @pairs=split(/\&/,$rep);
                   5698:    my %returnhash=();
1.42      www      5699:    my $i=0;
1.800     albertel 5700:    foreach my $item (@$storearr) {
                   5701:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5702:       $i++;
1.191     harris41 5703:    }
1.12      www      5704:    return %returnhash;
                   5705: }
                   5706: 
1.667     albertel 5707: # ------------------------------------------------------------ tmpput interface
                   5708: sub tmpput {
1.802     raeburn  5709:     my ($storehash,$server,$context)=@_;
1.667     albertel 5710:     my $items='';
1.800     albertel 5711:     foreach my $item (keys(%$storehash)) {
                   5712: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5713:     }
                   5714:     $items=~s/\&$//;
1.802     raeburn  5715:     if (defined($context)) {
                   5716:         $items .= ':'.&escape($context);
                   5717:     }
1.667     albertel 5718:     return &reply("tmpput:$items",$server);
                   5719: }
                   5720: 
                   5721: # ------------------------------------------------------------ tmpget interface
                   5722: sub tmpget {
1.688     albertel 5723:     my ($token,$server)=@_;
                   5724:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5725:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5726:     my %returnhash;
                   5727:     foreach my $item (split(/\&/,$rep)) {
                   5728: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5729:         next if ($key =~ /^error: 2 /);
1.667     albertel 5730: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5731:     }
                   5732:     return %returnhash;
                   5733: }
                   5734: 
1.1113    raeburn  5735: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5736: sub tmpdel {
                   5737:     my ($token,$server)=@_;
                   5738:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5739:     return &reply("tmpdel:$token",$server);
                   5740: }
                   5741: 
1.1198    raeburn  5742: # ------------------------------------------------------------ get_timebased_id 
                   5743: 
                   5744: sub get_timebased_id {
                   5745:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5746:         $maxtries) = @_;
                   5747:     my ($newid,$error,$dellock);
                   5748:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5749:         return ('','ok','invalid call to get suffix');
                   5750:     }
                   5751: 
                   5752: # set defaults for any optional args for which values were not supplied
                   5753:     if ($who eq '') {
                   5754:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5755:     }
                   5756:     if (!$locktries) {
                   5757:         $locktries = 3;
                   5758:     }
                   5759:     if (!$maxtries) {
                   5760:         $maxtries = 10;
                   5761:     }
                   5762:     
                   5763:     if (($cdom eq '') || ($cnum eq '')) {
                   5764:         if ($env{'request.course.id'}) {
                   5765:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5766:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5767:         }
                   5768:         if (($cdom eq '') || ($cnum eq '')) {
                   5769:             return ('','ok','call to get suffix not in course context');
                   5770:         }
                   5771:     }
                   5772: 
                   5773: # construct locking item
                   5774:     my $lockhash = {
                   5775:                       $prefix."\0".'locked_'.$keyid => $who,
                   5776:                    };
                   5777:     my $tries = 0;
                   5778: 
                   5779: # attempt to get lock on nohist_$namespace file
                   5780:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5781:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5782:         $tries ++;
                   5783:         sleep 1;
                   5784:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5785:     }
                   5786: 
                   5787: # attempt to get unique identifier, based on current timestamp
                   5788:     if ($gotlock eq 'ok') {
                   5789:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5790:         my $id = time;
                   5791:         $newid = $id;
                   5792:         my $idtries = 0;
                   5793:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5794:             if ($idtype eq 'concat') {
                   5795:                 $newid = $id.$idtries;
                   5796:             } else {
                   5797:                 $newid ++;
                   5798:             }
                   5799:             $idtries ++;
                   5800:         }
                   5801:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5802:             my %new_item =  (
                   5803:                               $prefix."\0".$newid => $who,
                   5804:                             );
                   5805:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5806:                                                  $cdom,$cnum);
                   5807:             if ($putresult ne 'ok') {
                   5808:                 undef($newid);
                   5809:                 $error = 'error saving new item: '.$putresult;
                   5810:             }
                   5811:         } else {
                   5812:              $error = ('error: no unique suffix available for the new item ');
                   5813:         }
                   5814: #  remove lock
                   5815:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5816:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5817:     } else {
                   5818:         $error = "error: could not obtain lockfile\n";
                   5819:         $dellock = 'ok';
                   5820:     }
                   5821:     return ($newid,$dellock,$error);
                   5822: }
                   5823: 
1.765     albertel 5824: # -------------------------------------------------- portfolio access checking
                   5825: 
                   5826: sub portfolio_access {
1.766     albertel 5827:     my ($requrl) = @_;
1.765     albertel 5828:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5829:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5830:     if ($result) {
                   5831:         my %setters;
                   5832:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5833:             my ($startblock,$endblock) =
                   5834:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5835:             if ($startblock && $endblock) {
                   5836:                 return 'B';
                   5837:             }
                   5838:         } else {
                   5839:             my ($startblock,$endblock) =
                   5840:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5841:             if ($startblock && $endblock) {
                   5842:                 return 'B';
                   5843:             }
                   5844:         }
                   5845:     }
1.765     albertel 5846:     if ($result eq 'ok') {
1.766     albertel 5847:        return 'F';
1.765     albertel 5848:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5849:        return 'A';
1.765     albertel 5850:     }
1.766     albertel 5851:     return '';
1.765     albertel 5852: }
                   5853: 
                   5854: sub get_portfolio_access {
1.767     albertel 5855:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5856: 
                   5857:     if (!ref($access_hash)) {
                   5858: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5859: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5860: 						   $file_name);
                   5861: 	$access_hash = $access_controls{$file_name};
                   5862:     }
                   5863: 
1.765     albertel 5864:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5865:     my $now = time;
                   5866:     if (ref($access_hash) eq 'HASH') {
                   5867:         foreach my $key (keys(%{$access_hash})) {
                   5868:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5869:             if ($start > $now) {
                   5870:                 next;
                   5871:             }
                   5872:             if ($end && $end<$now) {
                   5873:                 next;
                   5874:             }
                   5875:             if ($scope eq 'public') {
                   5876:                 $public = $key;
                   5877:                 last;
                   5878:             } elsif ($scope eq 'guest') {
                   5879:                 $guest = $key;
                   5880:             } elsif ($scope eq 'domains') {
                   5881:                 push(@domains,$key);
                   5882:             } elsif ($scope eq 'users') {
                   5883:                 push(@users,$key);
                   5884:             } elsif ($scope eq 'course') {
                   5885:                 push(@courses,$key);
                   5886:             } elsif ($scope eq 'group') {
                   5887:                 push(@groups,$key);
                   5888:             }
                   5889:         }
                   5890:         if ($public) {
                   5891:             return 'ok';
                   5892:         }
                   5893:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5894:             if ($guest) {
                   5895:                 return $guest;
                   5896:             }
                   5897:         } else {
                   5898:             if (@domains > 0) {
                   5899:                 foreach my $domkey (@domains) {
                   5900:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5901:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5902:                             return 'ok';
                   5903:                         }
                   5904:                     }
                   5905:                 }
                   5906:             }
                   5907:             if (@users > 0) {
                   5908:                 foreach my $userkey (@users) {
1.865     raeburn  5909:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5910:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5911:                             if (ref($item) eq 'HASH') {
                   5912:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5913:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5914:                                     return 'ok';
                   5915:                                 }
                   5916:                             }
                   5917:                         }
                   5918:                     } 
1.765     albertel 5919:                 }
                   5920:             }
                   5921:             my %roleshash;
                   5922:             my @courses_and_groups = @courses;
                   5923:             push(@courses_and_groups,@groups); 
                   5924:             if (@courses_and_groups > 0) {
                   5925:                 my (%allgroups,%allroles); 
                   5926:                 my ($start,$end,$role,$sec,$group);
                   5927:                 foreach my $envkey (%env) {
1.1060    raeburn  5928:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5929:                         my $cid = $2.'_'.$3; 
                   5930:                         if ($1 eq 'gr') {
                   5931:                             $group = $4;
                   5932:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5933:                         } else {
                   5934:                             if ($4 eq '') {
                   5935:                                 $sec = 'none';
                   5936:                             } else {
                   5937:                                 $sec = $4;
                   5938:                             }
                   5939:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5940:                         }
1.811     albertel 5941:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5942:                         my $cid = $2.'_'.$3;
                   5943:                         if ($4 eq '') {
                   5944:                             $sec = 'none';
                   5945:                         } else {
                   5946:                             $sec = $4;
                   5947:                         }
                   5948:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5949:                     }
                   5950:                 }
                   5951:                 if (keys(%allroles) == 0) {
                   5952:                     return;
                   5953:                 }
                   5954:                 foreach my $key (@courses_and_groups) {
                   5955:                     my %content = %{$$access_hash{$key}};
                   5956:                     my $cnum = $content{'number'};
                   5957:                     my $cdom = $content{'domain'};
                   5958:                     my $cid = $cdom.'_'.$cnum;
                   5959:                     if (!exists($allroles{$cid})) {
                   5960:                         next;
                   5961:                     }    
                   5962:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5963:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5964:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5965:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5966:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5967:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5968:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5969:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5970:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5971:                                         if (grep/^all$/,@sections) {
                   5972:                                             return 'ok';
                   5973:                                         } else {
                   5974:                                             if (grep/^$sec$/,@sections) {
                   5975:                                                 return 'ok';
                   5976:                                             }
                   5977:                                         }
                   5978:                                     }
                   5979:                                 }
                   5980:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5981:                                     if (grep/^none$/,@groups) {
                   5982:                                         return 'ok';
                   5983:                                     }
                   5984:                                 } else {
                   5985:                                     if (grep/^all$/,@groups) {
                   5986:                                         return 'ok';
                   5987:                                     } 
                   5988:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5989:                                         if (grep/^$group$/,@groups) {
                   5990:                                             return 'ok';
                   5991:                                         }
                   5992:                                     }
                   5993:                                 } 
                   5994:                             }
                   5995:                         }
                   5996:                     }
                   5997:                 }
                   5998:             }
                   5999:             if ($guest) {
                   6000:                 return $guest;
                   6001:             }
                   6002:         }
                   6003:     }
                   6004:     return;
                   6005: }
                   6006: 
                   6007: sub course_group_datechecker {
                   6008:     my ($dates,$now,$status) = @_;
                   6009:     my ($start,$end) = split(/\./,$dates);
                   6010:     if (!$start && !$end) {
                   6011:         return 'ok';
                   6012:     }
                   6013:     if (grep/^active$/,@{$status}) {
                   6014:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6015:             return 'ok';
                   6016:         }
                   6017:     }
                   6018:     if (grep/^previous$/,@{$status}) {
                   6019:         if ($end > $now ) {
                   6020:             return 'ok';
                   6021:         }
                   6022:     }
                   6023:     if (grep/^future$/,@{$status}) {
                   6024:         if ($start > $now) {
                   6025:             return 'ok';
                   6026:         }
                   6027:     }
                   6028:     return; 
                   6029: }
                   6030: 
                   6031: sub parse_portfolio_url {
                   6032:     my ($url) = @_;
                   6033: 
                   6034:     my ($type,$udom,$unum,$group,$file_name);
                   6035:     
1.823     albertel 6036:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6037: 	$type = 1;
                   6038:         $udom = $1;
                   6039:         $unum = $2;
                   6040:         $file_name = $3;
1.823     albertel 6041:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6042: 	$type = 2;
                   6043:         $udom = $1;
                   6044:         $unum = $2;
                   6045:         $group = $3;
                   6046:         $file_name = $3.'/'.$4;
                   6047:     }
                   6048:     if (wantarray) {
                   6049: 	return ($type,$udom,$unum,$file_name,$group);
                   6050:     }
                   6051:     return $type;
                   6052: }
                   6053: 
                   6054: sub is_portfolio_url {
                   6055:     my ($url) = @_;
                   6056:     return scalar(&parse_portfolio_url($url));
                   6057: }
                   6058: 
1.798     raeburn  6059: sub is_portfolio_file {
                   6060:     my ($file) = @_;
1.820     raeburn  6061:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6062:         return 1;
                   6063:     }
                   6064:     return;
                   6065: }
                   6066: 
1.976     raeburn  6067: sub usertools_access {
1.1084    raeburn  6068:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6069:     my ($access,%tools);
                   6070:     if ($context eq '') {
                   6071:         $context = 'tools';
                   6072:     }
                   6073:     if ($context eq 'requestcourses') {
                   6074:         %tools = (
                   6075:                       official   => 1,
                   6076:                       unofficial => 1,
1.1006    raeburn  6077:                       community  => 1,
1.985     raeburn  6078:                  );
1.1183    raeburn  6079:     } elsif ($context eq 'requestauthor') {
                   6080:         %tools = (
                   6081:                       requestauthor => 1,
                   6082:                  );
1.985     raeburn  6083:     } else {
                   6084:         %tools = (
                   6085:                       aboutme   => 1,
                   6086:                       blog      => 1,
1.1177    raeburn  6087:                       webdav    => 1,
1.985     raeburn  6088:                       portfolio => 1,
                   6089:                  );
                   6090:     }
1.976     raeburn  6091:     return if (!defined($tools{$tool}));
                   6092: 
                   6093:     if ((!defined($udom)) || (!defined($uname))) {
                   6094:         $udom = $env{'user.domain'};
                   6095:         $uname = $env{'user.name'};
                   6096:     }
                   6097: 
1.978     raeburn  6098:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6099:         if ($action ne 'reload') {
1.985     raeburn  6100:             if ($context eq 'requestcourses') {
                   6101:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6102:             } elsif ($context eq 'requestauthor') {
                   6103:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6104:             } else {
                   6105:                 return $env{'environment.availabletools.'.$tool};
                   6106:             }
                   6107:         }
1.976     raeburn  6108:     }
                   6109: 
1.1183    raeburn  6110:     my ($toolstatus,$inststatus,$envkey);
                   6111:     if ($context eq 'requestauthor') {
                   6112:         $envkey = $context; 
                   6113:     } else {
                   6114:         $envkey = $context.'.'.$tool;
                   6115:     }
1.976     raeburn  6116: 
1.985     raeburn  6117:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6118:          ($action ne 'reload')) {
1.1183    raeburn  6119:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6120:         $inststatus = $env{'environment.inststatus'};
                   6121:     } else {
1.1084    raeburn  6122:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6123:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6124:             $inststatus = $userenvref->{'inststatus'};
                   6125:         } else {
1.1183    raeburn  6126:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6127:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6128:             $inststatus = $userenv{'inststatus'};
                   6129:         }
1.976     raeburn  6130:     }
                   6131: 
                   6132:     if ($toolstatus ne '') {
                   6133:         if ($toolstatus) {
                   6134:             $access = 1;
                   6135:         } else {
                   6136:             $access = 0;
                   6137:         }
                   6138:         return $access;
                   6139:     }
                   6140: 
1.1084    raeburn  6141:     my ($is_adv,%domdef);
                   6142:     if (ref($is_advref) eq 'HASH') {
                   6143:         $is_adv = $is_advref->{'is_adv'};
                   6144:     } else {
                   6145:         $is_adv = &is_advanced_user($udom,$uname);
                   6146:     }
                   6147:     if (ref($domdefref) eq 'HASH') {
                   6148:         %domdef = %{$domdefref};
                   6149:     } else {
                   6150:         %domdef = &get_domain_defaults($udom);
                   6151:     }
1.976     raeburn  6152:     if (ref($domdef{$tool}) eq 'HASH') {
                   6153:         if ($is_adv) {
                   6154:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6155:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6156:                     $access = 1;
                   6157:                 } else {
                   6158:                     $access = 0;
                   6159:                 }
                   6160:                 return $access;
                   6161:             }
                   6162:         }
                   6163:         if ($inststatus ne '') {
                   6164:             my ($hasaccess,$hasnoaccess);
                   6165:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6166:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6167:                     if ($domdef{$tool}{$affiliation}) {
                   6168:                         $hasaccess = 1;
                   6169:                     } else {
                   6170:                         $hasnoaccess = 1;
                   6171:                     }
                   6172:                 }
                   6173:             }
                   6174:             if ($hasaccess || $hasnoaccess) {
                   6175:                 if ($hasaccess) {
                   6176:                     $access = 1;
                   6177:                 } elsif ($hasnoaccess) {
                   6178:                     $access = 0; 
                   6179:                 }
                   6180:                 return $access;
                   6181:             }
                   6182:         } else {
                   6183:             if ($domdef{$tool}{'default'} ne '') {
                   6184:                 if ($domdef{$tool}{'default'}) {
                   6185:                     $access = 1;
                   6186:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6187:                     $access = 0;
                   6188:                 }
                   6189:                 return $access;
                   6190:             }
                   6191:         }
                   6192:     } else {
1.1177    raeburn  6193:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6194:             $access = 1;
                   6195:         } else {
                   6196:             $access = 0;
                   6197:         }
1.976     raeburn  6198:         return $access;
                   6199:     }
                   6200: }
                   6201: 
1.1050    raeburn  6202: sub is_course_owner {
                   6203:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6204:     if (($udom eq '') || ($uname eq '')) {
                   6205:         $udom = $env{'user.domain'};
                   6206:         $uname = $env{'user.name'};
                   6207:     }
                   6208:     unless (($udom eq '') || ($uname eq '')) {
                   6209:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6210:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6211:                 return 1;
                   6212:             } else {
                   6213:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6214:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6215:                     return 1;
                   6216:                 }
                   6217:             }
                   6218:         }
                   6219:     }
                   6220:     return;
                   6221: }
                   6222: 
1.976     raeburn  6223: sub is_advanced_user {
                   6224:     my ($udom,$uname) = @_;
1.1085    raeburn  6225:     if ($udom ne '' && $uname ne '') {
                   6226:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6227:             if (wantarray) {
                   6228:                 return ($env{'user.adv'},$env{'user.author'});
                   6229:             } else {
                   6230:                 return $env{'user.adv'};
                   6231:             }
1.1085    raeburn  6232:         }
                   6233:     }
1.976     raeburn  6234:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6235:     my %allroles;
1.1128    raeburn  6236:     my ($is_adv,$is_author);
1.976     raeburn  6237:     foreach my $role (keys(%roleshash)) {
                   6238:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6239:         my $area = '/'.$tdomain.'/'.$trest;
                   6240:         if ($sec ne '') {
                   6241:             $area .= '/'.$sec;
                   6242:         }
                   6243:         if (($area ne '') && ($trole ne '')) {
                   6244:             my $spec=$trole.'.'.$area;
                   6245:             if ($trole =~ /^cr\//) {
                   6246:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6247:             } elsif ($trole ne 'gr') {
                   6248:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6249:             }
1.1128    raeburn  6250:             if ($trole eq 'au') {
                   6251:                 $is_author = 1;
                   6252:             }
1.976     raeburn  6253:         }
                   6254:     }
                   6255:     foreach my $role (keys(%allroles)) {
                   6256:         last if ($is_adv);
                   6257:         foreach my $item (split(/:/,$allroles{$role})) {
                   6258:             if ($item ne '') {
                   6259:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6260:                 if ($privilege eq 'adv') {
                   6261:                     $is_adv = 1;
                   6262:                     last;
                   6263:                 }
                   6264:             }
                   6265:         }
                   6266:     }
1.1128    raeburn  6267:     if (wantarray) {
                   6268:         return ($is_adv,$is_author);
                   6269:     }
1.976     raeburn  6270:     return $is_adv;
                   6271: }
1.798     raeburn  6272: 
1.1035    raeburn  6273: sub check_can_request {
1.1036    raeburn  6274:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6275:     my $canreq = 0;
                   6276:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6277:     my @options = ('approval','validate','autolimit');
                   6278:     my $optregex = join('|',@options);
                   6279:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6280:         foreach my $type (@{$types}) {
                   6281:             if (&usertools_access($env{'user.name'},
                   6282:                                   $env{'user.domain'},
                   6283:                                   $type,undef,'requestcourses')) {
                   6284:                 $canreq ++;
1.1036    raeburn  6285:                 if (ref($request_domains) eq 'HASH') {
                   6286:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6287:                 }
1.1035    raeburn  6288:                 if ($dom eq $env{'user.domain'}) {
                   6289:                     $can_request->{$type} = 1;
                   6290:                 }
                   6291:             }
                   6292:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6293:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6294:                 if (@curr > 0) {
1.1036    raeburn  6295:                     foreach my $item (@curr) {
                   6296:                         if (ref($request_domains) eq 'HASH') {
                   6297:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6298:                             if ($otherdom ne '') {
                   6299:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6300:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6301:                                         push(@{$request_domains->{$type}},$otherdom);
                   6302:                                     }
                   6303:                                 } else {
                   6304:                                     push(@{$request_domains->{$type}},$otherdom);
                   6305:                                 }
                   6306:                             }
                   6307:                         }
                   6308:                     }
                   6309:                     unless($dom eq $env{'user.domain'}) {
                   6310:                         $canreq ++;
1.1035    raeburn  6311:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6312:                             $can_request->{$type} = 1;
                   6313:                         }
                   6314:                     }
                   6315:                 }
                   6316:             }
                   6317:         }
                   6318:     }
                   6319:     return $canreq;
                   6320: }
                   6321: 
1.341     www      6322: # ---------------------------------------------- Custom access rule evaluation
                   6323: 
                   6324: sub customaccess {
                   6325:     my ($priv,$uri)=@_;
1.807     albertel 6326:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6327:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6328:     $udom = &LONCAPA::clean_domain($udom);
                   6329:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6330:     my $access=0;
1.800     albertel 6331:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6332: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6333: 	if ($type eq 'user') {
                   6334: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6335: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6336: 		if ($tdom) {
                   6337: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6338: 		}
1.896     albertel 6339: 		if ($tuname) {
                   6340: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6341: 		}
                   6342: 		$access=($effect eq 'allow');
                   6343: 		last;
                   6344: 	    }
                   6345: 	} else {
                   6346: 	    if ($role) {
                   6347: 		if ($role ne $urole) { next; }
                   6348: 	    }
                   6349: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6350: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6351: 		if ($tdom) {
                   6352: 		    if ($tdom ne $udom) { next; }
                   6353: 		}
                   6354: 		if ($tcrs) {
                   6355: 		    if ($tcrs ne $ucrs) { next; }
                   6356: 		}
                   6357: 		if ($tsec) {
                   6358: 		    if ($tsec ne $usec) { next; }
                   6359: 		}
                   6360: 		$access=($effect eq 'allow');
                   6361: 		last;
                   6362: 	    }
                   6363: 	    if ($realm eq '' && $role eq '') {
                   6364: 		$access=($effect eq 'allow');
                   6365: 	    }
1.402     bowersj2 6366: 	}
1.341     www      6367:     }
                   6368:     return $access;
                   6369: }
                   6370: 
1.103     harris41 6371: # ------------------------------------------------- Check for a user privilege
1.12      www      6372: 
                   6373: sub allowed {
1.810     raeburn  6374:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6375:     my $ver_orguri=$uri;
1.439     www      6376:     $uri=&deversion($uri);
1.152     www      6377:     my $orguri=$uri;
1.52      www      6378:     $uri=&declutter($uri);
1.809     raeburn  6379: 
1.810     raeburn  6380:     if ($priv eq 'evb') {
                   6381: # Evade communication block restrictions for specified role in a course
                   6382:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6383:             return $1;
                   6384:         } else {
                   6385:             return;
                   6386:         }
                   6387:     }
                   6388: 
1.620     albertel 6389:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6390: # Free bre access to adm and meta resources
1.775     albertel 6391:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6392: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6393: 	&& ($priv eq 'bre')) {
1.14      www      6394: 	return 'F';
1.159     www      6395:     }
                   6396: 
1.545     banghart 6397: # Free bre access to user's own portfolio contents
1.714     raeburn  6398:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6399:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6400: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6401:         my %setters;
                   6402:         my ($startblock,$endblock) = 
                   6403:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6404:         if ($startblock && $endblock) {
                   6405:             return 'B';
                   6406:         } else {
                   6407:             return 'F';
                   6408:         }
1.545     banghart 6409:     }
                   6410: 
1.762     raeburn  6411: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6412:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6413:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6414:         if (exists($env{'request.course.id'})) {
                   6415:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6416:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6417:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6418:                 my $courseprivid=$env{'request.course.id'};
                   6419:                 $courseprivid=~s/\_/\//;
                   6420:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6421:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6422:                     return $1; 
1.762     raeburn  6423:                 } else {
                   6424:                     if ($env{'request.course.sec'}) {
                   6425:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6426:                     }
                   6427:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6428:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6429:                         return $2;
                   6430:                     }
1.714     raeburn  6431:                 }
                   6432:             }
                   6433:         }
                   6434:     }
                   6435: 
1.159     www      6436: # Free bre to public access
                   6437: 
                   6438:     if ($priv eq 'bre') {
1.238     www      6439:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6440: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6441:            return 'F'; 
                   6442:         }
1.238     www      6443:         if ($copyright eq 'priv') {
                   6444:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6445: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6446: 		return '';
                   6447:             }
                   6448:         }
                   6449:         if ($copyright eq 'domain') {
                   6450:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6451: 	    unless (($env{'user.domain'} eq $1) ||
                   6452:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6453: 		return '';
                   6454:             }
1.262     matthew  6455:         }
1.620     albertel 6456:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6457:             # Library role, so allow browsing of resources in this domain.
                   6458:             return 'F';
1.238     www      6459:         }
1.341     www      6460:         if ($copyright eq 'custom') {
                   6461: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6462:         }
1.14      www      6463:     }
1.264     matthew  6464:     # Domain coordinator is trying to create a course
1.620     albertel 6465:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6466:         # uri is the requested domain in this case.
                   6467:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6468:         # a role of dc for the domain in question.
1.620     albertel 6469:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6470:     }
1.29      www      6471: 
1.52      www      6472:     my $thisallowed='';
                   6473:     my $statecond=0;
                   6474:     my $courseprivid='';
                   6475: 
1.1039    raeburn  6476:     my $ownaccess;
1.1043    raeburn  6477:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6478:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6479:         if ($uri eq '') {
                   6480:             $ownaccess = 1;
                   6481:         } else {
                   6482:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6483:                 my $udom = $env{'user.domain'};
                   6484:                 my $uname = $env{'user.name'};
                   6485:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6486:                     $ownaccess = 1;
1.1040    raeburn  6487:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6488:                     unless ($uri =~ m{\.\./}) {
                   6489:                         $ownaccess = 1;
                   6490:                     }
                   6491:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6492:                     my $now = time;
                   6493:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6494:                         my $adom = $1;
                   6495:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6496:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6497:                                 my ($start,$end) = split('.',$env{$key});
                   6498:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6499:                                     $ownaccess = 1;
                   6500:                                     last;
                   6501:                                 }
                   6502:                             }
                   6503:                         }
                   6504:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6505:                         my $adom = $1;
                   6506:                         my $aname = $2;
1.1042    raeburn  6507:                         foreach my $role ('ca','aa') { 
                   6508:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6509:                                 my ($start,$end) =
                   6510:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6511:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6512:                                     $ownaccess = 1;
                   6513:                                     last;
                   6514:                                 }
1.1039    raeburn  6515:                             }
                   6516:                         }
                   6517:                     }
                   6518:                 }
                   6519:             }
                   6520:         }
                   6521:     }
                   6522: 
1.52      www      6523: # Course
                   6524: 
1.620     albertel 6525:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6526:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6527:             $thisallowed.=$1;
                   6528:         }
1.52      www      6529:     }
1.29      www      6530: 
1.52      www      6531: # Domain
                   6532: 
1.620     albertel 6533:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6534:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6535:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6536:             $thisallowed.=$1;
                   6537:         }
1.12      www      6538:     }
1.52      www      6539: 
1.1141    raeburn  6540: # User who is not author or co-author might still be able to edit
                   6541: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6542:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6543:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6544:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6545:             $thisallowed.=$1;
                   6546:         }
                   6547:     }
                   6548: 
1.52      www      6549: # Course: uri itself is a course
1.66      www      6550:     my $courseuri=$uri;
                   6551:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6552:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6553: 
1.620     albertel 6554:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6555:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6556:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6557:             $thisallowed.=$1;
                   6558:         }
1.12      www      6559:     }
1.29      www      6560: 
1.665     albertel 6561: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6562: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6563:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6564: 	$thisallowed='';
1.671     raeburn  6565:         my ($match)=&is_on_map($uri);
                   6566:         if ($match) {
                   6567:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6568:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6569:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6570:                 if (@blockers > 0) {
                   6571:                     $thisallowed = 'B';
                   6572:                 } else {
                   6573:                     $thisallowed.=$1;
                   6574:                 }
1.671     raeburn  6575:             }
                   6576:         } else {
1.705     albertel 6577:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6578:             if ($refuri) {
                   6579:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6580:                     $thisallowed='F';
1.671     raeburn  6581:                 } else {
                   6582:                     $refuri=&declutter($refuri);
                   6583:                     my ($match) = &is_on_map($refuri);
                   6584:                     if ($match) {
1.1162    raeburn  6585:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6586:                         if (@blockers > 0) {
                   6587:                             $thisallowed = 'B';
                   6588:                         } else {
                   6589:                             $thisallowed='F';
                   6590:                         }
1.671     raeburn  6591:                     }
1.669     raeburn  6592:                 }
1.671     raeburn  6593:             }
                   6594:         }
1.314     www      6595:     }
1.492     albertel 6596: 
1.766     albertel 6597:     if ($priv eq 'bre'
                   6598: 	&& $thisallowed ne 'F' 
                   6599: 	&& $thisallowed ne '2'
                   6600: 	&& &is_portfolio_url($uri)) {
                   6601: 	$thisallowed = &portfolio_access($uri);
                   6602:     }
                   6603:     
1.52      www      6604: # Full access at system, domain or course-wide level? Exit.
1.29      www      6605:     if ($thisallowed=~/F/) {
                   6606: 	return 'F';
                   6607:     }
                   6608: 
1.52      www      6609: # If this is generating or modifying users, exit with special codes
1.29      www      6610: 
1.643     www      6611:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6612: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6613: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6614: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6615: 	    unless ($auname) { return $thisallowed; }
                   6616: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6617: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6618: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6619: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6620: 	}
1.52      www      6621: 	return $thisallowed;
                   6622:     }
                   6623: #
1.103     harris41 6624: # Gathered so far: system, domain and course wide privileges
1.52      www      6625: #
                   6626: # Course: See if uri or referer is an individual resource that is part of 
                   6627: # the course
                   6628: 
1.620     albertel 6629:     if ($env{'request.course.id'}) {
1.232     www      6630: 
1.620     albertel 6631:        $courseprivid=$env{'request.course.id'};
                   6632:        if ($env{'request.course.sec'}) {
                   6633:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6634:        }
                   6635:        $courseprivid=~s/\_/\//;
                   6636:        my $checkreferer=1;
1.232     www      6637:        my ($match,$cond)=&is_on_map($uri);
                   6638:        if ($match) {
                   6639:            $statecond=$cond;
1.620     albertel 6640:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6641:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6642:                my $value = $1;
                   6643:                if ($priv eq 'bre') {
                   6644:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6645:                    if (@blockers > 0) {
                   6646:                        $thisallowed = 'B';
                   6647:                    } else {
                   6648:                        $thisallowed.=$value;
                   6649:                    }
                   6650:                } else {
                   6651:                    $thisallowed.=$value;
                   6652:                }
1.52      www      6653:                $checkreferer=0;
                   6654:            }
1.29      www      6655:        }
1.83      www      6656:        
1.148     www      6657:        if ($checkreferer) {
1.620     albertel 6658: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6659:             unless ($refuri) {
1.800     albertel 6660:                 foreach my $key (keys(%env)) {
                   6661: 		    if ($key=~/^httpref\..*\*/) {
                   6662: 			my $pattern=$key;
1.156     www      6663:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6664:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6665:                         $pattern=~s/\//\\\//g;
1.152     www      6666:                         if ($orguri=~/$pattern/) {
1.800     albertel 6667: 			    $refuri=$env{$key};
1.148     www      6668:                         }
                   6669:                     }
1.191     harris41 6670:                 }
1.148     www      6671:             }
1.232     www      6672: 
1.148     www      6673:          if ($refuri) { 
1.152     www      6674: 	  $refuri=&declutter($refuri);
1.232     www      6675:           my ($match,$cond)=&is_on_map($refuri);
                   6676:             if ($match) {
                   6677:               my $refstatecond=$cond;
1.620     albertel 6678:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6679:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6680:                   my $value = $1;
                   6681:                   if ($priv eq 'bre') {
                   6682:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6683:                       if (@blockers > 0) {
                   6684:                           $thisallowed = 'B';
                   6685:                       } else {
                   6686:                           $thisallowed.=$value;
                   6687:                       }
                   6688:                   } else {
                   6689:                       $thisallowed.=$value;
                   6690:                   }
1.53      www      6691:                   $uri=$refuri;
                   6692:                   $statecond=$refstatecond;
1.52      www      6693:               }
                   6694:           }
1.148     www      6695:         }
1.29      www      6696:        }
1.52      www      6697:    }
1.29      www      6698: 
1.52      www      6699: #
1.103     harris41 6700: # Gathered now: all privileges that could apply, and condition number
1.52      www      6701: # 
                   6702: #
                   6703: # Full or no access?
                   6704: #
1.29      www      6705: 
1.52      www      6706:     if ($thisallowed=~/F/) {
                   6707: 	return 'F';
                   6708:     }
1.29      www      6709: 
1.52      www      6710:     unless ($thisallowed) {
                   6711:         return '';
                   6712:     }
1.29      www      6713: 
1.52      www      6714: # Restrictions exist, deal with them
                   6715: #
                   6716: #   C:according to course preferences
                   6717: #   R:according to resource settings
                   6718: #   L:unless locked
                   6719: #   X:according to user session state
                   6720: #
                   6721: 
                   6722: # Possibly locked functionality, check all courses
1.54      www      6723: # Locks might take effect only after 10 minutes cache expiration for other
                   6724: # courses, and 2 minutes for current course
1.52      www      6725: 
                   6726:     my $envkey;
                   6727:     if ($thisallowed=~/L/) {
1.1000    raeburn  6728:         foreach $envkey (keys(%env)) {
1.54      www      6729:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6730:                my $courseid=$2;
                   6731:                my $roleid=$1.'.'.$2;
1.92      www      6732:                $courseid=~s/^\///;
1.54      www      6733:                my $expiretime=600;
1.620     albertel 6734:                if ($env{'request.role'} eq $roleid) {
1.54      www      6735: 		  $expiretime=120;
                   6736:                }
                   6737: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6738:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6739:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6740: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6741:                }
1.620     albertel 6742:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6743:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6744: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6745:                        &log($env{'user.domain'},$env{'user.name'},
                   6746:                             $env{'user.home'},
1.57      www      6747:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6748:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6749:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6750: 		       return '';
                   6751:                    }
                   6752:                }
1.620     albertel 6753:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6754:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6755: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6756:                        &log($env{'user.domain'},$env{'user.name'},
                   6757:                             $env{'user.home'},
1.57      www      6758:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6759:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6760:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6761: 		       return '';
                   6762:                    }
                   6763:                }
                   6764: 	   }
1.29      www      6765:        }
1.52      www      6766:     }
                   6767:    
                   6768: #
                   6769: # Rest of the restrictions depend on selected course
                   6770: #
                   6771: 
1.620     albertel 6772:     unless ($env{'request.course.id'}) {
1.766     albertel 6773: 	if ($thisallowed eq 'A') {
                   6774: 	    return 'A';
1.814     raeburn  6775:         } elsif ($thisallowed eq 'B') {
                   6776:             return 'B';
1.766     albertel 6777: 	} else {
                   6778: 	    return '1';
                   6779: 	}
1.52      www      6780:     }
1.29      www      6781: 
1.52      www      6782: #
                   6783: # Now user is definitely in a course
                   6784: #
1.53      www      6785: 
                   6786: 
                   6787: # Course preferences
                   6788: 
                   6789:    if ($thisallowed=~/C/) {
1.620     albertel 6790:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6791:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6792:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6793: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6794: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6795: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6796: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6797: 			$env{'request.course.id'});
                   6798: 	   }
1.237     www      6799:            return '';
                   6800:        }
                   6801: 
1.620     albertel 6802:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6803: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6804: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6805: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6806: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6807: 			$env{'request.course.id'});
                   6808: 	   }
1.54      www      6809:            return '';
                   6810:        }
1.53      www      6811:    }
                   6812: 
                   6813: # Resource preferences
                   6814: 
                   6815:    if ($thisallowed=~/R/) {
1.620     albertel 6816:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6817:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6818: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6819: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6820: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6821: 	   }
                   6822: 	   return '';
1.54      www      6823:        }
1.53      www      6824:    }
1.30      www      6825: 
1.246     www      6826: # Restricted by state or randomout?
1.30      www      6827: 
1.52      www      6828:    if ($thisallowed=~/X/) {
1.620     albertel 6829:       if ($env{'acc.randomout'}) {
1.579     albertel 6830: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6831:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6832:             return ''; 
                   6833:          }
1.247     www      6834:       }
                   6835:       if (&condval($statecond)) {
1.52      www      6836: 	 return '2';
                   6837:       } else {
                   6838:          return '';
                   6839:       }
                   6840:    }
1.30      www      6841: 
1.766     albertel 6842:     if ($thisallowed eq 'A') {
                   6843: 	return 'A';
1.814     raeburn  6844:     } elsif ($thisallowed eq 'B') {
                   6845:         return 'B';
1.766     albertel 6846:     }
1.52      www      6847:    return 'F';
1.232     www      6848: }
1.1162    raeburn  6849: 
1.1192    raeburn  6850: # ------------------------------------------- Check construction space access
                   6851: 
                   6852: sub constructaccess {
                   6853:     my ($url,$setpriv)=@_;
                   6854: 
                   6855: # We do not allow editing of previous versions of files
                   6856:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6857: 
                   6858: # Get username and domain from URL
                   6859:     my ($ownername,$ownerdomain,$ownerhome);
                   6860: 
                   6861:     ($ownerdomain,$ownername) =
                   6862:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6863: 
                   6864: # The URL does not really point to any authorspace, forget it
                   6865:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6866: 
                   6867: # Now we need to see if the user has access to the authorspace of
                   6868: # $ownername at $ownerdomain
                   6869: 
                   6870:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6871: # Real author for this?
                   6872:        $ownerhome = $env{'user.home'};
                   6873:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6874:           return ($ownername,$ownerdomain,$ownerhome);
                   6875:        }
                   6876:     } else {
                   6877: # Co-author for this?
                   6878:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6879:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6880:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6881:             return ($ownername,$ownerdomain,$ownerhome);
                   6882:         }
                   6883:     }
                   6884: 
                   6885: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6886: # we might as well leave
                   6887:    unless ($setpriv) { return ''; }
                   6888: 
                   6889: # Backdoor access?
                   6890:     my $allowed=&allowed('eco',$ownerdomain);
                   6891: # Nope
                   6892:     unless ($allowed) { return ''; }
                   6893: # Looks like we may have access, but could be locked by the owner of the construction space
                   6894:     if ($allowed eq 'U') {
                   6895:         my %blocked=&get('environment',['domcoord.author'],
                   6896:                          $ownerdomain,$ownername);
                   6897: # Is blocked by owner
                   6898:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6899:     }
                   6900:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6901: # Grant temporary access
                   6902:         my $then=$env{'user.login.time'};
1.1209    raeburn  6903:         my $update=$env{'user.update.time'};
1.1192    raeburn  6904:         if (!$update) { $update = $then; }
                   6905:         my $refresh=$env{'user.refresh.time'};
                   6906:         if (!$refresh) { $refresh = $update; }
                   6907:         my $now = time;
                   6908:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6909:                            $now,'ca','constructaccess');
                   6910:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6911:         return($ownername,$ownerdomain,$ownerhome);
                   6912:     }
                   6913: # No business here
                   6914:     return '';
                   6915: }
                   6916: 
1.1162    raeburn  6917: sub get_comm_blocks {
                   6918:     my ($cdom,$cnum) = @_;
                   6919:     if ($cdom eq '' || $cnum eq '') {
                   6920:         return unless ($env{'request.course.id'});
                   6921:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6922:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6923:     }
                   6924:     my %commblocks;
                   6925:     my $hashid=$cdom.'_'.$cnum;
                   6926:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6927:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6928:         %commblocks = %{$blocksref};
                   6929:     } else {
                   6930:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6931:         my $cachetime = 600;
                   6932:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6933:     }
                   6934:     return %commblocks;
                   6935: }
                   6936: 
                   6937: sub has_comm_blocking {
                   6938:     my ($priv,$symb,$uri,$blocks) = @_;
                   6939:     return unless ($env{'request.course.id'});
                   6940:     return unless ($priv eq 'bre');
                   6941:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6942:     my %commblocks;
                   6943:     if (ref($blocks) eq 'HASH') {
                   6944:         %commblocks = %{$blocks};
                   6945:     } else {
                   6946:         %commblocks = &get_comm_blocks();
                   6947:     }
                   6948:     return unless (keys(%commblocks) > 0);
                   6949:     if (!$symb) { $symb=&symbread($uri,1); }
                   6950:     my ($map,$resid,undef)=&decode_symb($symb);
                   6951:     my %tocheck = (
                   6952:                     maps      => $map,
                   6953:                     resources => $symb,
                   6954:                   );
                   6955:     my @blockers;
                   6956:     my $now = time;
1.1163    raeburn  6957:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6958:     foreach my $block (keys(%commblocks)) {
                   6959:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6960:             my ($start,$end) = ($1,$2);
                   6961:             if ($start <= $now && $end >= $now) {
                   6962:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6963:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6964:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6965:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6966:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6967:                                     push(@blockers,$block);
                   6968:                                 }
                   6969:                             }
                   6970:                         }
                   6971:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6972:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6973:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6974:                                     push(@blockers,$block);
                   6975:                                 }
                   6976:                             }
                   6977:                         }
                   6978:                     }
                   6979:                 }
                   6980:             }
                   6981:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6982:             my $item = $1;
1.1163    raeburn  6983:             my @to_test;
1.1162    raeburn  6984:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6985:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6986:                     my $check_interval;
                   6987:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6988:                         my @interval;
                   6989:                         my $type = 'map';
                   6990:                         if ($item eq 'course') {
                   6991:                             $type = 'course';
                   6992:                             @interval=&EXT("resource.0.interval");
                   6993:                         } else {
                   6994:                             if ($item =~ /___\d+___/) {
                   6995:                                 $type = 'resource';
                   6996:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6997:                                 if (ref($navmap)) {                        
                   6998:                                     my $res = $navmap->getBySymb($item); 
                   6999:                                     push(@to_test,$res);
                   7000:                                 }
1.1162    raeburn  7001:                             } else {
                   7002:                                 my $mapsymb = &symbread($item,1);
                   7003:                                 if ($mapsymb) {
                   7004:                                     if (ref($navmap)) {
                   7005:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7006:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7007:                                         foreach my $res (@to_test) {
1.1162    raeburn  7008:                                             my $symb = $res->symb();
                   7009:                                             next if ($symb eq $mapsymb);
                   7010:                                             if ($symb ne '') {
                   7011:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7012:                                                 last;
                   7013:                                             }
                   7014:                                         }
                   7015:                                     }
                   7016:                                 }
                   7017:                             }
                   7018:                         }
                   7019:                         if ($interval[0] =~ /\d+/) {
                   7020:                             my $first_access;
                   7021:                             if ($type eq 'resource') {
                   7022:                                 $first_access=&get_first_access($interval[1],$item);
                   7023:                             } elsif ($type eq 'map') {
                   7024:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7025:                             } else {
                   7026:                                 $first_access=&get_first_access($interval[1]);
                   7027:                             }
                   7028:                             if ($first_access) {
                   7029:                                 my $timesup = $first_access+$interval[0];
                   7030:                                 if ($timesup > $now) {
1.1163    raeburn  7031:                                     foreach my $res (@to_test) {
                   7032:                                         if ($res->is_problem()) {
                   7033:                                             if ($res->completable()) {
                   7034:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7035:                                                     push(@blockers,$block);
                   7036:                                                 }
                   7037:                                                 last;
                   7038:                                             }
                   7039:                                         }
1.1162    raeburn  7040:                                     }
                   7041:                                 }
                   7042:                             }
                   7043:                         }
                   7044:                     }
                   7045:                 }
                   7046:             }
                   7047:         }
                   7048:     }
                   7049:     return @blockers;
                   7050: }
                   7051: 
                   7052: sub check_docs_block {
                   7053:     my ($docsblock,$tocheck) =@_;
                   7054:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7055:         return;
                   7056:     }
                   7057:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7058:         if ($tocheck->{'maps'}) {
                   7059:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7060:                 return 1;
                   7061:             }
                   7062:         }
                   7063:     }
                   7064:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7065:         if ($tocheck->{'resources'}) {
                   7066:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7067:                 return 1;
                   7068:             }
                   7069:         }
                   7070:     }
                   7071:     return;
                   7072: }
                   7073: 
1.1133    foxr     7074: #
                   7075: #   Removes the versino from a URI and
                   7076: #   splits it in to its filename and path to the filename.
                   7077: #   Seems like File::Basename could have done this more clearly.
                   7078: #   Parameters:
                   7079: #      $uri   - input URI
                   7080: #   Returns:
                   7081: #     Two element list consisting of 
                   7082: #     $pathname  - the URI up to and excluding the trailing /
                   7083: #     $filename  - The part of the URI following the last /
                   7084: #  NOTE:
                   7085: #    Another realization of this is simply:
                   7086: #    use File::Basename;
                   7087: #    ...
                   7088: #    $uri = shift;
                   7089: #    $filename = basename($uri);
                   7090: #    $path     = dirname($uri);
                   7091: #    return ($filename, $path);
                   7092: #
                   7093: #     The implementation below is probably faster however.
                   7094: #
1.710     albertel 7095: sub split_uri_for_cond {
                   7096:     my $uri=&deversion(&declutter(shift));
                   7097:     my @uriparts=split(/\//,$uri);
                   7098:     my $filename=pop(@uriparts);
                   7099:     my $pathname=join('/',@uriparts);
                   7100:     return ($pathname,$filename);
                   7101: }
1.232     www      7102: # --------------------------------------------------- Is a resource on the map?
                   7103: 
                   7104: sub is_on_map {
1.710     albertel 7105:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7106:     #Trying to find the conditional for the file
1.620     albertel 7107:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7108: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7109:     if ($match) {
1.289     bowersj2 7110: 	return (1,$1);
                   7111:     } else {
1.434     www      7112: 	return (0,0);
1.289     bowersj2 7113:     }
1.12      www      7114: }
                   7115: 
1.427     www      7116: # --------------------------------------------------------- Get symb from alias
                   7117: 
                   7118: sub get_symb_from_alias {
                   7119:     my $symb=shift;
                   7120:     my ($map,$resid,$url)=&decode_symb($symb);
                   7121: # Already is a symb
                   7122:     if ($url) { return $symb; }
                   7123: # Must be an alias
                   7124:     my $aliassymb='';
                   7125:     my %bighash;
1.620     albertel 7126:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7127:                             &GDBM_READER(),0640)) {
                   7128:         my $rid=$bighash{'mapalias_'.$symb};
                   7129: 	if ($rid) {
                   7130: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7131: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7132: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7133: 	}
                   7134:         untie %bighash;
                   7135:     }
                   7136:     return $aliassymb;
                   7137: }
                   7138: 
1.12      www      7139: # ----------------------------------------------------------------- Define Role
                   7140: 
                   7141: sub definerole {
                   7142:   if (allowed('mcr','/')) {
                   7143:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7144:     foreach my $role (split(':',$sysrole)) {
                   7145: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7146:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7147:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7148: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7149:                return "refused:s:$crole&$cqual"; 
                   7150:             }
                   7151:         }
1.191     harris41 7152:     }
1.800     albertel 7153:     foreach my $role (split(':',$domrole)) {
                   7154: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7155:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7156:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7157: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7158:                return "refused:d:$crole&$cqual"; 
                   7159:             }
                   7160:         }
1.191     harris41 7161:     }
1.800     albertel 7162:     foreach my $role (split(':',$courole)) {
                   7163: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7164:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7165:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7166: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7167:                return "refused:c:$crole&$cqual"; 
                   7168:             }
                   7169:         }
1.191     harris41 7170:     }
1.620     albertel 7171:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7172:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7173: 	        "rolesdef_$rolename=".
                   7174:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7175:     return reply($command,$env{'user.home'});
1.12      www      7176:   } else {
                   7177:     return 'refused';
                   7178:   }
1.105     harris41 7179: }
                   7180: 
                   7181: # ---------------- Make a metadata query against the network of library servers
                   7182: 
                   7183: sub metadata_query {
1.244     matthew  7184:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7185:     my %rhash;
1.845     albertel 7186:     my %libserv = &all_library();
1.244     matthew  7187:     my @server_list = (defined($server_array) ? @$server_array
                   7188:                                               : keys(%libserv) );
                   7189:     for my $server (@server_list) {
1.118     harris41 7190: 	unless ($custom or $customshow) {
                   7191: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7192: 	    $rhash{$server}=$reply;
                   7193: 	}
                   7194: 	else {
                   7195: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7196: 			     &escape($custom).':'.&escape($customshow),
                   7197: 			     $server);
                   7198: 	    $rhash{$server}=$reply;
                   7199: 	}
1.112     harris41 7200:     }
1.118     harris41 7201:     return \%rhash;
1.240     www      7202: }
                   7203: 
                   7204: # ----------------------------------------- Send log queries and wait for reply
                   7205: 
                   7206: sub log_query {
                   7207:     my ($uname,$udom,$query,%filters)=@_;
                   7208:     my $uhome=&homeserver($uname,$udom);
                   7209:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7210:     my $uhost=&hostname($uhome);
1.800     albertel 7211:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7212:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7213:                        $uhome);
1.479     albertel 7214:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7215:     return get_query_reply($queryid);
                   7216: }
                   7217: 
1.818     raeburn  7218: # -------------------------- Update MySQL table for portfolio file
                   7219: 
                   7220: sub update_portfolio_table {
1.821     raeburn  7221:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7222:     if ($group ne '') {
                   7223:         $file_name =~s /^\Q$group\E//;
                   7224:     }
1.818     raeburn  7225:     my $homeserver = &homeserver($uname,$udom);
                   7226:     my $queryid=
1.821     raeburn  7227:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7228:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7229:     my $reply = &get_query_reply($queryid);
                   7230:     return $reply;
                   7231: }
                   7232: 
1.899     raeburn  7233: # -------------------------- Update MySQL allusers table
                   7234: 
                   7235: sub update_allusers_table {
                   7236:     my ($uname,$udom,$names) = @_;
                   7237:     my $homeserver = &homeserver($uname,$udom);
                   7238:     my $queryid=
                   7239:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7240:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7241:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7242:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7243:                'generation='.&escape($names->{'generation'}).'%%'.
                   7244:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7245:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7246:     return;
1.899     raeburn  7247: }
                   7248: 
1.508     raeburn  7249: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7250: 
                   7251: sub fetch_enrollment_query {
1.511     raeburn  7252:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7253:     my $homeserver;
1.547     raeburn  7254:     my $maxtries = 1;
1.508     raeburn  7255:     if ($context eq 'automated') {
                   7256:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7257:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7258:     } else {
                   7259:         $homeserver = &homeserver($cnum,$dom);
                   7260:     }
1.838     albertel 7261:     my $host=&hostname($homeserver);
1.506     raeburn  7262:     my $cmd = '';
1.1000    raeburn  7263:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7264:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7265:     }
                   7266:     $cmd =~ s/%%$//;
                   7267:     $cmd = &escape($cmd);
                   7268:     my $query = 'fetchenrollment';
1.620     albertel 7269:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7270:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7271:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7272:         return 'error: '.$queryid;
                   7273:     }
1.506     raeburn  7274:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7275:     my $tries = 1;
                   7276:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7277:         $reply = &get_query_reply($queryid);
                   7278:         $tries ++;
                   7279:     }
1.526     raeburn  7280:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7281:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7282:     } else {
1.901     albertel 7283:         my @responses = split(/:/,$reply);
1.515     raeburn  7284:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7285:             foreach my $line (@responses) {
                   7286:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7287:                 $$replyref{$key} = $value;
                   7288:             }
                   7289:         } else {
1.1117    foxr     7290:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7291:             foreach my $line (@responses) {
                   7292:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7293:                 $$replyref{$key} = $value;
                   7294:                 if ($value > 0) {
1.800     albertel 7295:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7296:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7297:                         my $destname = $pathname.'/'.$filename;
                   7298:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7299:                         if ($xml_classlist =~ /^error/) {
                   7300:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7301:                         } else {
1.506     raeburn  7302:                             if ( open(FILE,">$destname") ) {
                   7303:                                 print FILE &unescape($xml_classlist);
                   7304:                                 close(FILE);
1.526     raeburn  7305:                             } else {
                   7306:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7307:                             }
                   7308:                         }
                   7309:                     }
                   7310:                 }
                   7311:             }
                   7312:         }
                   7313:         return 'ok';
                   7314:     }
                   7315:     return 'error';
                   7316: }
                   7317: 
1.242     www      7318: sub get_query_reply {
                   7319:     my $queryid=shift;
1.1117    foxr     7320:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7321:     my $reply='';
                   7322:     for (1..100) {
                   7323: 	sleep 2;
                   7324:         if (-e $replyfile.'.end') {
1.448     albertel 7325: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7326: 		$reply = join('',<$fh>);
                   7327: 		close($fh);
1.240     www      7328: 	   } else { return 'error: reply_file_error'; }
1.242     www      7329:            return &unescape($reply);
                   7330: 	}
1.240     www      7331:     }
1.242     www      7332:     return 'timeout:'.$queryid;
1.240     www      7333: }
                   7334: 
                   7335: sub courselog_query {
1.241     www      7336: #
                   7337: # possible filters:
                   7338: # url: url or symb
                   7339: # username
                   7340: # domain
                   7341: # action: view, submit, grade
                   7342: # start: timestamp
                   7343: # end: timestamp
                   7344: #
1.240     www      7345:     my (%filters)=@_;
1.620     albertel 7346:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7347:     if ($filters{'url'}) {
                   7348: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7349:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7350:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7351:     }
1.620     albertel 7352:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7353:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7354:     return &log_query($cname,$cdom,'courselog',%filters);
                   7355: }
                   7356: 
                   7357: sub userlog_query {
1.858     raeburn  7358: #
                   7359: # possible filters:
                   7360: # action: log check role
                   7361: # start: timestamp
                   7362: # end: timestamp
                   7363: #
1.240     www      7364:     my ($uname,$udom,%filters)=@_;
                   7365:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7366: }
                   7367: 
1.506     raeburn  7368: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7369: 
                   7370: sub auto_run {
1.508     raeburn  7371:     my ($cnum,$cdom) = @_;
1.876     raeburn  7372:     my $response = 0;
                   7373:     my $settings;
                   7374:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7375:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7376:         $settings = $domconfig{'autoenroll'};
                   7377:         if ($settings->{'run'} eq '1') {
                   7378:             $response = 1;
                   7379:         }
                   7380:     } else {
1.934     raeburn  7381:         my $homeserver;
                   7382:         if (&is_course($cdom,$cnum)) {
                   7383:             $homeserver = &homeserver($cnum,$cdom);
                   7384:         } else {
                   7385:             $homeserver = &domain($cdom,'primary');
                   7386:         }
                   7387:         if ($homeserver ne 'no_host') {
                   7388:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7389:         }
1.876     raeburn  7390:     }
1.506     raeburn  7391:     return $response;
                   7392: }
1.776     albertel 7393: 
1.506     raeburn  7394: sub auto_get_sections {
1.508     raeburn  7395:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7396:     my $homeserver;
                   7397:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7398:         $homeserver = &homeserver($cnum,$cdom);
                   7399:     }
                   7400:     if (!defined($homeserver)) { 
                   7401:         if ($cdom =~ /^$match_domain$/) {
                   7402:             $homeserver = &domain($cdom,'primary');
                   7403:         }
                   7404:     }
                   7405:     my @secs;
                   7406:     if (defined($homeserver)) {
                   7407:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7408:         unless ($response eq 'refused') {
                   7409:             @secs = split(/:/,$response);
                   7410:         }
1.506     raeburn  7411:     }
                   7412:     return @secs;
                   7413: }
1.776     albertel 7414: 
1.506     raeburn  7415: sub auto_new_course {
1.1099    raeburn  7416:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7417:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7418:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7419:     return $response;
                   7420: }
1.776     albertel 7421: 
1.506     raeburn  7422: sub auto_validate_courseID {
1.508     raeburn  7423:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7424:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7425:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7426:     return $response;
                   7427: }
1.776     albertel 7428: 
1.1007    raeburn  7429: sub auto_validate_instcode {
1.1020    raeburn  7430:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7431:     my ($homeserver,$response);
                   7432:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7433:         $homeserver = &homeserver($cnum,$cdom);
                   7434:     }
                   7435:     if (!defined($homeserver)) {
                   7436:         if ($cdom =~ /^$match_domain$/) {
                   7437:             $homeserver = &domain($cdom,'primary');
                   7438:         }
                   7439:     }
1.1065    raeburn  7440:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7441:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  7442:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   7443:     return ($outcome,$description);
1.1007    raeburn  7444: }
                   7445: 
1.506     raeburn  7446: sub auto_create_password {
1.873     raeburn  7447:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7448:     my ($homeserver,$response);
1.506     raeburn  7449:     my $create_passwd = 0;
                   7450:     my $authchk = '';
1.873     raeburn  7451:     if ($udom =~ /^$match_domain$/) {
                   7452:         $homeserver = &domain($udom,'primary');
                   7453:     }
                   7454:     if ($homeserver eq '') {
                   7455:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7456:             $homeserver = &homeserver($cnum,$cdom);
                   7457:         }
                   7458:     }
                   7459:     if ($homeserver eq '') {
                   7460:         $authchk = 'nodomain';
1.506     raeburn  7461:     } else {
1.873     raeburn  7462:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7463:         if ($response eq 'refused') {
                   7464:             $authchk = 'refused';
                   7465:         } else {
1.901     albertel 7466:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7467:         }
1.506     raeburn  7468:     }
                   7469:     return ($authparam,$create_passwd,$authchk);
                   7470: }
                   7471: 
1.706     raeburn  7472: sub auto_photo_permission {
                   7473:     my ($cnum,$cdom,$students) = @_;
                   7474:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7475:     my ($outcome,$perm_reqd,$conditions) = 
                   7476: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7477:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7478: 	return (undef,undef);
                   7479:     }
1.706     raeburn  7480:     return ($outcome,$perm_reqd,$conditions);
                   7481: }
                   7482: 
                   7483: sub auto_checkphotos {
                   7484:     my ($uname,$udom,$pid) = @_;
                   7485:     my $homeserver = &homeserver($uname,$udom);
                   7486:     my ($result,$resulttype);
                   7487:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7488: 				   &escape($uname).':'.&escape($pid),
                   7489: 				   $homeserver));
1.709     albertel 7490:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7491: 	return (undef,undef);
                   7492:     }
1.706     raeburn  7493:     if ($outcome) {
                   7494:         ($result,$resulttype) = split(/:/,$outcome);
                   7495:     } 
                   7496:     return ($result,$resulttype);
                   7497: }
                   7498: 
                   7499: sub auto_photochoice {
                   7500:     my ($cnum,$cdom) = @_;
                   7501:     my $homeserver = &homeserver($cnum,$cdom);
                   7502:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7503: 						       &escape($cdom),
                   7504: 						       $homeserver)));
1.709     albertel 7505:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7506: 	return (undef,undef);
                   7507:     }
1.706     raeburn  7508:     return ($update,$comment);
                   7509: }
                   7510: 
                   7511: sub auto_photoupdate {
                   7512:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7513:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7514:     my $host=&hostname($homeserver);
1.706     raeburn  7515:     my $cmd = '';
                   7516:     my $maxtries = 1;
1.800     albertel 7517:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7518:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7519:     }
                   7520:     $cmd =~ s/%%$//;
                   7521:     $cmd = &escape($cmd);
                   7522:     my $query = 'institutionalphotos';
                   7523:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7524:     unless ($queryid=~/^\Q$host\E\_/) {
                   7525:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7526:         return 'error: '.$queryid;
                   7527:     }
                   7528:     my $reply = &get_query_reply($queryid);
                   7529:     my $tries = 1;
                   7530:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7531:         $reply = &get_query_reply($queryid);
                   7532:         $tries ++;
                   7533:     }
                   7534:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7535:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7536:     } else {
                   7537:         my @responses = split(/:/,$reply);
                   7538:         my $outcome = shift(@responses); 
                   7539:         foreach my $item (@responses) {
                   7540:             my ($key,$value) = split(/=/,$item);
                   7541:             $$photo{$key} = $value;
                   7542:         }
                   7543:         return $outcome;
                   7544:     }
                   7545:     return 'error';
                   7546: }
                   7547: 
1.521     raeburn  7548: sub auto_instcode_format {
1.793     albertel 7549:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7550: 	$cat_order) = @_;
1.521     raeburn  7551:     my $courses = '';
1.772     raeburn  7552:     my @homeservers;
1.521     raeburn  7553:     if ($caller eq 'global') {
1.841     albertel 7554: 	my %servers = &get_servers($codedom,'library');
                   7555: 	foreach my $tryserver (keys(%servers)) {
                   7556: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7557: 		push(@homeservers,$tryserver);
                   7558: 	    }
1.584     raeburn  7559:         }
1.1022    raeburn  7560:     } elsif ($caller eq 'requests') {
                   7561:         if ($codedom =~ /^$match_domain$/) {
                   7562:             my $chome = &domain($codedom,'primary');
                   7563:             unless ($chome eq 'no_host') {
                   7564:                 push(@homeservers,$chome);
                   7565:             }
                   7566:         }
1.521     raeburn  7567:     } else {
1.772     raeburn  7568:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7569:     }
1.793     albertel 7570:     foreach my $code (keys(%{$instcodes})) {
                   7571:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7572:     }
                   7573:     chop($courses);
1.772     raeburn  7574:     my $ok_response = 0;
                   7575:     my $response;
                   7576:     while (@homeservers > 0 && $ok_response == 0) {
                   7577:         my $server = shift(@homeservers); 
                   7578:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7579:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7580:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7581: 		split(/:/,$response);
1.772     raeburn  7582:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7583:             push(@{$codetitles},&str2array($codetitles_str));
                   7584:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7585:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7586:             $ok_response = 1;
                   7587:         }
                   7588:     }
                   7589:     if ($ok_response) {
1.521     raeburn  7590:         return 'ok';
1.772     raeburn  7591:     } else {
                   7592:         return $response;
1.521     raeburn  7593:     }
                   7594: }
                   7595: 
1.792     raeburn  7596: sub auto_instcode_defaults {
                   7597:     my ($domain,$returnhash,$code_order) = @_;
                   7598:     my @homeservers;
1.841     albertel 7599: 
                   7600:     my %servers = &get_servers($domain,'library');
                   7601:     foreach my $tryserver (keys(%servers)) {
                   7602: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7603: 	    push(@homeservers,$tryserver);
                   7604: 	}
1.792     raeburn  7605:     }
1.841     albertel 7606: 
1.792     raeburn  7607:     my $response;
1.841     albertel 7608:     foreach my $server (@homeservers) {
1.792     raeburn  7609:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7610:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7611: 	
                   7612: 	foreach my $pair (split(/\&/,$response)) {
                   7613: 	    my ($name,$value)=split(/\=/,$pair);
                   7614: 	    if ($name eq 'code_order') {
                   7615: 		@{$code_order} = split(/\&/,&unescape($value));
                   7616: 	    } else {
                   7617: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7618: 	    }
                   7619: 	}
                   7620: 	return 'ok';
1.792     raeburn  7621:     }
1.841     albertel 7622: 
                   7623:     return $response;
1.1003    raeburn  7624: }
                   7625: 
                   7626: sub auto_possible_instcodes {
1.1007    raeburn  7627:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7628:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7629:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7630:         return;
                   7631:     }
1.1003    raeburn  7632:     my (@homeservers,$uhome);
                   7633:     if (defined(&domain($domain,'primary'))) {
                   7634:         $uhome=&domain($domain,'primary');
                   7635:         push(@homeservers,&domain($domain,'primary'));
                   7636:     } else {
                   7637:         my %servers = &get_servers($domain,'library');
                   7638:         foreach my $tryserver (keys(%servers)) {
                   7639:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7640:                 push(@homeservers,$tryserver);
                   7641:             }
                   7642:         }
                   7643:     }
                   7644:     my $response;
                   7645:     foreach my $server (@homeservers) {
                   7646:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7647:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7648:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7649:             split(':',$response);
                   7650:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7651:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7652:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7653:             my ($name,$value)=split('=',$item);
                   7654:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7655:         }
                   7656:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7657:             my ($name,$value)=split('=',$item);
                   7658:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7659:         }
                   7660:         return 'ok';
                   7661:     }
                   7662:     return $response;
                   7663: }
1.792     raeburn  7664: 
1.1010    raeburn  7665: sub auto_courserequest_checks {
                   7666:     my ($dom) = @_;
1.1020    raeburn  7667:     my ($homeserver,%validations);
                   7668:     if ($dom =~ /^$match_domain$/) {
                   7669:         $homeserver = &domain($dom,'primary');
                   7670:     }
                   7671:     unless ($homeserver eq 'no_host') {
                   7672:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7673:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7674:             my @items = split(/&/,$response);
                   7675:             foreach my $item (@items) {
                   7676:                 my ($key,$value) = split('=',$item);
                   7677:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7678:             }
                   7679:         }
                   7680:     }
1.1010    raeburn  7681:     return %validations; 
                   7682: }
                   7683: 
1.1020    raeburn  7684: sub auto_courserequest_validation {
                   7685:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7686:     my ($homeserver,$response);
                   7687:     if ($dom =~ /^$match_domain$/) {
                   7688:         $homeserver = &domain($dom,'primary');
                   7689:     }
                   7690:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7691:           
1.1020    raeburn  7692:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7693:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7694:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7695:                                     $homeserver));
                   7696:     }
                   7697:     return $response;
                   7698: }
                   7699: 
1.777     albertel 7700: sub auto_validate_class_sec {
1.918     raeburn  7701:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7702:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7703:     my $ownerlist;
                   7704:     if (ref($owners) eq 'ARRAY') {
                   7705:         $ownerlist = join(',',@{$owners});
                   7706:     } else {
                   7707:         $ownerlist = $owners;
                   7708:     }
1.773     raeburn  7709:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7710:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7711:     return $response;
                   7712: }
                   7713: 
1.679     raeburn  7714: # ------------------------------------------------------- Course Group routines
                   7715: 
                   7716: sub get_coursegroups {
1.809     raeburn  7717:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7718:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7719: }
                   7720: 
1.679     raeburn  7721: sub modify_coursegroup {
                   7722:     my ($cdom,$cnum,$groupsettings) = @_;
                   7723:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7724: }
                   7725: 
1.809     raeburn  7726: sub toggle_coursegroup_status {
                   7727:     my ($cdom,$cnum,$group,$action) = @_;
                   7728:     my ($from_namespace,$to_namespace);
                   7729:     if ($action eq 'delete') {
                   7730:         $from_namespace = 'coursegroups';
                   7731:         $to_namespace = 'deleted_groups';
                   7732:     } else {
                   7733:         $from_namespace = 'deleted_groups';
                   7734:         $to_namespace = 'coursegroups';
                   7735:     }
                   7736:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7737:     if (my $tmp = &error(%curr_group)) {
                   7738:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7739:         return ('read error',$tmp);
                   7740:     } else {
                   7741:         my %savedsettings = %curr_group; 
1.809     raeburn  7742:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7743:         my $deloutcome;
                   7744:         if ($result eq 'ok') {
1.809     raeburn  7745:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7746:         } else {
                   7747:             return ('write error',$result);
                   7748:         }
                   7749:         if ($deloutcome eq 'ok') {
                   7750:             return 'ok';
                   7751:         } else {
                   7752:             return ('delete error',$deloutcome);
                   7753:         }
                   7754:     }
                   7755: }
                   7756: 
1.679     raeburn  7757: sub modify_group_roles {
1.957     raeburn  7758:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7759:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7760:     my $role = 'gr/'.&escape($userprivs);
                   7761:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7762:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7763:     if ($result eq 'ok') {
                   7764:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7765:     }
1.679     raeburn  7766:     return $result;
                   7767: }
                   7768: 
                   7769: sub modify_coursegroup_membership {
                   7770:     my ($cdom,$cnum,$membership) = @_;
                   7771:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7772:     return $result;
                   7773: }
                   7774: 
1.682     raeburn  7775: sub get_active_groups {
                   7776:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7777:     my $now = time;
                   7778:     my %groups = ();
                   7779:     foreach my $key (keys(%env)) {
1.811     albertel 7780:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7781:             my ($start,$end) = split(/\./,$env{$key});
                   7782:             if (($end!=0) && ($end<$now)) { next; }
                   7783:             if (($start!=0) && ($start>$now)) { next; }
                   7784:             if ($1 eq $cdom && $2 eq $cnum) {
                   7785:                 $groups{$3} = $env{$key} ;
                   7786:             }
                   7787:         }
                   7788:     }
                   7789:     return %groups;
                   7790: }
                   7791: 
1.683     raeburn  7792: sub get_group_membership {
                   7793:     my ($cdom,$cnum,$group) = @_;
                   7794:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7795: }
                   7796: 
                   7797: sub get_users_groups {
                   7798:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7799:     my @usersgroups;
1.683     raeburn  7800:     my $cachetime=1800;
                   7801: 
                   7802:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7803:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7804:     if (defined($cached)) {
1.734     albertel 7805:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7806:     } else {  
                   7807:         $grouplist = '';
1.816     raeburn  7808:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7809:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7810:         my $access_end = $env{'course.'.$courseid.
                   7811:                               '.default_enrollment_end_date'};
                   7812:         my $now = time;
                   7813:         foreach my $key (keys(%roleshash)) {
                   7814:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7815:                 my $group = $1;
                   7816:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7817:                     my $start = $2;
                   7818:                     my $end = $1;
                   7819:                     if ($start == -1) { next; } # deleted from group
                   7820:                     if (($start!=0) && ($start>$now)) { next; }
                   7821:                     if (($end!=0) && ($end<$now)) {
                   7822:                         if ($access_end && $access_end < $now) {
                   7823:                             if ($access_end - $end < 86400) {
                   7824:                                 push(@usersgroups,$group);
1.733     raeburn  7825:                             }
                   7826:                         }
1.817     raeburn  7827:                         next;
1.733     raeburn  7828:                     }
1.817     raeburn  7829:                     push(@usersgroups,$group);
1.683     raeburn  7830:                 }
                   7831:             }
                   7832:         }
1.817     raeburn  7833:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7834:         $grouplist = join(':',@usersgroups);
                   7835:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7836:     }
1.733     raeburn  7837:     return @usersgroups;
1.683     raeburn  7838: }
                   7839: 
                   7840: sub devalidate_getgroups_cache {
                   7841:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7842:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7843: 
1.683     raeburn  7844:     my $hashid="$udom:$uname:$courseid";
                   7845:     &devalidate_cache_new('getgroups',$hashid);
                   7846: }
                   7847: 
1.12      www      7848: # ------------------------------------------------------------------ Plain Text
                   7849: 
                   7850: sub plaintext {
1.988     raeburn  7851:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7852:     if ($short =~ m{^cr/}) {
1.758     albertel 7853: 	return (split('/',$short))[-1];
                   7854:     }
1.742     raeburn  7855:     if (!defined($cid)) {
                   7856:         $cid = $env{'request.course.id'};
                   7857:     }
                   7858:     my %rolenames = (
1.1008    raeburn  7859:                       Course    => 'std',
                   7860:                       Community => 'alt1',
1.742     raeburn  7861:                     );
1.1037    raeburn  7862:     if ($cid ne '') {
                   7863:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7864:             unless ($forcedefault) {
                   7865:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7866:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7867:                 return &Apache::lonlocal::mt($roletext);
                   7868:             }
                   7869:         }
                   7870:     }
                   7871:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7872:         (defined($rolenames{$type})) && 
                   7873:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7874:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7875:     } elsif ($cid ne '') {
                   7876:         my $crstype = $env{'course.'.$cid.'.type'};
                   7877:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7878:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7879:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7880:         }
1.742     raeburn  7881:     }
1.1037    raeburn  7882:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7883: }
                   7884: 
                   7885: # ----------------------------------------------------------------- Assign Role
                   7886: 
                   7887: sub assignrole {
1.957     raeburn  7888:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7889:         $context)=@_;
1.21      www      7890:     my $mrole;
                   7891:     if ($role =~ /^cr\//) {
1.393     www      7892:         my $cwosec=$url;
1.811     albertel 7893:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7894: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7895:            my $refused = 1;
                   7896:            if ($context eq 'requestcourses') {
                   7897:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7898:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7899:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7900:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7901:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7902:                            if ($crsenv{'internal.courseowner'} eq
                   7903:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7904:                                $refused = '';
                   7905:                            }
                   7906:                        }
                   7907:                    }
                   7908:                }
                   7909:            }
                   7910:            if ($refused) {
                   7911:                &logthis('Refused custom assignrole: '.
                   7912:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7913:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7914:                return 'refused';
                   7915:            }
1.104     www      7916:         }
1.21      www      7917:         $mrole='cr';
1.678     raeburn  7918:     } elsif ($role =~ /^gr\//) {
                   7919:         my $cwogrp=$url;
1.811     albertel 7920:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7921:         unless (&allowed('mdg',$cwogrp)) {
                   7922:             &logthis('Refused group assignrole: '.
                   7923:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7924:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7925:             return 'refused';
                   7926:         }
                   7927:         $mrole='gr';
1.21      www      7928:     } else {
1.82      www      7929:         my $cwosec=$url;
1.811     albertel 7930:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7931:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7932:             my $refused;
                   7933:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7934:                 if (!(&allowed('c'.$role,$url))) {
                   7935:                     $refused = 1;
                   7936:                 }
                   7937:             } else {
                   7938:                 $refused = 1;
                   7939:             }
1.947     raeburn  7940:             if ($refused) {
1.1045    raeburn  7941:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7942:                 if (!$selfenroll && $context eq 'course') {
                   7943:                     my %crsenv;
                   7944:                     if ($role eq 'cc' || $role eq 'co') {
                   7945:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7946:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7947:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7948:                                 if ($crsenv{'internal.courseowner'} eq 
                   7949:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7950:                                     $refused = '';
                   7951:                                 }
                   7952:                             }
                   7953:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7954:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7955:                                 if ($crsenv{'internal.courseowner'} eq 
                   7956:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7957:                                     $refused = '';
                   7958:                                 }
                   7959:                             }
                   7960:                         }
                   7961:                     }
                   7962:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7963:                     $refused = '';
1.1017    raeburn  7964:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7965:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7966:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7967:                         my $wrongcc;
                   7968:                         if ($cnum =~ /^$match_community$/) {
                   7969:                             $wrongcc = 1 if ($role eq 'cc');
                   7970:                         } else {
                   7971:                             $wrongcc = 1 if ($role eq 'co');
                   7972:                         }
                   7973:                         unless ($wrongcc) {
                   7974:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7975:                             if ($crsenv{'internal.courseowner'} eq 
                   7976:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7977:                                 $refused = '';
                   7978:                             }
1.1017    raeburn  7979:                         }
                   7980:                     }
1.1183    raeburn  7981:                 } elsif ($context eq 'requestauthor') {
                   7982:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   7983:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7984:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7985:                             $refused = '';
                   7986:                         } else {
                   7987:                             my %domdefaults = &get_domain_defaults($udom);
                   7988:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7989:                                 my $checkbystatus;
                   7990:                                 if ($env{'user.adv'}) { 
                   7991:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7992:                                     if ($disposition eq 'automatic') {
                   7993:                                         $refused = '';
                   7994:                                     } elsif ($disposition eq '') {
                   7995:                                         $checkbystatus = 1;
                   7996:                                     } 
                   7997:                                 } else {
                   7998:                                     $checkbystatus = 1;
                   7999:                                 }
                   8000:                                 if ($checkbystatus) {
                   8001:                                     if ($env{'environment.inststatus'}) {
                   8002:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8003:                                         foreach my $type (@inststatuses) {
                   8004:                                             if (($type ne '') &&
                   8005:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8006:                                                 $refused = '';
                   8007:                                             }
                   8008:                                         }
                   8009:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8010:                                         $refused = '';
                   8011:                                     }
                   8012:                                 }
                   8013:                             }
                   8014:                         }
                   8015:                     }
1.1017    raeburn  8016:                 }
                   8017:                 if ($refused) {
1.947     raeburn  8018:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8019:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8020: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8021:                     return 'refused';
                   8022:                 }
1.932     raeburn  8023:             }
1.1131    raeburn  8024:         } elsif ($role eq 'au') {
                   8025:             if ($url ne '/'.$udom.'/') {
                   8026:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8027:                          ' to assign author role for '.$uname.':'.$udom.
                   8028:                          ' in domain: '.$url.' refused (wrong domain).');
                   8029:                 return 'refused';
                   8030:             }
1.104     www      8031:         }
1.21      www      8032:         $mrole=$role;
                   8033:     }
1.620     albertel 8034:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8035:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8036:     if ($end) { $command.='_'.$end; }
1.21      www      8037:     if ($start) {
                   8038: 	if ($end) { 
1.81      www      8039:            $command.='_'.$start; 
1.21      www      8040:         } else {
1.81      www      8041:            $command.='_0_'.$start;
1.21      www      8042:         }
                   8043:     }
1.739     raeburn  8044:     my $origstart = $start;
                   8045:     my $origend = $end;
1.957     raeburn  8046:     my $delflag;
1.357     www      8047: # actually delete
                   8048:     if ($deleteflag) {
1.373     www      8049: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8050: # modify command to delete the role
1.620     albertel 8051:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8052:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8053: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8054: # set start and finish to negative values for userrolelog
                   8055:            $start=-1;
                   8056:            $end=-1;
1.957     raeburn  8057:            $delflag = 1;
1.357     www      8058:         }
                   8059:     }
                   8060: # send command
1.349     www      8061:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8062: # log new user role if status is ok
1.349     www      8063:     if ($answer eq 'ok') {
1.663     raeburn  8064: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8065:         if (($role eq 'cc') || ($role eq 'in') ||
                   8066:             ($role eq 'ep') || ($role eq 'ad') ||
                   8067:             ($role eq 'ta') || ($role eq 'st') ||
                   8068:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8069:             ($role eq 'co')) {
1.1200    raeburn  8070: # for course roles, perform group memberships changes triggered by role change.
                   8071:             unless ($role =~ /^gr/) {
                   8072:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8073:                                                  $origstart,$selfenroll,$context);
                   8074:             }
1.1184    raeburn  8075:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8076:                            $selfenroll,$context);
                   8077:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8078:                  ($role eq 'au') || ($role eq 'dc')) {
                   8079:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8080:                            $context);
                   8081:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8082:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8083:                              $context); 
                   8084:         }
1.1053    raeburn  8085:         if ($role eq 'cc') {
                   8086:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8087:         }
1.349     www      8088:     }
                   8089:     return $answer;
1.169     harris41 8090: }
                   8091: 
1.1053    raeburn  8092: sub autoupdate_coowners {
                   8093:     my ($url,$end,$start,$uname,$udom) = @_;
                   8094:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8095:     if (($cdom ne '') && ($cnum ne '')) {
                   8096:         my $now = time;
                   8097:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8098:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8099:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8100:             my $instcode = $coursehash{'internal.coursecode'};
                   8101:             if ($instcode ne '') {
1.1056    raeburn  8102:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8103:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8104:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8105:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8106:                         if ($result eq 'valid') {
                   8107:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8108:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8109:                                     push(@newcoowners,$coowner);
                   8110:                                 }
                   8111:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8112:                                     push(@newcoowners,$uname.':'.$udom);
                   8113:                                 }
                   8114:                                 @newcoowners = sort(@newcoowners);
                   8115:                             } else {
                   8116:                                 push(@newcoowners,$uname.':'.$udom);
                   8117:                             }
                   8118:                         } else {
                   8119:                             if ($coursehash{'internal.co-owners'}) {
                   8120:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8121:                                     unless ($coowner eq $uname.':'.$udom) {
                   8122:                                         push(@newcoowners,$coowner);
                   8123:                                     }
                   8124:                                 }
                   8125:                                 unless (@newcoowners > 0) {
                   8126:                                     $delcoowners = 1;
                   8127:                                     $coowners = '';
                   8128:                                 }
                   8129:                             }
                   8130:                         }
                   8131:                         if (@newcoowners || $delcoowners) {
                   8132:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8133:                                             $delcoowners,@newcoowners);
                   8134:                         }
                   8135:                     }
                   8136:                 }
                   8137:             }
                   8138:         }
                   8139:     }
                   8140: }
                   8141: 
                   8142: sub store_coowners {
                   8143:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8144:     my $cid = $cdom.'_'.$cnum;
                   8145:     my ($coowners,$delresult,$putresult);
                   8146:     if (@newcoowners) {
                   8147:         $coowners = join(',',@newcoowners);
                   8148:         my %coownershash = (
                   8149:                             'internal.co-owners' => $coowners,
                   8150:                            );
                   8151:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8152:         if ($putresult eq 'ok') {
                   8153:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8154:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8155:             }
                   8156:         }
                   8157:     }
                   8158:     if ($delcoowners) {
                   8159:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8160:         if ($delresult eq 'ok') {
                   8161:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8162:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8163:             }
                   8164:         }
                   8165:     }
                   8166:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8167:         my %crsinfo =
                   8168:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8169:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8170:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8171:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8172:         }
                   8173:     }
                   8174: }
                   8175: 
1.169     harris41 8176: # -------------------------------------------------- Modify user authentication
1.197     www      8177: # Overrides without validation
                   8178: 
1.169     harris41 8179: sub modifyuserauth {
                   8180:     my ($udom,$uname,$umode,$upass)=@_;
                   8181:     my $uhome=&homeserver($uname,$udom);
1.197     www      8182:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8183:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8184:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8185:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8186:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8187: 		     &escape($upass),$uhome);
1.620     albertel 8188:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8189:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8190:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8191:     &log($udom,,$uname,$uhome,
1.620     albertel 8192:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8193:                                      $env{'user.name'}.', '.$umode.
1.197     www      8194:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8195:     unless ($reply eq 'ok') {
1.197     www      8196:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8197: 	return 'error: '.$reply;
                   8198:     }   
1.170     harris41 8199:     return 'ok';
1.80      www      8200: }
                   8201: 
1.81      www      8202: # --------------------------------------------------------------- Modify a user
1.80      www      8203: 
1.81      www      8204: sub modifyuser {
1.206     matthew  8205:     my ($udom,    $uname, $uid,
                   8206:         $umode,   $upass, $first,
                   8207:         $middle,  $last,  $gene,
1.1058    raeburn  8208:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8209:     $udom= &LONCAPA::clean_domain($udom);
                   8210:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8211:     my $showcandelete = 'none';
                   8212:     if (ref($candelete) eq 'ARRAY') {
                   8213:         if (@{$candelete} > 0) {
                   8214:             $showcandelete = join(', ',@{$candelete});
                   8215:         }
                   8216:     }
1.81      www      8217:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8218:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8219: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8220:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8221:                                      ' desiredhome not specified'). 
1.620     albertel 8222:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8223:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8224:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8225:     my $newuser;
                   8226:     if ($uhome eq 'no_host') {
                   8227:         $newuser = 1;
                   8228:     }
1.80      www      8229: # ----------------------------------------------------------------- Create User
1.406     albertel 8230:     if (($uhome eq 'no_host') && 
                   8231: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8232:         my $unhome='';
1.844     albertel 8233:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8234:             $unhome = $desiredhome;
1.620     albertel 8235: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8236: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8237:         } else { # load balancing routine for determining $unhome
1.81      www      8238:             my $loadm=10000000;
1.841     albertel 8239: 	    my %servers = &get_servers($udom,'library');
                   8240: 	    foreach my $tryserver (keys(%servers)) {
                   8241: 		my $answer=reply('load',$tryserver);
                   8242: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8243: 		    $loadm=$answer;
                   8244: 		    $unhome=$tryserver;
                   8245: 		}
1.80      www      8246: 	    }
                   8247:         }
                   8248:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8249: 	    return 'error: unable to find a home server for '.$uname.
                   8250:                    ' in domain '.$udom;
1.80      www      8251:         }
                   8252:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8253:                          &escape($upass),$unhome);
                   8254: 	unless ($reply eq 'ok') {
                   8255:             return 'error: '.$reply;
                   8256:         }   
1.230     stredwic 8257:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8258:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8259: 	    return 'error: unable verify users home machine.';
1.80      www      8260:         }
1.209     matthew  8261:     }   # End of creation of new user
1.80      www      8262: # ---------------------------------------------------------------------- Add ID
                   8263:     if ($uid) {
                   8264:        $uid=~tr/A-Z/a-z/;
                   8265:        my %uidhash=&idrget($udom,$uname);
1.196     www      8266:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8267:          && (!$forceid)) {
1.80      www      8268: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8269: 	      return 'error: user id "'.$uid.'" does not match '.
                   8270:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8271:           }
                   8272:        } else {
                   8273: 	  &idput($udom,($uname => $uid));
                   8274:        }
                   8275:     }
                   8276: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8277:     my @tmp=&get('environment',
1.899     raeburn  8278: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8279:                     'permanentemail','inststatus'],
1.134     albertel 8280: 		   $udom,$uname);
1.1075    raeburn  8281:     my (%names,%oldnames);
1.313     matthew  8282:     if ($tmp[0] =~ m/^error:.*/) { 
                   8283:         %names=(); 
                   8284:     } else {
                   8285:         %names = @tmp;
1.1075    raeburn  8286:         %oldnames = %names;
1.313     matthew  8287:     }
1.388     www      8288: #
1.1058    raeburn  8289: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8290: # of users did not contain them), do not overwrite existing values
                   8291: # unless field is in $candelete array ref.  
                   8292: #
                   8293: 
                   8294:     my @fields = ('firstname','middlename','lastname','generation',
                   8295:                   'permanentemail','id');
                   8296:     my %newvalues;
                   8297:     if (ref($candelete) eq 'ARRAY') {
                   8298:         foreach my $field (@fields) {
                   8299:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8300:                 if ($field eq 'firstname') {
                   8301:                     $names{$field} = $first;
                   8302:                 } elsif ($field eq 'middlename') {
                   8303:                     $names{$field} = $middle;
                   8304:                 } elsif ($field eq 'lastname') {
                   8305:                     $names{$field} = $last;
                   8306:                 } elsif ($field eq 'generation') { 
                   8307:                     $names{$field} = $gene;
                   8308:                 } elsif ($field eq 'permanentemail') {
                   8309:                     $names{$field} = $email;
                   8310:                 } elsif ($field eq 'id') {
                   8311:                     $names{$field}  = $uid;
                   8312:                 }
                   8313:             }
                   8314:         }
                   8315:     }
1.388     www      8316:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8317:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8318:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8319:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8320:     if ($email) {
                   8321:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8322:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8323:     }
1.899     raeburn  8324:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8325:     if (defined($inststatus)) {
                   8326:         $names{'inststatus'} = '';
                   8327:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8328:         if (ref($usertypes) eq 'HASH') {
                   8329:             my @okstatuses; 
                   8330:             foreach my $item (split(/:/,$inststatus)) {
                   8331:                 if (defined($usertypes->{$item})) {
                   8332:                     push(@okstatuses,$item);  
                   8333:                 }
                   8334:             }
                   8335:             if (@okstatuses) {
                   8336:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8337:             }
                   8338:         }
                   8339:     }
1.1075    raeburn  8340:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8341:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8342:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8343:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8344:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8345:     } else {
                   8346:         $logmsg .= ' during self creation';
                   8347:     }
1.1075    raeburn  8348:     my $changed;
                   8349:     if ($newuser) {
                   8350:         $changed = 1;
                   8351:     } else {
                   8352:         foreach my $field (@fields) {
                   8353:             if ($names{$field} ne $oldnames{$field}) {
                   8354:                 $changed = 1;
                   8355:                 last;
                   8356:             }
                   8357:         }
                   8358:     }
                   8359:     unless ($changed) {
                   8360:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8361:         &logthis($logmsg);
                   8362:         return 'ok';
                   8363:     }
                   8364:     my $reply = &put('environment', \%names, $udom,$uname);
                   8365:     if ($reply ne 'ok') { 
                   8366:         return 'error: '.$reply;
                   8367:     }
1.1087    raeburn  8368:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8369:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8370:     }
1.1075    raeburn  8371:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8372:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8373:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8374:     &logthis($logmsg);
1.134     albertel 8375:     return 'ok';
1.80      www      8376: }
                   8377: 
1.81      www      8378: # -------------------------------------------------------------- Modify student
1.80      www      8379: 
1.81      www      8380: sub modifystudent {
                   8381:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8382:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  8383:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 8384:     if (!$cid) {
1.620     albertel 8385: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8386: 	    return 'not_in_class';
                   8387: 	}
1.80      www      8388:     }
                   8389: # --------------------------------------------------------------- Make the user
1.81      www      8390:     my $reply=&modifyuser
1.209     matthew  8391: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8392:          $desiredhome,$email,$inststatus);
1.80      www      8393:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8394:     # This will cause &modify_student_enrollment to get the uid from the
                   8395:     # students environment
                   8396:     $uid = undef if (!$forceid);
1.455     albertel 8397:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  8398: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  8399:     return $reply;
                   8400: }
                   8401: 
                   8402: sub modify_student_enrollment {
1.957     raeburn  8403:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 8404:     my ($cdom,$cnum,$chome);
                   8405:     if (!$cid) {
1.620     albertel 8406: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8407: 	    return 'not_in_class';
                   8408: 	}
1.620     albertel 8409: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8410: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8411:     } else {
                   8412: 	($cdom,$cnum)=split(/_/,$cid);
                   8413:     }
1.620     albertel 8414:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8415:     if (!$chome) {
1.457     raeburn  8416: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8417:     }
1.455     albertel 8418:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8419:     # Make sure the user exists
1.81      www      8420:     my $uhome=&homeserver($uname,$udom);
                   8421:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8422: 	return 'error: no such user';
                   8423:     }
1.297     matthew  8424:     # Get student data if we were not given enough information
                   8425:     if (!defined($first)  || $first  eq '' || 
                   8426:         !defined($last)   || $last   eq '' || 
                   8427:         !defined($uid)    || $uid    eq '' || 
                   8428:         !defined($middle) || $middle eq '' || 
                   8429:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8430:         # They did not supply us with enough data to enroll the student, so
                   8431:         # we need to pick up more information.
1.297     matthew  8432:         my %tmp = &get('environment',
1.294     matthew  8433:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8434:                        ,$udom,$uname);
                   8435: 
1.800     albertel 8436:         #foreach my $key (keys(%tmp)) {
                   8437:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8438:         #}
1.294     matthew  8439:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8440:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8441:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8442:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8443:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8444:     }
1.556     albertel 8445:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8446:     my $user = "$uname:$udom";
                   8447:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8448:     my $reply=cput('classlist',
1.1148    raeburn  8449: 		   {$user => 
1.515     raeburn  8450: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 8451: 		   $cdom,$cnum);
1.1148    raeburn  8452:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8453:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8454:     } else { 
1.81      www      8455: 	return 'error: '.$reply;
                   8456:     }
1.297     matthew  8457:     # Add student role to user
1.83      www      8458:     my $uurl='/'.$cid;
1.81      www      8459:     $uurl=~s/\_/\//g;
                   8460:     if ($usec) {
                   8461: 	$uurl.='/'.$usec;
                   8462:     }
1.1148    raeburn  8463:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8464:                              $selfenroll,$context);
                   8465:     if ($result ne 'ok') {
                   8466:         if ($old_entry{$user} ne '') {
                   8467:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8468:         } else {
                   8469:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8470:         }
                   8471:     }
                   8472:     return $result; 
1.21      www      8473: }
                   8474: 
1.556     albertel 8475: sub format_name {
                   8476:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8477:     my $name;
                   8478:     if ($first ne 'lastname') {
                   8479: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8480:     } else {
                   8481: 	if ($lastname=~/\S/) {
                   8482: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8483: 	    $name=~s/\s+,/,/;
                   8484: 	} else {
                   8485: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8486: 	}
                   8487:     }
                   8488:     $name=~s/^\s+//;
                   8489:     $name=~s/\s+$//;
                   8490:     $name=~s/\s+/ /g;
                   8491:     return $name;
                   8492: }
                   8493: 
1.84      www      8494: # ------------------------------------------------- Write to course preferences
                   8495: 
                   8496: sub writecoursepref {
                   8497:     my ($courseid,%prefs)=@_;
                   8498:     $courseid=~s/^\///;
                   8499:     $courseid=~s/\_/\//g;
                   8500:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8501:     my $chome=homeserver($cnum,$cdomain);
                   8502:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8503: 	return 'error: no such course';
                   8504:     }
                   8505:     my $cstring='';
1.800     albertel 8506:     foreach my $pref (keys(%prefs)) {
                   8507: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8508:     }
1.84      www      8509:     $cstring=~s/\&$//;
                   8510:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8511: }
                   8512: 
                   8513: # ---------------------------------------------------------- Make/modify course
                   8514: 
                   8515: sub createcourse {
1.741     raeburn  8516:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8517:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8518:     $url=&declutter($url);
                   8519:     my $cid='';
1.1028    raeburn  8520:     if ($context eq 'requestcourses') {
                   8521:         my $can_create = 0;
                   8522:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8523:         if ($udom eq $ownerdom) {
                   8524:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8525:                                   $context)) {
                   8526:                 $can_create = 1;
                   8527:             }
                   8528:         } else {
                   8529:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8530:                                            $category);
                   8531:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8532:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8533:                 if (@curr > 0) {
                   8534:                     my @options = qw(approval validate autolimit);
                   8535:                     my $optregex = join('|',@options);
                   8536:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8537:                         $can_create = 1;
                   8538:                     }
                   8539:                 }
                   8540:             }
                   8541:         }
                   8542:         if ($can_create) {
                   8543:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8544:                 unless (&allowed('ccc',$udom)) {
                   8545:                     return 'refused'; 
                   8546:                 }
1.1017    raeburn  8547:             }
                   8548:         } else {
                   8549:             return 'refused';
                   8550:         }
1.1028    raeburn  8551:     } elsif (!&allowed('ccc',$udom)) {
                   8552:         return 'refused';
1.84      www      8553:     }
1.1011    raeburn  8554: # --------------------------------------------------------------- Get Unique ID
                   8555:     my $uname;
                   8556:     if ($cnum =~ /^$match_courseid$/) {
                   8557:         my $chome=&homeserver($cnum,$udom,'true');
                   8558:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8559:             $uname = $cnum;
                   8560:         } else {
1.1038    raeburn  8561:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8562:         }
                   8563:     } else {
1.1038    raeburn  8564:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8565:     }
                   8566:     return $uname if ($uname =~ /^error/);
                   8567: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8568:     if (!defined($course_server)) {
                   8569:         if (defined(&domain($udom,'primary'))) {
                   8570:             $course_server = &domain($udom,'primary');
                   8571:         } else {
                   8572:             $course_server = $env{'user.home'}; 
                   8573:         }
                   8574:     }
                   8575:     my %host_servers =
                   8576:         &Apache::lonnet::get_servers($udom,'library');
                   8577:     unless ($host_servers{$course_server}) {
                   8578:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8579:     }
1.84      www      8580: # ------------------------------------------------------------- Make the course
                   8581:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8582:                       $course_server);
1.84      www      8583:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8584:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8585:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8586: 	return 'error: no such course';
                   8587:     }
1.271     www      8588: # ----------------------------------------------------------------- Course made
1.516     raeburn  8589: # log existence
1.1029    raeburn  8590:     my $now = time;
1.918     raeburn  8591:     my $newcourse = {
                   8592:                     $udom.'_'.$uname => {
1.921     raeburn  8593:                                      description => $description,
                   8594:                                      inst_code   => $inst_code,
                   8595:                                      owner       => $course_owner,
                   8596:                                      type        => $crstype,
1.1029    raeburn  8597:                                      creator     => $env{'user.name'}.':'.
                   8598:                                                     $env{'user.domain'},
                   8599:                                      created     => $now,
                   8600:                                      context     => $context,
1.918     raeburn  8601:                                                 },
                   8602:                     };
1.921     raeburn  8603:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8604: # set toplevel url
1.271     www      8605:     my $topurl=$url;
                   8606:     unless ($nonstandard) {
                   8607: # ------------------------------------------ For standard courses, make top url
                   8608:         my $mapurl=&clutter($url);
1.278     www      8609:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8610:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8611: <map>
                   8612: <resource id="1" type="start"></resource>
                   8613: <resource id="2" src="$mapurl"></resource>
                   8614: <resource id="3" type="finish"></resource>
                   8615: <link index="1" from="1" to="2"></link>
                   8616: <link index="2" from="2" to="3"></link>
                   8617: </map>
                   8618: ENDINITMAP
                   8619:         $topurl=&declutter(
1.638     albertel 8620:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8621:                           );
                   8622:     }
                   8623: # ----------------------------------------------------------- Write preferences
1.84      www      8624:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8625:                      ('description'              => $description,
                   8626:                       'url'                      => $topurl,
                   8627:                       'internal.creator'         => $env{'user.name'}.':'.
                   8628:                                                     $env{'user.domain'},
                   8629:                       'internal.created'         => $now,
                   8630:                       'internal.creationcontext' => $context)
                   8631:                     );
1.84      www      8632:     return '/'.$udom.'/'.$uname;
                   8633: }
                   8634: 
1.1011    raeburn  8635: # ------------------------------------------------------------------- Create ID
                   8636: sub generate_coursenum {
1.1038    raeburn  8637:     my ($udom,$crstype) = @_;
1.1011    raeburn  8638:     my $domdesc = &domain($udom);
                   8639:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8640:     my $first;
                   8641:     if ($crstype eq 'Community') {
                   8642:         $first = '0';
                   8643:     } else {
                   8644:         $first = int(1+rand(9)); 
                   8645:     } 
                   8646:     my $uname=$first.
1.1011    raeburn  8647:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8648:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8649:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8650: # ----------------------------------------------- Make sure that does not exist
                   8651:     my $uhome=&homeserver($uname,$udom,'true');
                   8652:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8653:         if ($crstype eq 'Community') {
                   8654:             $first = '0';
                   8655:         } else {
                   8656:             $first = int(1+rand(9));
                   8657:         }
                   8658:         $uname=$first.
1.1011    raeburn  8659:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8660:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8661:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8662:         $uhome=&homeserver($uname,$udom,'true');
                   8663:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8664:             return 'error: unable to generate unique course-ID';
                   8665:         }
                   8666:     }
                   8667:     return $uname;
                   8668: }
                   8669: 
1.813     albertel 8670: sub is_course {
1.1167    droeschl 8671:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8672:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8673: 
                   8674:     return unless $cdom and $cnum;
                   8675: 
                   8676:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8677:         '.');
                   8678: 
                   8679:     return unless exists($courses{$cdom.'_'.$cnum});
                   8680:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8681: }
                   8682: 
1.1015    raeburn  8683: sub store_userdata {
                   8684:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8685:     my $result;
1.1016    raeburn  8686:     if ($datakey ne '') {
1.1013    raeburn  8687:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8688:             if ($udom eq '' || $uname eq '') {
                   8689:                 $udom = $env{'user.domain'};
                   8690:                 $uname = $env{'user.name'};
                   8691:             }
                   8692:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8693:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8694:                 $result = 'error: no_host';
                   8695:             } else {
                   8696:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8697:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8698: 
                   8699:                 my $namevalue='';
                   8700:                 foreach my $key (keys(%{$storehash})) {
                   8701:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8702:                 }
                   8703:                 $namevalue=~s/\&$//;
1.1105    raeburn  8704:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8705:                                   $namevalue,$uhome);
1.1013    raeburn  8706:             }
                   8707:         } else {
                   8708:             $result = 'error: data to store was not a hash reference'; 
                   8709:         }
                   8710:     } else {
                   8711:         $result= 'error: invalid requestkey'; 
                   8712:     }
                   8713:     return $result;
                   8714: }
                   8715: 
1.21      www      8716: # ---------------------------------------------------------- Assign Custom Role
                   8717: 
                   8718: sub assigncustomrole {
1.957     raeburn  8719:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8720:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8721:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8722: }
                   8723: 
                   8724: # ----------------------------------------------------------------- Revoke Role
                   8725: 
                   8726: sub revokerole {
1.957     raeburn  8727:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8728:     my $now=time;
1.965     raeburn  8729:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8730: }
                   8731: 
                   8732: # ---------------------------------------------------------- Revoke Custom Role
                   8733: 
                   8734: sub revokecustomrole {
1.957     raeburn  8735:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8736:     my $now=time;
1.357     www      8737:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8738:            $deleteflag,$selfenroll,$context);
1.17      www      8739: }
                   8740: 
1.533     banghart 8741: # ------------------------------------------------------------ Disk usage
1.535     albertel 8742: sub diskusage {
1.955     raeburn  8743:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8744:     $directorypath =~ s/\/$//;
                   8745:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8746:                        .&escape($getpropath).':'.&escape($uname).':'
                   8747:                        .&escape($udom),homeserver($uname,$udom));
                   8748:     if ($listing eq 'unknown_cmd') {
                   8749:         if ($getpropath) {
                   8750:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8751:         }
                   8752:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8753:     }
1.514     albertel 8754:     return $listing;
1.512     banghart 8755: }
                   8756: 
1.566     banghart 8757: sub is_locked {
1.1096    raeburn  8758:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8759:     my @check;
                   8760:     my $is_locked;
1.1093    raeburn  8761:     push (@check,$file_name);
1.613     albertel 8762:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8763: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8764:     my ($tmp)=keys(%locked);
                   8765:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8766:     
1.566     banghart 8767:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8768:         $is_locked = 'false';
                   8769:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8770:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8771:                $is_locked = 'true';
1.1096    raeburn  8772:                if (ref($which) eq 'ARRAY') {
                   8773:                    push(@{$which},$entry);
                   8774:                } else {
                   8775:                    last;
                   8776:                }
1.745     raeburn  8777:            }
                   8778:        }
1.566     banghart 8779:     } else {
                   8780:         $is_locked = 'false';
                   8781:     }
1.1093    raeburn  8782:     return $is_locked;
1.566     banghart 8783: }
                   8784: 
1.759     albertel 8785: sub declutter_portfile {
                   8786:     my ($file) = @_;
1.833     albertel 8787:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8788:     return $file;
                   8789: }
                   8790: 
1.559     banghart 8791: # ------------------------------------------------------------- Mark as Read Only
                   8792: 
                   8793: sub mark_as_readonly {
                   8794:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8795:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8796:     my ($tmp)=keys(%current_permissions);
                   8797:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8798:     foreach my $file (@{$files}) {
1.759     albertel 8799: 	$file = &declutter_portfile($file);
1.561     banghart 8800:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8801:     }
1.613     albertel 8802:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8803:     return;
                   8804: }
                   8805: 
1.572     banghart 8806: # ------------------------------------------------------------Save Selected Files
                   8807: 
                   8808: sub save_selected_files {
                   8809:     my ($user, $path, @files) = @_;
                   8810:     my $filename = $user."savedfiles";
1.573     banghart 8811:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8812:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8813:     foreach my $file (@files) {
1.620     albertel 8814:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8815:     }
                   8816:     foreach my $file (@other_files) {
1.574     banghart 8817:         print (OUT $file."\n");
1.572     banghart 8818:     }
1.574     banghart 8819:     close (OUT);
1.572     banghart 8820:     return 'ok';
                   8821: }
                   8822: 
1.574     banghart 8823: sub clear_selected_files {
                   8824:     my ($user) = @_;
                   8825:     my $filename = $user."savedfiles";
1.1117    foxr     8826:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8827:     print (OUT undef);
                   8828:     close (OUT);
                   8829:     return ("ok");    
                   8830: }
                   8831: 
1.572     banghart 8832: sub files_in_path {
                   8833:     my ($user, $path) = @_;
                   8834:     my $filename = $user."savedfiles";
                   8835:     my %return_files;
1.1117    foxr     8836:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8837:     while (my $line_in = <IN>) {
1.574     banghart 8838:         chomp ($line_in);
                   8839:         my @paths_and_file = split (m!/!, $line_in);
                   8840:         my $file_part = pop (@paths_and_file);
                   8841:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8842:         $path_part.='/';
                   8843:         my $path_and_file = $path_part.$file_part;
                   8844:         if ($path_part eq $path) {
                   8845:             $return_files{$file_part}= 'selected';
                   8846:         }
                   8847:     }
1.574     banghart 8848:     close (IN);
                   8849:     return (\%return_files);
1.572     banghart 8850: }
                   8851: 
                   8852: # called in portfolio select mode, to show files selected NOT in current directory
                   8853: sub files_not_in_path {
                   8854:     my ($user, $path) = @_;
                   8855:     my $filename = $user."savedfiles";
                   8856:     my @return_files;
                   8857:     my $path_part;
1.1117    foxr     8858:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8859:     while (my $line = <IN>) {
1.572     banghart 8860:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8861:         my @paths_and_file = split(m|/|, $line);
                   8862:         my $file_part = pop(@paths_and_file);
                   8863:         chomp($file_part);
                   8864:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8865:         $path_part .= '/';
                   8866:         my $path_and_file = $path_part.$file_part;
                   8867:         if ($path_part ne $path) {
1.800     albertel 8868:             push(@return_files, ($path_and_file));
1.572     banghart 8869:         }
                   8870:     }
1.800     albertel 8871:     close(OUT);
1.574     banghart 8872:     return (@return_files);
1.572     banghart 8873: }
                   8874: 
1.745     raeburn  8875: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8876: 
1.745     raeburn  8877: sub get_portfile_permissions {
                   8878:     my ($domain,$user) = @_;
1.613     albertel 8879:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8880:     my ($tmp)=keys(%current_permissions);
                   8881:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8882:     return \%current_permissions;
                   8883: }
                   8884: 
                   8885: #---------------------------------------------Get portfolio file access controls
                   8886: 
1.749     raeburn  8887: sub get_access_controls {
1.745     raeburn  8888:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8889:     my %access;
                   8890:     my $real_file = $file;
                   8891:     $file =~ s/\.meta$//;
1.745     raeburn  8892:     if (defined($file)) {
1.749     raeburn  8893:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8894:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8895:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8896:             }
                   8897:         }
1.745     raeburn  8898:     } else {
1.749     raeburn  8899:         foreach my $key (keys(%{$current_permissions})) {
                   8900:             if ($key =~ /\0accesscontrol$/) {
                   8901:                 if (defined($group)) {
                   8902:                     if ($key !~ m-^\Q$group\E/-) {
                   8903:                         next;
                   8904:                     }
                   8905:                 }
                   8906:                 my ($fullpath) = split(/\0/,$key);
                   8907:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8908:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8909:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8910:                     }
                   8911:                 }
                   8912:             }
                   8913:         }
                   8914:     }
                   8915:     return %access;
                   8916: }
                   8917: 
                   8918: sub modify_access_controls {
                   8919:     my ($file_name,$changes,$domain,$user)=@_;
                   8920:     my ($outcome,$deloutcome);
                   8921:     my %store_permissions;
                   8922:     my %new_values;
                   8923:     my %new_control;
                   8924:     my %translation;
                   8925:     my @deletions = ();
                   8926:     my $now = time;
                   8927:     if (exists($$changes{'activate'})) {
                   8928:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8929:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8930:             my $numnew = scalar(@newitems);
                   8931:             for (my $i=0; $i<$numnew; $i++) {
                   8932:                 my $newkey = $newitems[$i];
                   8933:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8934:                 if ($newkey =~ /^\d+:/) { 
                   8935:                     $newkey =~ s/^(\d+)/$newid/;
                   8936:                     $translation{$1} = $newid;
                   8937:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8938:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8939:                     $translation{$1} = $newid;
                   8940:                 }
1.749     raeburn  8941:                 $new_values{$file_name."\0".$newkey} = 
                   8942:                                           $$changes{'activate'}{$newitems[$i]};
                   8943:                 $new_control{$newkey} = $now;
                   8944:             }
                   8945:         }
                   8946:     }
                   8947:     my %todelete;
                   8948:     my %changed_items;
                   8949:     foreach my $action ('delete','update') {
                   8950:         if (exists($$changes{$action})) {
                   8951:             if (ref($$changes{$action}) eq 'HASH') {
                   8952:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8953:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8954:                     if ($action eq 'delete') { 
                   8955:                         $todelete{$itemnum} = 1;
                   8956:                     } else {
                   8957:                         $changed_items{$itemnum} = $key;
                   8958:                     }
                   8959:                 }
1.745     raeburn  8960:             }
                   8961:         }
1.749     raeburn  8962:     }
                   8963:     # get lock on access controls for file.
                   8964:     my $lockhash = {
                   8965:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8966:                                                        ':'.$env{'user.domain'},
                   8967:                    }; 
                   8968:     my $tries = 0;
                   8969:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8970:    
                   8971:     while (($gotlock ne 'ok') && $tries <3) {
                   8972:         $tries ++;
                   8973:         sleep 1;
                   8974:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8975:     }
                   8976:     if ($gotlock eq 'ok') {
                   8977:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8978:         my ($tmp)=keys(%curr_permissions);
                   8979:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8980:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8981:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8982:             if (ref($curr_controls) eq 'HASH') {
                   8983:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8984:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8985:                     if (defined($todelete{$itemnum})) {
                   8986:                         push(@deletions,$file_name."\0".$control_item);
                   8987:                     } else {
                   8988:                         if (defined($changed_items{$itemnum})) {
                   8989:                             $new_control{$changed_items{$itemnum}} = $now;
                   8990:                             push(@deletions,$file_name."\0".$control_item);
                   8991:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8992:                         } else {
                   8993:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8994:                         }
                   8995:                     }
1.745     raeburn  8996:                 }
                   8997:             }
                   8998:         }
1.970     raeburn  8999:         my ($group);
                   9000:         if (&is_course($domain,$user)) {
                   9001:             ($group,my $file) = split(/\//,$file_name,2);
                   9002:         }
1.749     raeburn  9003:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9004:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9005:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9006:         #  remove lock
                   9007:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9008:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9009:         my $sqlresult =
1.970     raeburn  9010:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9011:                                     $group);
1.749     raeburn  9012:     } else {
                   9013:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9014:     }
1.749     raeburn  9015:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9016: }
                   9017: 
1.827     raeburn  9018: sub make_public_indefinitely {
                   9019:     my ($requrl) = @_;
                   9020:     my $now = time;
                   9021:     my $action = 'activate';
                   9022:     my $aclnum = 0;
                   9023:     if (&is_portfolio_url($requrl)) {
                   9024:         my (undef,$udom,$unum,$file_name,$group) =
                   9025:             &parse_portfolio_url($requrl);
                   9026:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9027:         my %access_controls = &get_access_controls($current_perms,
                   9028:                                                    $group,$file_name);
                   9029:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9030:             my ($num,$scope,$end,$start) = 
                   9031:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9032:             if ($scope eq 'public') {
                   9033:                 if ($start <= $now && $end == 0) {
                   9034:                     $action = 'none';
                   9035:                 } else {
                   9036:                     $action = 'update';
                   9037:                     $aclnum = $num;
                   9038:                 }
                   9039:                 last;
                   9040:             }
                   9041:         }
                   9042:         if ($action eq 'none') {
                   9043:              return 'ok';
                   9044:         } else {
                   9045:             my %changes;
                   9046:             my $newend = 0;
                   9047:             my $newstart = $now;
                   9048:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9049:             $changes{$action}{$newkey} = {
                   9050:                 type => 'public',
                   9051:                 time => {
                   9052:                     start => $newstart,
                   9053:                     end   => $newend,
                   9054:                 },
                   9055:             };
                   9056:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9057:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9058:             return $outcome;
                   9059:         }
                   9060:     } else {
                   9061:         return 'invalid';
                   9062:     }
                   9063: }
                   9064: 
1.745     raeburn  9065: #------------------------------------------------------Get Marked as Read Only
                   9066: 
                   9067: sub get_marked_as_readonly {
                   9068:     my ($domain,$user,$what,$group) = @_;
                   9069:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9070:     my @readonly_files;
1.629     banghart 9071:     my $cmp1=$what;
                   9072:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9073:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9074:         if (defined($group)) {
                   9075:             if ($file_name !~ m-^\Q$group\E/-) {
                   9076:                 next;
                   9077:             }
                   9078:         }
1.561     banghart 9079:         if (ref($value) eq "ARRAY"){
                   9080:             foreach my $stored_what (@{$value}) {
1.629     banghart 9081:                 my $cmp2=$stored_what;
1.759     albertel 9082:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9083:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9084:                 }
1.629     banghart 9085:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9086:                     push(@readonly_files, $file_name);
1.745     raeburn  9087:                     last;
1.563     banghart 9088:                 } elsif (!defined($what)) {
                   9089:                     push(@readonly_files, $file_name);
1.745     raeburn  9090:                     last;
1.561     banghart 9091:                 }
                   9092:             }
1.745     raeburn  9093:         }
1.561     banghart 9094:     }
                   9095:     return @readonly_files;
                   9096: }
1.577     banghart 9097: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9098: 
1.577     banghart 9099: sub get_marked_as_readonly_hash {
1.745     raeburn  9100:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9101:     my %readonly_files;
1.745     raeburn  9102:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9103:         if (defined($group)) {
                   9104:             if ($file_name !~ m-^\Q$group\E/-) {
                   9105:                 next;
                   9106:             }
                   9107:         }
1.577     banghart 9108:         if (ref($value) eq "ARRAY"){
                   9109:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9110:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9111:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9112:                         if ($lock_descriptor eq 'graded') {
                   9113:                             $readonly_files{$file_name} = 'graded';
                   9114:                         } elsif ($lock_descriptor eq 'handback') {
                   9115:                             $readonly_files{$file_name} = 'handback';
                   9116:                         } else {
                   9117:                             if (!exists($readonly_files{$file_name})) {
                   9118:                                 $readonly_files{$file_name} = 'locked';
                   9119:                             }
                   9120:                         }
1.745     raeburn  9121:                     }
1.750     banghart 9122:                 } 
1.577     banghart 9123:             }
                   9124:         } 
                   9125:     }
                   9126:     return %readonly_files;
                   9127: }
1.559     banghart 9128: # ------------------------------------------------------------ Unmark as Read Only
                   9129: 
                   9130: sub unmark_as_readonly {
1.629     banghart 9131:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9132:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9133:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9134:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9135:     my $symb_crs = $what;
                   9136:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9137:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9138:     my ($tmp)=keys(%current_permissions);
                   9139:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9140:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9141:     foreach my $file (@readonly_files) {
1.759     albertel 9142: 	my $clean_file = &declutter_portfile($file);
                   9143: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9144: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9145:         my @new_locks;
                   9146:         my @del_keys;
                   9147:         if (ref($current_locks) eq "ARRAY"){
                   9148:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9149:                 my $compare=$locker;
1.749     raeburn  9150:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9151:                     $compare=join('',@{$locker});
1.746     raeburn  9152:                     if ($compare ne $symb_crs) {
                   9153:                         push(@new_locks, $locker);
                   9154:                     }
1.563     banghart 9155:                 }
                   9156:             }
1.650     albertel 9157:             if (scalar(@new_locks) > 0) {
1.563     banghart 9158:                 $current_permissions{$file} = \@new_locks;
                   9159:             } else {
                   9160:                 push(@del_keys, $file);
1.613     albertel 9161:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9162:                 delete($current_permissions{$file});
1.563     banghart 9163:             }
                   9164:         }
1.561     banghart 9165:     }
1.613     albertel 9166:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9167:     return;
                   9168: }
1.512     banghart 9169: 
1.17      www      9170: # ------------------------------------------------------------ Directory lister
                   9171: 
                   9172: sub dirlist {
1.955     raeburn  9173:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9174:     $uri=~s/^\///;
                   9175:     $uri=~s/\/$//;
1.253     stredwic 9176:     my ($udom, $uname);
1.955     raeburn  9177:     if ($getuserdir) {
1.253     stredwic 9178:         $udom = $userdomain;
                   9179:         $uname = $username;
1.955     raeburn  9180:     } else {
                   9181:         (undef,$udom,$uname)=split(/\//,$uri);
                   9182:         if(defined($userdomain)) {
                   9183:             $udom = $userdomain;
                   9184:         }
                   9185:         if(defined($username)) {
                   9186:             $uname = $username;
                   9187:         }
1.253     stredwic 9188:     }
1.955     raeburn  9189:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9190: 
1.955     raeburn  9191:     $dirRoot = $perlvar{'lonDocRoot'};
                   9192:     if (defined($getpropath)) {
                   9193:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9194:         $dirRoot =~ s/\/$//;
1.955     raeburn  9195:     } elsif (defined($getuserdir)) {
                   9196:         my $subdir=$uname.'__';
                   9197:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9198:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9199:                    ."/$udom/$subdir/$uname";
                   9200:     } elsif (defined($alternateRoot)) {
                   9201:         $dirRoot = $alternateRoot;
1.751     banghart 9202:     }
1.253     stredwic 9203: 
                   9204:     if($udom) {
                   9205:         if($uname) {
1.1135    raeburn  9206:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9207:             if ($uhome eq 'no_host') {
                   9208:                 return ([],'no_host');
                   9209:             }
1.955     raeburn  9210:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9211:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9212:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9213:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9214:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9215:             } else {
                   9216:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9217:             }
1.605     matthew  9218:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9219:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9220:                 @listing_results = split(/:/,$listing);
                   9221:             } else {
                   9222:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9223:             }
1.1135    raeburn  9224:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9225:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9226:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9227:                 return ([],$listing);
                   9228:             } else {
                   9229:                 return (\@listing_results);
1.1135    raeburn  9230:             }
1.955     raeburn  9231:         } elsif(!$alternateRoot) {
1.1136    raeburn  9232:             my (%allusers,%listerror);
1.841     albertel 9233: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9234:  	    foreach my $tryserver (keys(%servers)) {
                   9235:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9236:                                   &escape($udom),$tryserver);
                   9237:                 if ($listing eq 'unknown_cmd') {
                   9238: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9239: 				      $udom, $tryserver);
                   9240:                 } else {
                   9241:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9242:                 }
1.841     albertel 9243: 		if ($listing eq 'unknown_cmd') {
                   9244: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9245: 				      $udom, $tryserver);
                   9246: 		    @listing_results = split(/:/,$listing);
                   9247: 		} else {
                   9248: 		    @listing_results =
                   9249: 			map { &unescape($_); } split(/:/,$listing);
                   9250: 		}
1.1136    raeburn  9251:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9252:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9253:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9254:                     $listerror{$tryserver} = $listing;
                   9255:                 } else {
1.841     albertel 9256: 		    foreach my $line (@listing_results) {
                   9257: 			my ($entry) = split(/&/,$line,2);
                   9258: 			$allusers{$entry} = 1;
                   9259: 		    }
                   9260: 		}
1.253     stredwic 9261:             }
1.1136    raeburn  9262:             my @alluserslist=();
1.800     albertel 9263:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9264:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9265:             }
1.1136    raeburn  9266:             return (\@alluserslist);
1.253     stredwic 9267:         } else {
1.1136    raeburn  9268:             return ([],'missing username');
1.253     stredwic 9269:         }
1.955     raeburn  9270:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9271:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9272:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9273:         return (\@all_domains);
1.955     raeburn  9274:     } else {
1.1136    raeburn  9275:         return ([],'missing domain');
1.275     stredwic 9276:     }
                   9277: }
                   9278: 
                   9279: # --------------------------------------------- GetFileTimestamp
                   9280: # This function utilizes dirlist and returns the date stamp for
                   9281: # when it was last modified.  It will also return an error of -1
                   9282: # if an error occurs
                   9283: 
                   9284: sub GetFileTimestamp {
1.955     raeburn  9285:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9286:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9287:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9288:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9289:                                     undef,$getuserdir);
                   9290:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9291:         return -1;
                   9292:     }
                   9293:     if (ref($fileref) eq 'ARRAY') {
                   9294:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9295:         # @stats contains first the filename, then the stat output
                   9296:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9297:     } else {
                   9298:         return -1;
1.253     stredwic 9299:     }
1.26      www      9300: }
                   9301: 
1.712     albertel 9302: sub stat_file {
                   9303:     my ($uri) = @_;
1.787     albertel 9304:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9305: 
1.955     raeburn  9306:     my ($udom,$uname,$file);
1.712     albertel 9307:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9308: 	($udom,$uname,$file) =
1.811     albertel 9309: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9310: 	$file = 'userfiles/'.$file;
                   9311:     }
                   9312:     if ($uri =~ m-^/res/-) {
                   9313: 	($udom,$uname) = 
1.807     albertel 9314: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9315: 	$file = $uri;
                   9316:     }
                   9317: 
                   9318:     if (!$udom || !$uname || !$file) {
                   9319: 	# unable to handle the uri
                   9320: 	return ();
                   9321:     }
1.956     raeburn  9322:     my $getpropath;
                   9323:     if ($file =~ /^userfiles\//) {
                   9324:         $getpropath = 1;
                   9325:     }
1.1136    raeburn  9326:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9327:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9328:         return ();
                   9329:     } else {
                   9330:         if (ref($listref) eq 'ARRAY') {
                   9331:             my @stats = split('&',$listref->[0]);
                   9332: 	    shift(@stats); #filename is first
                   9333: 	    return @stats;
                   9334:         }
1.712     albertel 9335:     }
                   9336:     return ();
                   9337: }
                   9338: 
1.26      www      9339: # -------------------------------------------------------- Value of a Condition
                   9340: 
1.713     albertel 9341: # gets the value of a specific preevaluated condition
                   9342: #    stored in the string  $env{user.state.<cid>}
                   9343: # or looks up a condition reference in the bighash and if if hasn't
                   9344: # already been evaluated recurses into docondval to get the value of
                   9345: # the condition, then memoizing it to 
                   9346: #   $env{user.state.<cid>.<condition>}
1.40      www      9347: sub directcondval {
                   9348:     my $number=shift;
1.620     albertel 9349:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9350: 	&Apache::lonuserstate::evalstate();
                   9351:     }
1.713     albertel 9352:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9353: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9354:     } elsif ($number =~ /^_/) {
                   9355: 	my $sub_condition;
                   9356: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9357: 		&GDBM_READER(),0640)) {
                   9358: 	    $sub_condition=$bighash{'conditions'.$number};
                   9359: 	    untie(%bighash);
                   9360: 	}
                   9361: 	my $value = &docondval($sub_condition);
1.949     raeburn  9362: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9363: 	return $value;
                   9364:     }
1.620     albertel 9365:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9366:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9367:     } else {
                   9368:        return 2;
                   9369:     }
                   9370: }
                   9371: 
1.713     albertel 9372: # get the collection of conditions for this resource
1.26      www      9373: sub condval {
                   9374:     my $condidx=shift;
1.54      www      9375:     my $allpathcond='';
1.713     albertel 9376:     foreach my $cond (split(/\|/,$condidx)) {
                   9377: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9378: 	    $allpathcond.=
                   9379: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9380: 	}
1.191     harris41 9381:     }
1.54      www      9382:     $allpathcond=~s/\|$//;
1.713     albertel 9383:     return &docondval($allpathcond);
                   9384: }
                   9385: 
                   9386: #evaluates an expression of conditions
                   9387: sub docondval {
                   9388:     my ($allpathcond) = @_;
                   9389:     my $result=0;
                   9390:     if ($env{'request.course.id'}
                   9391: 	&& defined($allpathcond)) {
                   9392: 	my $operand='|';
                   9393: 	my @stack;
                   9394: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9395: 	    if ($chunk eq '(') {
                   9396: 		push @stack,($operand,$result);
                   9397: 	    } elsif ($chunk eq ')') {
                   9398: 		my $before=pop @stack;
                   9399: 		if (pop @stack eq '&') {
                   9400: 		    $result=$result>$before?$before:$result;
                   9401: 		} else {
                   9402: 		    $result=$result>$before?$result:$before;
                   9403: 		}
                   9404: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9405: 		$operand=$chunk;
                   9406: 	    } else {
                   9407: 		my $new=directcondval($chunk);
                   9408: 		if ($operand eq '&') {
                   9409: 		    $result=$result>$new?$new:$result;
                   9410: 		} else {
                   9411: 		    $result=$result>$new?$result:$new;
                   9412: 		}
                   9413: 	    }
                   9414: 	}
1.26      www      9415:     }
                   9416:     return $result;
1.421     albertel 9417: }
                   9418: 
                   9419: # ---------------------------------------------------- Devalidate courseresdata
                   9420: 
                   9421: sub devalidatecourseresdata {
                   9422:     my ($coursenum,$coursedomain)=@_;
                   9423:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9424:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9425: }
                   9426: 
1.763     www      9427: 
1.200     www      9428: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9429: #
                   9430: #  Parameters:
                   9431: #      $coursenum    - Number of the course.
                   9432: #      $coursedomain - Domain at which the course was created.
                   9433: #  Returns:
                   9434: #     A hash of the course parameters along (I think) with timestamps
                   9435: #     and version info.
1.877     foxr     9436: 
1.624     albertel 9437: sub get_courseresdata {
                   9438:     my ($coursenum,$coursedomain)=@_;
1.200     www      9439:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9440:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9441:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9442:     my %dumpreply;
1.417     albertel 9443:     unless (defined($cached)) {
1.624     albertel 9444: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9445: 	$result=\%dumpreply;
1.251     albertel 9446: 	my ($tmp) = keys(%dumpreply);
                   9447: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9448: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9449: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9450: 	    return $tmp;
1.416     albertel 9451: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9452: 	    $result=undef;
1.599     albertel 9453: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9454: 	}
                   9455:     }
1.624     albertel 9456:     return $result;
                   9457: }
                   9458: 
1.633     albertel 9459: sub devalidateuserresdata {
                   9460:     my ($uname,$udom)=@_;
                   9461:     my $hashid="$udom:$uname";
                   9462:     &devalidate_cache_new('userres',$hashid);
                   9463: }
                   9464: 
1.624     albertel 9465: sub get_userresdata {
                   9466:     my ($uname,$udom)=@_;
                   9467:     #most student don\'t have any data set, check if there is some data
                   9468:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9469: 
                   9470:     my $hashid="$udom:$uname";
                   9471:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9472:     if (!defined($cached)) {
                   9473: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9474: 	$result=\%resourcedata;
                   9475: 	&do_cache_new('userres',$hashid,$result,600);
                   9476:     }
                   9477:     my ($tmp)=keys(%$result);
                   9478:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9479: 	return $result;
                   9480:     }
                   9481:     #error 2 occurs when the .db doesn't exist
                   9482:     if ($tmp!~/error: 2 /) {
1.672     albertel 9483: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9484: 		 " Trying to get resource data for ".
                   9485: 		 $uname." at ".$udom.": ".
                   9486: 		 $tmp."</font>");
                   9487:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9488: 	#&EXT_cache_set($udom,$uname);
                   9489: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9490: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9491:     }
                   9492:     return $tmp;
                   9493: }
1.879     foxr     9494: #----------------------------------------------- resdata - return resource data
                   9495: #  Purpose:
                   9496: #    Return resource data for either users or for a course.
                   9497: #  Parameters:
                   9498: #     $name      - Course/user name.
                   9499: #     $domain    - Name of the domain the user/course is registered on.
                   9500: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9501: #     @which     - Array of names of resources desired.
                   9502: #  Returns:
                   9503: #     The value of the first reasource in @which that is found in the
                   9504: #     resource hash.
                   9505: #  Exceptional Conditions:
                   9506: #     If the $type passed in is not valid (not the string 'course' or 
                   9507: #     'user', an undefined  reference is returned.
                   9508: #     If none of the resources are found, an undef is returned
1.624     albertel 9509: sub resdata {
                   9510:     my ($name,$domain,$type,@which)=@_;
                   9511:     my $result;
                   9512:     if ($type eq 'course') {
                   9513: 	$result=&get_courseresdata($name,$domain);
                   9514:     } elsif ($type eq 'user') {
                   9515: 	$result=&get_userresdata($name,$domain);
                   9516:     }
                   9517:     if (!ref($result)) { return $result; }    
1.251     albertel 9518:     foreach my $item (@which) {
1.927     albertel 9519: 	if (defined($result->{$item->[0]})) {
                   9520: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9521: 	}
1.250     albertel 9522:     }
1.291     albertel 9523:     return undef;
1.200     www      9524: }
                   9525: 
1.379     matthew  9526: #
                   9527: # EXT resource caching routines
                   9528: #
                   9529: 
                   9530: sub clear_EXT_cache_status {
1.383     albertel 9531:     &delenv('cache.EXT.');
1.379     matthew  9532: }
                   9533: 
                   9534: sub EXT_cache_status {
                   9535:     my ($target_domain,$target_user) = @_;
1.383     albertel 9536:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9537:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9538:         # We know already the user has no data
                   9539:         return 1;
                   9540:     } else {
                   9541:         return 0;
                   9542:     }
                   9543: }
                   9544: 
                   9545: sub EXT_cache_set {
                   9546:     my ($target_domain,$target_user) = @_;
1.383     albertel 9547:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9548:     #&appenv({$cachename => time});
1.379     matthew  9549: }
                   9550: 
1.28      www      9551: # --------------------------------------------------------- Value of a Variable
1.58      www      9552: sub EXT {
1.715     albertel 9553: 
1.395     albertel 9554:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9555:     unless ($varname) { return ''; }
1.218     albertel 9556:     #get real user name/domain, courseid and symb
                   9557:     my $courseid;
1.359     albertel 9558:     my $publicuser;
1.427     www      9559:     if ($symbparm) {
                   9560: 	$symbparm=&get_symb_from_alias($symbparm);
                   9561:     }
1.218     albertel 9562:     if (!($uname && $udom)) {
1.790     albertel 9563:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9564:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9565:     } else {
1.620     albertel 9566: 	$courseid=$env{'request.course.id'};
1.218     albertel 9567:     }
1.48      www      9568:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9569:     my $rest;
1.320     albertel 9570:     if (defined($therest[0])) {
1.48      www      9571:        $rest=join('.',@therest);
                   9572:     } else {
                   9573:        $rest='';
                   9574:     }
1.320     albertel 9575: 
1.57      www      9576:     my $qualifierrest=$qualifier;
                   9577:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9578:     my $spacequalifierrest=$space;
                   9579:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9580:     if ($realm eq 'user') {
1.48      www      9581: # --------------------------------------------------------------- user.resource
                   9582: 	if ($space eq 'resource') {
1.651     albertel 9583: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9584: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9585: 		 &&
1.744     albertel 9586: 		 ($symbparm eq &symbread()) ) {	
                   9587: 		# if we are in the middle of processing the resource the
                   9588: 		# get the value we are planning on committing
                   9589:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9590:                     return $Apache::lonhomework::results{$qualifierrest};
                   9591:                 } else {
                   9592:                     return $Apache::lonhomework::history{$qualifierrest};
                   9593:                 }
1.335     albertel 9594: 	    } else {
1.359     albertel 9595: 		my %restored;
1.620     albertel 9596: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9597: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9598: 		} else {
                   9599: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9600: 		}
1.335     albertel 9601: 		return $restored{$qualifierrest};
                   9602: 	    }
1.48      www      9603: # ----------------------------------------------------------------- user.access
                   9604:         } elsif ($space eq 'access') {
1.218     albertel 9605: 	    # FIXME - not supporting calls for a specific user
1.48      www      9606:             return &allowed($qualifier,$rest);
                   9607: # ------------------------------------------ user.preferences, user.environment
                   9608:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9609: 	    if (($uname eq $env{'user.name'}) &&
                   9610: 		($udom eq $env{'user.domain'})) {
                   9611: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9612: 	    } else {
1.359     albertel 9613: 		my %returnhash;
                   9614: 		if (!$publicuser) {
                   9615: 		    %returnhash=&userenvironment($udom,$uname,
                   9616: 						 $qualifierrest);
                   9617: 		}
1.218     albertel 9618: 		return $returnhash{$qualifierrest};
                   9619: 	    }
1.48      www      9620: # ----------------------------------------------------------------- user.course
                   9621:         } elsif ($space eq 'course') {
1.218     albertel 9622: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9623:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9624: # ------------------------------------------------------------------- user.role
                   9625:         } elsif ($space eq 'role') {
1.218     albertel 9626: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9627:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9628:             if ($qualifier eq 'value') {
                   9629: 		return $role;
                   9630:             } elsif ($qualifier eq 'extent') {
                   9631:                 return $where;
                   9632:             }
                   9633: # ----------------------------------------------------------------- user.domain
                   9634:         } elsif ($space eq 'domain') {
1.218     albertel 9635:             return $udom;
1.48      www      9636: # ------------------------------------------------------------------- user.name
                   9637:         } elsif ($space eq 'name') {
1.218     albertel 9638:             return $uname;
1.48      www      9639: # ---------------------------------------------------- Any other user namespace
1.29      www      9640:         } else {
1.359     albertel 9641: 	    my %reply;
                   9642: 	    if (!$publicuser) {
                   9643: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9644: 	    }
                   9645: 	    return $reply{$qualifierrest};
1.48      www      9646:         }
1.236     www      9647:     } elsif ($realm eq 'query') {
                   9648: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9649:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9650: 						[$spacequalifierrest]);
1.620     albertel 9651: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9652:    } elsif ($realm eq 'request') {
1.48      www      9653: # ------------------------------------------------------------- request.browser
                   9654:         if ($space eq 'browser') {
1.1145    bisitz   9655:             return $env{'browser.'.$qualifier};
1.57      www      9656: # ------------------------------------------------------------ request.filename
                   9657:         } else {
1.620     albertel 9658:             return $env{'request.'.$spacequalifierrest};
1.29      www      9659:         }
1.28      www      9660:     } elsif ($realm eq 'course') {
1.48      www      9661: # ---------------------------------------------------------- course.description
1.620     albertel 9662:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9663:     } elsif ($realm eq 'resource') {
1.165     www      9664: 
1.620     albertel 9665: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9666: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9667: 	}
1.693     albertel 9668: 
                   9669: 	if ($space eq 'title') {
                   9670: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9671: 	    return &gettitle($symbparm);
                   9672: 	}
                   9673: 	
                   9674: 	if ($space eq 'map') {
                   9675: 	    my ($map) = &decode_symb($symbparm);
                   9676: 	    return &symbread($map);
                   9677: 	}
1.905     albertel 9678: 	if ($space eq 'filename') {
                   9679: 	    if ($symbparm) {
                   9680: 		return &clutter((&decode_symb($symbparm))[2]);
                   9681: 	    }
                   9682: 	    return &hreflocation('',$env{'request.filename'});
                   9683: 	}
1.693     albertel 9684: 
                   9685: 	my ($section, $group, @groups);
1.593     albertel 9686: 	my ($courselevelm,$courselevel);
1.539     albertel 9687: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9688: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9689: 
1.218     albertel 9690: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9691: 
1.60      www      9692: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9693: 	    my $symbp=$symbparm;
1.735     albertel 9694: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9695: 
                   9696: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9697: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9698: 
1.620     albertel 9699: 	    if (($env{'user.name'} eq $uname) &&
                   9700: 		($env{'user.domain'} eq $udom)) {
                   9701: 		$section=$env{'request.course.sec'};
1.733     raeburn  9702:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9703:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9704: 	    } else {
1.539     albertel 9705: 		if (! defined($usection)) {
1.551     albertel 9706: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9707: 		} else {
                   9708: 		    $section = $usection;
                   9709: 		}
1.733     raeburn  9710:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9711: 	    }
                   9712: 
                   9713: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9714: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9715: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9716: 
1.593     albertel 9717: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9718: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9719: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9720: 
1.60      www      9721: # ----------------------------------------------------------- first, check user
1.624     albertel 9722: 
                   9723: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9724: 				       ([$courselevelr,'resource'],
                   9725: 					[$courselevelm,'map'     ],
                   9726: 					[$courselevel, 'course'  ]));
1.931     albertel 9727: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9728: 
1.594     albertel 9729: # ------------------------------------------------ second, check some of course
1.684     raeburn  9730:             my $coursereply;
1.691     raeburn  9731:             if (@groups > 0) {
                   9732:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9733:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9734:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9735:             }
1.96      www      9736: 
1.684     raeburn  9737: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9738: 				  $env{'course.'.$courseid.'.domain'},
                   9739: 				  'course',
                   9740: 				  ([$seclevelr,   'resource'],
                   9741: 				   [$seclevelm,   'map'     ],
                   9742: 				   [$seclevel,    'course'  ],
                   9743: 				   [$courselevelr,'resource']));
                   9744: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9745: 
1.60      www      9746: # ------------------------------------------------------ third, check map parms
1.218     albertel 9747: 	    my %parmhash=();
                   9748: 	    my $thisparm='';
                   9749: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9750: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9751: 		    &GDBM_READER(),0640)) {
1.218     albertel 9752: 		$thisparm=$parmhash{$symbparm};
                   9753: 		untie(%parmhash);
                   9754: 	    }
1.927     albertel 9755: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9756: 	}
1.594     albertel 9757: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9758: 
1.218     albertel 9759: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9760: 	my $filename;
                   9761: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9762: 	if ($symbparm) {
1.409     www      9763: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9764: 	} else {
1.620     albertel 9765: 	    $filename=$env{'request.filename'};
1.282     albertel 9766: 	}
                   9767: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9768: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9769: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9770: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9771: 
1.927     albertel 9772: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9773: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9774: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9775: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9776: 				     $env{'course.'.$courseid.'.domain'},
                   9777: 				     'course',
1.927     albertel 9778: 				     ([$courselevelm,'map'   ],
                   9779: 				      [$courselevel, 'course']));
                   9780: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9781: 	}
1.145     www      9782: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9783: 	unless ($space eq '0') {
1.336     albertel 9784: 	    my @parts=split(/_/,$space);
                   9785: 	    my $id=pop(@parts);
                   9786: 	    my $part=join('_',@parts);
                   9787: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9788: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9789: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9790: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9791: 	}
1.395     albertel 9792: 	if ($recurse) { return undef; }
                   9793: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9794: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9795: # ---------------------------------------------------- Any other user namespace
                   9796:     } elsif ($realm eq 'environment') {
                   9797: # ----------------------------------------------------------------- environment
1.620     albertel 9798: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9799: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9800: 	} else {
1.770     albertel 9801: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9802: 		return '';
                   9803: 	    }
1.219     albertel 9804: 	    my %returnhash=&userenvironment($udom,$uname,
                   9805: 					    $spacequalifierrest);
                   9806: 	    return $returnhash{$spacequalifierrest};
                   9807: 	}
1.28      www      9808:     } elsif ($realm eq 'system') {
1.48      www      9809: # ----------------------------------------------------------------- system.time
                   9810: 	if ($space eq 'time') {
                   9811: 	    return time;
                   9812:         }
1.696     albertel 9813:     } elsif ($realm eq 'server') {
                   9814: # ----------------------------------------------------------------- system.time
                   9815: 	if ($space eq 'name') {
                   9816: 	    return $ENV{'SERVER_NAME'};
                   9817:         }
1.28      www      9818:     }
1.48      www      9819:     return '';
1.61      www      9820: }
                   9821: 
1.927     albertel 9822: sub get_reply {
                   9823:     my ($reply_value) = @_;
1.940     raeburn  9824:     if (ref($reply_value) eq 'ARRAY') {
                   9825:         if (wantarray) {
                   9826: 	    return @$reply_value;
                   9827:         }
                   9828:         return $reply_value->[0];
                   9829:     } else {
                   9830:         return $reply_value;
1.927     albertel 9831:     }
                   9832: }
                   9833: 
1.691     raeburn  9834: sub check_group_parms {
                   9835:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9836:     my @groupitems = ();
                   9837:     my $resultitem;
1.927     albertel 9838:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9839:     foreach my $group (@{$groups}) {
                   9840:         foreach my $level (@levels) {
1.927     albertel 9841:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9842:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9843:         }
                   9844:     }
                   9845:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9846:                             $env{'course.'.$courseid.'.domain'},
                   9847:                                      'course',@groupitems);
                   9848:     return $coursereply;
                   9849: }
                   9850: 
                   9851: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9852:     my ($courseid,@groups) = @_;
                   9853:     @groups = sort(@groups);
1.691     raeburn  9854:     return @groups;
                   9855: }
                   9856: 
1.395     albertel 9857: sub packages_tab_default {
                   9858:     my ($uri,$varname)=@_;
                   9859:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9860: 
                   9861:     my (@extension,@specifics,$do_default);
                   9862:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9863: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9864: 	if ($pack_type eq 'default') {
                   9865: 	    $do_default=1;
                   9866: 	} elsif ($pack_type eq 'extension') {
                   9867: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9868: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9869: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9870: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9871: 	}
                   9872:     }
                   9873:     # first look for a package that matches the requested part id
                   9874:     foreach my $package (@specifics) {
                   9875: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9876: 	next if ($pack_part ne $part);
                   9877: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9878: 	    return $packagetab{"$pack_type&$name&default"};
                   9879: 	}
                   9880:     }
                   9881:     # look for any possible matching non extension_ package
                   9882:     foreach my $package (@specifics) {
                   9883: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9884: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9885: 	    return $packagetab{"$pack_type&$name&default"};
                   9886: 	}
1.585     albertel 9887: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9888: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9889: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9890: 	}
                   9891:     }
1.738     albertel 9892:     # look for any posible extension_ match
                   9893:     foreach my $package (@extension) {
                   9894: 	my ($package,$pack_type)=@{$package};
                   9895: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9896: 	    return $packagetab{"$pack_type&$name&default"};
                   9897: 	}
                   9898: 	if (defined($packagetab{$package."&$name&default"})) {
                   9899: 	    return $packagetab{$package."&$name&default"};
                   9900: 	}
                   9901:     }
                   9902:     # look for a global default setting
                   9903:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9904: 	return $packagetab{"default&$name&default"};
                   9905:     }
1.395     albertel 9906:     return undef;
                   9907: }
                   9908: 
1.334     albertel 9909: sub add_prefix_and_part {
                   9910:     my ($prefix,$part)=@_;
                   9911:     my $keyroot;
                   9912:     if (defined($prefix) && $prefix !~ /^__/) {
                   9913: 	# prefix that has a part already
                   9914: 	$keyroot=$prefix;
                   9915:     } elsif (defined($prefix)) {
                   9916: 	# prefix that is missing a part
                   9917: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9918:     } else {
                   9919: 	# no prefix at all
                   9920: 	if (defined($part)) { $keyroot='_'.$part; }
                   9921:     }
                   9922:     return $keyroot;
                   9923: }
                   9924: 
1.71      www      9925: # ---------------------------------------------------------------- Get metadata
                   9926: 
1.599     albertel 9927: my %metaentry;
1.1070    www      9928: my %importedpartids;
1.71      www      9929: sub metadata {
1.176     www      9930:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9931:     $uri=&declutter($uri);
1.288     albertel 9932:     # if it is a non metadata possible uri return quickly
1.529     albertel 9933:     if (($uri eq '') || 
                   9934: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9935: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9936:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9937: 	return undef;
                   9938:     }
1.1140    www      9939:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9940: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9941: 	return undef;
1.288     albertel 9942:     }
1.73      www      9943:     my $filename=$uri;
                   9944:     $uri=~s/\.meta$//;
1.172     www      9945: #
                   9946: # Is the metadata already cached?
1.177     www      9947: # Look at timestamp of caching
1.172     www      9948: # Everything is cached by the main uri, libraries are never directly cached
                   9949: #
1.428     albertel 9950:     if (!defined($liburi)) {
1.599     albertel 9951: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9952: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9953:     }
                   9954:     {
1.1069    www      9955: # Imported parts would go here
1.1070    www      9956:         my %importedids=();
                   9957:         my @origfileimportpartids=();
1.1069    www      9958:         my $importedparts=0;
1.172     www      9959: #
                   9960: # Is this a recursive call for a library?
                   9961: #
1.599     albertel 9962: #	if (! exists($metacache{$uri})) {
                   9963: #	    $metacache{$uri}={};
                   9964: #	}
1.924     albertel 9965: 	my $cachetime = 60*60;
1.171     www      9966:         if ($liburi) {
                   9967: 	    $liburi=&declutter($liburi);
                   9968:             $filename=$liburi;
1.401     bowersj2 9969:         } else {
1.599     albertel 9970: 	    &devalidate_cache_new('meta',$uri);
                   9971: 	    undef(%metaentry);
1.401     bowersj2 9972: 	}
1.140     www      9973:         my %metathesekeys=();
1.73      www      9974:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9975: 	my $metastring;
1.1140    www      9976: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9977: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9978: 	    $metastring = 
1.929     albertel 9979: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9980: 					  ('grade_target' => 'meta'));
                   9981: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9982: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9983:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9984: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9985: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9986: 	    $metastring=&getfile($file);
1.489     albertel 9987: 	}
1.208     albertel 9988:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9989:         my $token;
1.140     www      9990:         undef %metathesekeys;
1.71      www      9991:         while ($token=$parser->get_token) {
1.339     albertel 9992: 	    if ($token->[0] eq 'S') {
                   9993: 		if (defined($token->[2]->{'package'})) {
1.172     www      9994: #
                   9995: # This is a package - get package info
                   9996: #
1.339     albertel 9997: 		    my $package=$token->[2]->{'package'};
                   9998: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9999: 		    if (defined($token->[2]->{'id'})) { 
                   10000: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10001: 		    }
1.599     albertel 10002: 		    if ($metaentry{':packages'}) {
                   10003: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10004: 		    } else {
1.599     albertel 10005: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10006: 		    }
1.736     albertel 10007: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10008: 			my $part=$keyroot;
                   10009: 			$part=~s/^\_//;
1.736     albertel 10010: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10011: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10012: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10013: 			    # ignore package.tab specified default values
                   10014:                             # here &package_tab_default() will fetch those
                   10015: 			    if ($subp eq 'default') { next; }
1.736     albertel 10016: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10017: 			    my $unikey;
                   10018: 			    if ($pack =~ /_0$/) {
                   10019: 				$unikey='parameter_0_'.$name;
                   10020: 				$part=0;
                   10021: 			    } else {
                   10022: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10023: 			    }
1.339     albertel 10024: 			    if ($subp eq 'display') {
                   10025: 				$value.=' [Part: '.$part.']';
                   10026: 			    }
1.599     albertel 10027: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10028: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10029: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10030: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10031: 			    }
1.599     albertel 10032: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10033: 				$metaentry{':'.$unikey}=
                   10034: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10035: 			    }
1.339     albertel 10036: 			}
                   10037: 		    }
                   10038: 		} else {
1.172     www      10039: #
                   10040: # This is not a package - some other kind of start tag
1.339     albertel 10041: #
                   10042: 		    my $entry=$token->[1];
1.1068    www      10043: 		    my $unikey='';
1.175     www      10044: 
1.339     albertel 10045: 		    if ($entry eq 'import') {
1.175     www      10046: #
                   10047: # Importing a library here
1.339     albertel 10048: #
1.1067    www      10049:                         my $location=$parser->get_text('/import');
                   10050:                         my $dir=$filename;
                   10051:                         $dir=~s|[^/]*$||;
                   10052:                         $location=&filelocation($dir,$location);
1.1069    www      10053:                        
1.1068    www      10054:                         my $importmode=$token->[2]->{'importmode'};
                   10055:                         if ($importmode eq 'problem') {
1.1069    www      10056: # Import as problem/response
1.1068    www      10057:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10058:                         } elsif ($importmode eq 'part') {
                   10059: # Import as part(s)
1.1069    www      10060:                            $importedparts=1;
                   10061: # We need to get the original file and the imported file to get the part order correct
                   10062: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10063: # Load and inspect original file
1.1070    www      10064:                            if ($#origfileimportpartids<0) {
                   10065:                               undef(%importedpartids);
                   10066:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10067:                               my $origfile=&getfile($origfilelocation);
                   10068:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10069:                            }
                   10070: 
1.1069    www      10071: # Load and inspect imported file
                   10072:                            my $impfile=&getfile($location);
                   10073:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10074:                            if ($#impfilepartids>=0) {
                   10075: # This problem had parts
1.1070    www      10076:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10077:                            } else {
                   10078: # Importing by turning a single problem into a problem part
                   10079: # It gets the import-tags ID as part-ID
                   10080:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10081:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10082:                            }
1.1068    www      10083:                         } else {
                   10084: # Normal import
                   10085:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10086:                            if (defined($token->[2]->{'id'})) {
                   10087:                               $unikey.='_'.$token->[2]->{'id'};
                   10088:                            }
1.1067    www      10089:                         }
                   10090: 
1.339     albertel 10091: 			if ($depthcount<20) {
1.736     albertel 10092: 			    my $metadata = 
                   10093: 				&metadata($uri,'keys', $location,$unikey,
                   10094: 					  $depthcount+1);
                   10095: 			    foreach my $meta (split(',',$metadata)) {
                   10096: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10097: 				$metathesekeys{$meta}=1;
1.339     albertel 10098: 			    }
1.1068    www      10099: 			
                   10100:                         }
1.1067    www      10101: 		    } else {
                   10102: #
                   10103: # Not importing, some other kind of non-package, non-library start tag
                   10104: # 
                   10105:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10106:                         if (defined($token->[2]->{'id'})) {
                   10107:                             $unikey.='_'.$token->[2]->{'id'};
                   10108:                         }
1.339     albertel 10109: 			if (defined($token->[2]->{'name'})) { 
                   10110: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10111: 			}
                   10112: 			$metathesekeys{$unikey}=1;
1.736     albertel 10113: 			foreach my $param (@{$token->[3]}) {
                   10114: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10115: 				$token->[2]->{$param};
1.339     albertel 10116: 			}
                   10117: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10118: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10119: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10120: 		 # only ws inside the tag, and not in default, so use default
                   10121: 		 # as value
1.599     albertel 10122: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10123: 			} elsif ( $internaltext =~ /\S/ ) {
                   10124: 		  # something interesting inside the tag
                   10125: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10126: 			} else {
1.908     albertel 10127: 		  # no interesting values, don't set a default
1.339     albertel 10128: 			}
1.172     www      10129: # end of not-a-package not-a-library import
1.339     albertel 10130: 		    }
1.172     www      10131: # end of not-a-package start tag
1.339     albertel 10132: 		}
1.172     www      10133: # the next is the end of "start tag"
1.339     albertel 10134: 	    }
                   10135: 	}
1.483     albertel 10136: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10137: 	$extension = lc($extension);
                   10138: 	if ($extension eq 'htm') { $extension='html'; }
                   10139: 
1.737     albertel 10140: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10141: 	    #no specific packages #how's our extension
                   10142: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10143: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10144: 					 \%metathesekeys);
                   10145: 	}
1.883     albertel 10146: 
                   10147: 	if (!exists($metaentry{':packages'})
                   10148: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10149: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10150: 		#no specific packages well let's get default then
                   10151: 		if ($key!~/^default&/) { next; }
1.488     albertel 10152: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10153: 					     \%metathesekeys);
                   10154: 	    }
                   10155: 	}
1.338     www      10156: # are there custom rights to evaluate
1.599     albertel 10157: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10158: 
1.338     www      10159:     #
                   10160:     # Importing a rights file here
1.339     albertel 10161:     #
                   10162: 	    unless ($depthcount) {
1.599     albertel 10163: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10164: 		my $dir=$filename;
                   10165: 		$dir=~s|[^/]*$||;
                   10166: 		$location=&filelocation($dir,$location);
1.736     albertel 10167: 		my $rights_metadata =
                   10168: 		    &metadata($uri,'keys',$location,'_rights',
                   10169: 			      $depthcount+1);
                   10170: 		foreach my $rights (split(',',$rights_metadata)) {
                   10171: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10172: 		    $metathesekeys{$rights}=1;
1.339     albertel 10173: 		}
                   10174: 	    }
                   10175: 	}
1.737     albertel 10176: 	# uniqifiy package listing
                   10177: 	my %seen;
                   10178: 	my @uniq_packages =
                   10179: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10180: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10181: 
1.1070    www      10182:         if ($importedparts) {
                   10183: # We had imported parts and need to rebuild partorder
                   10184:            $metaentry{':partorder'}='';
                   10185:            $metathesekeys{'partorder'}=1;
                   10186:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10187:                if ($origfileimportpartids[$index] eq 'part') {
                   10188: # original part, part of the problem
                   10189:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10190:                } else {
                   10191: # we have imported parts at this position
                   10192:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10193:                }
                   10194:            }
                   10195:            $metaentry{':partorder'}=~s/^\,//;
                   10196:         }
                   10197: 
1.737     albertel 10198: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10199: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10200: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10201: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10202: # this is the end of "was not already recently cached
1.71      www      10203:     }
1.599     albertel 10204:     return $metaentry{':'.$what};
1.261     albertel 10205: }
                   10206: 
1.488     albertel 10207: sub metadata_create_package_def {
1.483     albertel 10208:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10209:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10210:     if ($subp eq 'default') { next; }
                   10211:     
1.599     albertel 10212:     if (defined($metaentry{':packages'})) {
                   10213: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10214:     } else {
1.599     albertel 10215: 	$metaentry{':packages'}=$package;
1.483     albertel 10216:     }
                   10217:     my $value=$packagetab{$key};
                   10218:     my $unikey;
                   10219:     $unikey='parameter_0_'.$name;
1.599     albertel 10220:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10221:     $$metathesekeys{$unikey}=1;
1.599     albertel 10222:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10223: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10224:     }
1.599     albertel 10225:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10226: 	$metaentry{':'.$unikey}=
                   10227: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10228:     }
                   10229: }
                   10230: 
1.261     albertel 10231: sub metadata_generate_part0 {
                   10232:     my ($metadata,$metacache,$uri) = @_;
                   10233:     my %allnames;
1.737     albertel 10234:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10235: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10236: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10237: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10238: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10239: 	    $allnames{$name}=$part;
                   10240: 	  }
                   10241: 	}
                   10242:     }
                   10243:     foreach my $name (keys(%allnames)) {
                   10244:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10245:       my $key=":parameter_0_$name";
1.261     albertel 10246:       $$metacache{"$key.part"}='0';
                   10247:       $$metacache{"$key.name"}=$name;
1.428     albertel 10248:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10249: 					   $allnames{$name}.'_'.$name.
                   10250: 					   '.type'};
1.428     albertel 10251:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10252: 			     '.display'};
1.644     www      10253:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10254:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10255:       $$metacache{"$key.display"}=$olddis;
                   10256:     }
1.71      www      10257: }
                   10258: 
1.764     albertel 10259: # ------------------------------------------------------ Devalidate title cache
                   10260: 
                   10261: sub devalidate_title_cache {
                   10262:     my ($url)=@_;
                   10263:     if (!$env{'request.course.id'}) { return; }
                   10264:     my $symb=&symbread($url);
                   10265:     if (!$symb) { return; }
                   10266:     my $key=$env{'request.course.id'}."\0".$symb;
                   10267:     &devalidate_cache_new('title',$key);
                   10268: }
                   10269: 
1.1014    droeschl 10270: # ------------------------------------------------- Get the title of a course
                   10271: 
                   10272: sub current_course_title {
                   10273:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10274: }
1.301     www      10275: # ------------------------------------------------- Get the title of a resource
                   10276: 
                   10277: sub gettitle {
                   10278:     my $urlsymb=shift;
                   10279:     my $symb=&symbread($urlsymb);
1.534     albertel 10280:     if ($symb) {
1.620     albertel 10281: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10282: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10283: 	if (defined($cached)) { 
                   10284: 	    return $result;
                   10285: 	}
1.534     albertel 10286: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10287: 	my $title='';
1.907     albertel 10288: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10289: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10290: 	} else {
                   10291: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10292: 		    &GDBM_READER(),0640)) {
                   10293: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10294: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10295: 		untie(%bighash);
                   10296: 	    }
1.534     albertel 10297: 	}
                   10298: 	$title=~s/\&colon\;/\:/gs;
                   10299: 	if ($title) {
1.1159    www      10300: # Remember both $symb and $title for dynamic metadata
                   10301:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10302:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10303: # Cache this title and then return it
1.599     albertel 10304: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10305: 	}
                   10306: 	$urlsymb=$url;
                   10307:     }
                   10308:     my $title=&metadata($urlsymb,'title');
                   10309:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10310:     return $title;
1.301     www      10311: }
1.613     albertel 10312: 
1.1199    raeburn  10313: sub getdocspath {
                   10314:     my ($symb) = @_;
                   10315:     my $path;
                   10316:     if ($symb) {
                   10317:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10318:         if ($resurl=~/\.(sequence|page)$/) {
                   10319:             $mapurl=$resurl;
                   10320:         } elsif ($resurl eq 'adm/navmaps') {
                   10321:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10322:         }
                   10323:         my $mapresobj;
                   10324:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10325:         if (ref($navmap)) {
                   10326:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10327:         }
                   10328:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10329:         my $type=$2;
                   10330:         if (ref($mapresobj)) {
                   10331:             my $pcslist = $mapresobj->map_hierarchy();
                   10332:             if ($pcslist ne '') {
                   10333:                 foreach my $pc (split(/,/,$pcslist)) {
                   10334:                     next if ($pc <= 1);
                   10335:                     my $res = $navmap->getByMapPc($pc);
                   10336:                     if (ref($res)) {
                   10337:                         my $thisurl = $res->src();
                   10338:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10339:                         my $thistitle = $res->title();
                   10340:                         $path .= '&'.
                   10341:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10342:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10343:                                  ':'.$res->randompick().
                   10344:                                  ':'.$res->randomout().
                   10345:                                  ':'.$res->encrypted().
1.1205    raeburn  10346:                                  ':'.$res->randomorder().
                   10347:                                  ':'.$res->is_page();
1.1199    raeburn  10348:                     }
                   10349:                 }
                   10350:             }
                   10351:             $path =~ s/^\&//;
                   10352:             my $maptitle = $mapresobj->title();
                   10353:             if ($mapurl eq 'default') {
                   10354:                 $maptitle = 'Main Course Documents';
                   10355:             }
                   10356:             $path .= ($path ne '')? '&' : ''.
                   10357:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10358:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10359:                     ':'.$mapresobj->randompick().
                   10360:                     ':'.$mapresobj->randomout().
                   10361:                     ':'.$mapresobj->encrypted().
1.1205    raeburn  10362:                     ':'.$mapresobj->randomorder().
                   10363:                     ':'.$mapresobj->is_page();
1.1199    raeburn  10364:         } else {
                   10365:             my $maptitle = &gettitle($mapurl);
1.1205    raeburn  10366:             my $ispage;
                   10367:             if ($mapurl =~ /\.page$/) {
                   10368:                 $ispage = 1;
                   10369:             }
1.1199    raeburn  10370:             if ($mapurl eq 'default') {
                   10371:                 $maptitle = 'Main Course Documents';
                   10372:             }
                   10373:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1205    raeburn  10374:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
1.1199    raeburn  10375:         }
                   10376:         unless ($mapurl eq 'default') {
                   10377:             $path = 'default&'.
                   10378:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
1.1205    raeburn  10379:                     ':::::&'.$path;
1.1199    raeburn  10380:         }
                   10381:     }
                   10382:     return $path;
                   10383: }
                   10384: 
1.614     albertel 10385: sub get_slot {
                   10386:     my ($which,$cnum,$cdom)=@_;
                   10387:     if (!$cnum || !$cdom) {
1.790     albertel 10388: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10389: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10390: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10391:     }
1.703     albertel 10392:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10393:     my %slotinfo;
                   10394:     if (exists($remembered{$key})) {
                   10395: 	$slotinfo{$which} = $remembered{$key};
                   10396:     } else {
                   10397: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10398: 	&Apache::lonhomework::showhash(%slotinfo);
                   10399: 	my ($tmp)=keys(%slotinfo);
                   10400: 	if ($tmp=~/^error:/) { return (); }
                   10401: 	$remembered{$key} = $slotinfo{$which};
                   10402:     }
1.616     albertel 10403:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10404: 	return %{$slotinfo{$which}};
                   10405:     }
                   10406:     return $slotinfo{$which};
1.614     albertel 10407: }
1.1150    raeburn  10408: 
                   10409: sub get_reservable_slots {
                   10410:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10411:     my $now = time;
                   10412:     my $reservable_info;
                   10413:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10414:     if (exists($remembered{$key})) {
                   10415:         $reservable_info = $remembered{$key};
                   10416:     } else {
                   10417:         my %resv;
                   10418:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10419:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10420:         $reservable_info = \%resv;
                   10421:         $remembered{$key} = $reservable_info;
                   10422:     }
                   10423:     return $reservable_info;
                   10424: }
                   10425: 
                   10426: sub get_course_slots {
                   10427:     my ($cnum,$cdom) = @_;
                   10428:     my $hashid=$cnum.':'.$cdom;
                   10429:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10430:     if (defined($cached)) {
                   10431:         if (ref($result) eq 'HASH') {
                   10432:             return %{$result};
                   10433:         }
                   10434:     } else {
                   10435:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10436:         my ($tmp) = keys(%slots);
                   10437:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10438:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10439:             return %slots;
                   10440:         }
                   10441:     }
                   10442:     return;
                   10443: }
                   10444: 
                   10445: sub devalidate_slots_cache {
                   10446:     my ($cnum,$cdom)=@_;
                   10447:     my $hashid=$cnum.':'.$cdom;
                   10448:     &devalidate_cache_new('allslots',$hashid);
                   10449: }
                   10450: 
1.1181    raeburn  10451: sub get_coursechange {
                   10452:     my ($cdom,$cnum) = @_;
                   10453:     if ($cdom eq '' || $cnum eq '') {
                   10454:         return unless ($env{'request.course.id'});
                   10455:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10456:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10457:     }
                   10458:     my $hashid=$cdom.'_'.$cnum;
                   10459:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10460:     if ((defined($cached)) && ($change ne '')) {
                   10461:         return $change;
                   10462:     } else {
                   10463:         my %crshash;
                   10464:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10465:         if ($crshash{'internal.contentchange'} eq '') {
                   10466:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10467:             if ($change eq '') {
                   10468:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10469:                 $change = $crshash{'internal.created'};
                   10470:             }
                   10471:         } else {
                   10472:             $change = $crshash{'internal.contentchange'};
                   10473:         }
                   10474:         my $cachetime = 600;
                   10475:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10476:     }
                   10477:     return $change;
                   10478: }
                   10479: 
                   10480: sub devalidate_coursechange_cache {
                   10481:     my ($cnum,$cdom)=@_;
                   10482:     my $hashid=$cnum.':'.$cdom;
                   10483:     &devalidate_cache_new('crschange',$hashid);
                   10484: }
                   10485: 
1.31      www      10486: # ------------------------------------------------- Update symbolic store links
                   10487: 
                   10488: sub symblist {
                   10489:     my ($mapname,%newhash)=@_;
1.438     www      10490:     $mapname=&deversion(&declutter($mapname));
1.31      www      10491:     my %hash;
1.620     albertel 10492:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10493:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10494:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10495: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10496: 		next if ($url eq 'last_known'
                   10497: 			 && $env{'form.no_update_last_known'});
                   10498: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10499: 						    $newhash{$url}->[1],
                   10500: 						    $newhash{$url}->[0]);
1.191     harris41 10501:             }
1.31      www      10502:             if (untie(%hash)) {
                   10503: 		return 'ok';
                   10504:             }
                   10505:         }
                   10506:     }
                   10507:     return 'error';
1.212     www      10508: }
                   10509: 
                   10510: # --------------------------------------------------------------- Verify a symb
                   10511: 
                   10512: sub symbverify {
1.1190    raeburn  10513:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10514:     my $thisfn=$thisurl;
1.439     www      10515:     $thisfn=&declutter($thisfn);
1.215     www      10516: # direct jump to resource in page or to a sequence - will construct own symbs
                   10517:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10518: # check URL part
1.409     www      10519:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10520: 
1.431     www      10521:     unless ($url eq $thisfn) { return 0; }
1.213     www      10522: 
1.216     www      10523:     $symb=&symbclean($symb);
1.510     www      10524:     $thisurl=&deversion($thisurl);
1.439     www      10525:     $thisfn=&deversion($thisfn);
1.213     www      10526: 
                   10527:     my %bighash;
                   10528:     my $okay=0;
1.431     www      10529: 
1.620     albertel 10530:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10531:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10532:         my $noclutter;
1.1032    raeburn  10533:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10534:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10535:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10536:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10537:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10538:                 $noclutter = 1;
                   10539:             }
                   10540:         }
                   10541:         my $ids;
                   10542:         if ($noclutter) {
                   10543:             $ids=$bighash{'ids_'.$thisurl};
                   10544:         } else {
                   10545:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10546:         }
1.1102    raeburn  10547:         unless ($ids) {
                   10548:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10549:             $ids=$bighash{$idkey};
1.216     www      10550:         }
                   10551:         if ($ids) {
                   10552: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10553:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10554:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10555:             }
1.800     albertel 10556: 	    foreach my $id (split(/\,/,$ids)) {
                   10557: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10558:                if (
                   10559:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10560:    eq $symb) {
                   10561:                    if (ref($encstate)) {
                   10562:                        $$encstate = $bighash{'encrypted_'.$id};
                   10563:                    }
1.620     albertel 10564: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10565: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10566:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10567: 		       $okay=1;
1.1202    raeburn  10568:                        last;
1.582     albertel 10569: 		   }
                   10570: 	       }
1.216     www      10571: 	   }
                   10572:         }
1.213     www      10573: 	untie(%bighash);
                   10574:     }
                   10575:     return $okay;
1.31      www      10576: }
                   10577: 
1.210     www      10578: # --------------------------------------------------------------- Clean-up symb
                   10579: 
                   10580: sub symbclean {
                   10581:     my $symb=shift;
1.568     albertel 10582:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10583: # remove version from map
                   10584:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10585: 
1.210     www      10586: # remove version from URL
                   10587:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10588: 
1.507     www      10589: # remove wrapper
                   10590: 
1.510     www      10591:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10592:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10593:     return $symb;
1.409     www      10594: }
                   10595: 
                   10596: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10597: 
                   10598: sub encode_symb {
                   10599:     my ($map,$resid,$url)=@_;
                   10600:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10601: }
1.409     www      10602: 
                   10603: sub decode_symb {
1.568     albertel 10604:     my $symb=shift;
                   10605:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10606:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10607:     return (&fixversion($map),$resid,&fixversion($url));
                   10608: }
                   10609: 
                   10610: sub fixversion {
                   10611:     my $fn=shift;
1.609     banghart 10612:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10613:     my %bighash;
                   10614:     my $uri=&clutter($fn);
1.620     albertel 10615:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10616: # is this cached?
1.599     albertel 10617:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10618:     if (defined($cached)) { return $result; }
                   10619: # unfortunately not cached, or expired
1.620     albertel 10620:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10621: 	    &GDBM_READER(),0640)) {
                   10622:  	if ($bighash{'version_'.$uri}) {
                   10623:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10624:  	    unless (($version eq 'mostrecent') || 
                   10625: 		    ($version==&getversion($uri))) {
1.440     www      10626:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10627:  	    }
                   10628:  	}
                   10629:  	untie %bighash;
1.413     www      10630:     }
1.599     albertel 10631:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10632: }
                   10633: 
                   10634: sub deversion {
                   10635:     my $url=shift;
                   10636:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10637:     return $url;
1.210     www      10638: }
                   10639: 
1.31      www      10640: # ------------------------------------------------------ Return symb list entry
                   10641: 
                   10642: sub symbread {
1.249     www      10643:     my ($thisfn,$donotrecurse)=@_;
1.1206    raeburn  10644:     my $cache_str;
                   10645:     if ($thisfn ne '') {
                   10646:         $cache_str='request.symbread.cached.'.$thisfn;
                   10647:         if ($env{$cache_str} ne '') {
1.1179    raeburn  10648:             return $env{$cache_str};
                   10649:         }
1.1206    raeburn  10650:     } else {
1.242     www      10651: # no filename provided? try from environment
1.620     albertel 10652:         if ($env{'request.symb'}) {
                   10653: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10654: 	}
1.620     albertel 10655: 	$thisfn=$env{'request.filename'};
1.44      www      10656:     }
1.569     albertel 10657:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10658: # is that filename actually a symb? Verify, clean, and return
                   10659:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10660: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10661: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10662: 	}
1.242     www      10663:     }
1.44      www      10664:     $thisfn=declutter($thisfn);
1.31      www      10665:     my %hash;
1.37      www      10666:     my %bighash;
                   10667:     my $syval='';
1.620     albertel 10668:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10669:         my $targetfn = $thisfn;
1.609     banghart 10670:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10671:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10672:         }
1.687     albertel 10673: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10674: 	    $targetfn=$1;
                   10675: 	}
1.620     albertel 10676:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10677:                       &GDBM_READER(),0640)) {
1.481     raeburn  10678: 	    $syval=$hash{$targetfn};
1.37      www      10679:             untie(%hash);
                   10680:         }
                   10681: # ---------------------------------------------------------- There was an entry
                   10682:         if ($syval) {
1.601     albertel 10683: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10684: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10685: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10686: 		    #return $env{$cache_str}='';
1.601     albertel 10687: 		#}    
                   10688: 		#$syval.=$1;
                   10689: 	    #}
1.37      www      10690:         } else {
                   10691: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10692:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10693:                             &GDBM_READER(),0640)) {
1.37      www      10694: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10695:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10696:               unless ($ids) { 
                   10697:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10698:               }
                   10699:               unless ($ids) {
                   10700: # alias?
                   10701: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10702:               }
1.37      www      10703:               if ($ids) {
                   10704: # ------------------------------------------------------------------- Has ID(s)
                   10705:                  my @possibilities=split(/\,/,$ids);
1.39      www      10706:                  if ($#possibilities==0) {
                   10707: # ----------------------------------------------- There is only one possibility
1.37      www      10708: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10709: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10710: 						    $resid,$thisfn);
1.249     www      10711:                  } elsif (!$donotrecurse) {
1.39      www      10712: # ------------------------------------------ There is more than one possibility
                   10713:                      my $realpossible=0;
1.800     albertel 10714:                      foreach my $id (@possibilities) {
                   10715: 			 my $file=$bighash{'src_'.$id};
1.39      www      10716:                          if (&allowed('bre',$file)) {
1.800     albertel 10717:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10718:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10719: 				$realpossible++;
1.626     albertel 10720:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10721: 						    $resid,$thisfn);
1.39      www      10722:                             }
                   10723: 			 }
1.191     harris41 10724:                      }
1.39      www      10725: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10726:                  } else {
                   10727:                      $syval='';
1.37      www      10728:                  }
                   10729: 	      }
                   10730:               untie(%bighash)
1.481     raeburn  10731:            }
1.31      www      10732:         }
1.62      www      10733:         if ($syval) {
1.620     albertel 10734: 	    return $env{$cache_str}=$syval;
1.62      www      10735:         }
1.31      www      10736:     }
1.949     raeburn  10737:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10738:     return $env{$cache_str}='';
1.31      www      10739: }
                   10740: 
                   10741: # ---------------------------------------------------------- Return random seed
                   10742: 
1.32      www      10743: sub numval {
                   10744:     my $txt=shift;
                   10745:     $txt=~tr/A-J/0-9/;
                   10746:     $txt=~tr/a-j/0-9/;
                   10747:     $txt=~tr/K-T/0-9/;
                   10748:     $txt=~tr/k-t/0-9/;
                   10749:     $txt=~tr/U-Z/0-5/;
                   10750:     $txt=~tr/u-z/0-5/;
                   10751:     $txt=~s/\D//g;
1.564     albertel 10752:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10753:     return int($txt);
1.368     albertel 10754: }
                   10755: 
1.484     albertel 10756: sub numval2 {
                   10757:     my $txt=shift;
                   10758:     $txt=~tr/A-J/0-9/;
                   10759:     $txt=~tr/a-j/0-9/;
                   10760:     $txt=~tr/K-T/0-9/;
                   10761:     $txt=~tr/k-t/0-9/;
                   10762:     $txt=~tr/U-Z/0-5/;
                   10763:     $txt=~tr/u-z/0-5/;
                   10764:     $txt=~s/\D//g;
                   10765:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10766:     my $total;
                   10767:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10768:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10769:     return int($total);
                   10770: }
                   10771: 
1.575     albertel 10772: sub numval3 {
                   10773:     use integer;
                   10774:     my $txt=shift;
                   10775:     $txt=~tr/A-J/0-9/;
                   10776:     $txt=~tr/a-j/0-9/;
                   10777:     $txt=~tr/K-T/0-9/;
                   10778:     $txt=~tr/k-t/0-9/;
                   10779:     $txt=~tr/U-Z/0-5/;
                   10780:     $txt=~tr/u-z/0-5/;
                   10781:     $txt=~s/\D//g;
                   10782:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10783:     my $total;
                   10784:     foreach my $val (@txts) { $total+=$val; }
                   10785:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10786:     return $total;
                   10787: }
                   10788: 
1.675     albertel 10789: sub digest {
                   10790:     my ($data)=@_;
                   10791:     my $digest=&Digest::MD5::md5($data);
                   10792:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10793:     my ($e,$f);
                   10794:     {
                   10795:         use integer;
                   10796:         $e=($a+$b);
                   10797:         $f=($c+$d);
                   10798:         if ($_64bit) {
                   10799:             $e=(($e<<32)>>32);
                   10800:             $f=(($f<<32)>>32);
                   10801:         }
                   10802:     }
                   10803:     if (wantarray) {
                   10804: 	return ($e,$f);
                   10805:     } else {
                   10806: 	my $g;
                   10807: 	{
                   10808: 	    use integer;
                   10809: 	    $g=($e+$f);
                   10810: 	    if ($_64bit) {
                   10811: 		$g=(($g<<32)>>32);
                   10812: 	    }
                   10813: 	}
                   10814: 	return $g;
                   10815:     }
                   10816: }
                   10817: 
1.368     albertel 10818: sub latest_rnd_algorithm_id {
1.675     albertel 10819:     return '64bit5';
1.366     albertel 10820: }
1.32      www      10821: 
1.503     albertel 10822: sub get_rand_alg {
                   10823:     my ($courseid)=@_;
1.790     albertel 10824:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10825:     if ($courseid) {
1.620     albertel 10826: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10827:     }
                   10828:     return &latest_rnd_algorithm_id();
                   10829: }
                   10830: 
1.562     albertel 10831: sub validCODE {
                   10832:     my ($CODE)=@_;
                   10833:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10834:     return 0;
                   10835: }
                   10836: 
1.491     albertel 10837: sub getCODE {
1.620     albertel 10838:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10839:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10840: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10841: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10842: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10843:     }
                   10844:     return undef;
                   10845: }
1.1133    foxr     10846: #
                   10847: #  Determines the random seed for a specific context:
                   10848: #
                   10849: # parameters:
                   10850: #   symb      - in course context the symb for the seed.
                   10851: #   course_id - The course id of the form domain_coursenum.
                   10852: #   domain    - Domain for the user.
                   10853: #   course    - Course for the user.
                   10854: #   cenv      - environment of the course.
                   10855: #
                   10856: # NOTE:
                   10857: #   All parameters are picked out of the environment if missing
                   10858: #   or not defined.
                   10859: #   If a symb cannot be determined the current time is used instead.
                   10860: #
                   10861: #  For a given well defined symb, courside, domain, username,
                   10862: #  and course environment, the seed is reproducible.
                   10863: #
1.31      www      10864: sub rndseed {
1.1133    foxr     10865:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10866:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10867:     if (!defined($symb)) {
1.366     albertel 10868: 	unless ($symb=$wsymb) { return time; }
                   10869:     }
1.1146    foxr     10870:     if (!defined $courseid) { 
                   10871: 	$courseid=$wcourseid; 
                   10872:     }
                   10873:     if (!defined $domain) { $domain=$wdomain; }
                   10874:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10875: 
                   10876:     my $which;
                   10877:     if (defined($cenv->{'rndseed'})) {
                   10878: 	$which = $cenv->{'rndseed'};
                   10879:     } else {
                   10880: 	$which =&get_rand_alg($courseid);
                   10881:     }
1.491     albertel 10882:     if (defined(&getCODE())) {
1.1133    foxr     10883: 
1.675     albertel 10884: 	if ($which eq '64bit5') {
                   10885: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10886: 	} elsif ($which eq '64bit4') {
1.575     albertel 10887: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10888: 	} else {
                   10889: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10890: 	}
1.675     albertel 10891:     } elsif ($which eq '64bit5') {
                   10892: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10893:     } elsif ($which eq '64bit4') {
                   10894: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10895:     } elsif ($which eq '64bit3') {
                   10896: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10897:     } elsif ($which eq '64bit2') {
                   10898: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10899:     } elsif ($which eq '64bit') {
                   10900: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10901:     }
                   10902:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10903: }
                   10904: 
                   10905: sub rndseed_32bit {
                   10906:     my ($symb,$courseid,$domain,$username)=@_;
                   10907:     {
                   10908: 	use integer;
                   10909: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10910: 	my $symbseed=numval($symb) << 22;
                   10911: 	my $namechck=unpack("%32C*",$username) << 17;
                   10912: 	my $nameseed=numval($username) << 12;
                   10913: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10914: 	my $courseseed=unpack("%32C*",$courseid);
                   10915: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10916: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10917: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10918: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10919: 	return $num;
                   10920:     }
                   10921: }
                   10922: 
                   10923: sub rndseed_64bit {
                   10924:     my ($symb,$courseid,$domain,$username)=@_;
                   10925:     {
                   10926: 	use integer;
                   10927: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10928: 	my $symbseed=numval($symb) << 10;
                   10929: 	my $namechck=unpack("%32S*",$username);
                   10930: 	
                   10931: 	my $nameseed=numval($username) << 21;
                   10932: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10933: 	my $courseseed=unpack("%32S*",$courseid);
                   10934: 	
                   10935: 	my $num1=$symbchck+$symbseed+$namechck;
                   10936: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10937: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10938: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10939: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10940: 	return "$num1,$num2";
1.155     albertel 10941:     }
1.366     albertel 10942: }
                   10943: 
1.443     albertel 10944: sub rndseed_64bit2 {
                   10945:     my ($symb,$courseid,$domain,$username)=@_;
                   10946:     {
                   10947: 	use integer;
                   10948: 	# strings need to be an even # of cahracters long, it it is odd the
                   10949:         # last characters gets thrown away
                   10950: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10951: 	my $symbseed=numval($symb) << 10;
                   10952: 	my $namechck=unpack("%32S*",$username.' ');
                   10953: 	
                   10954: 	my $nameseed=numval($username) << 21;
1.501     albertel 10955: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10956: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10957: 	
                   10958: 	my $num1=$symbchck+$symbseed+$namechck;
                   10959: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10960: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10961: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10962: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10963: 	return "$num1,$num2";
                   10964:     }
                   10965: }
                   10966: 
                   10967: sub rndseed_64bit3 {
                   10968:     my ($symb,$courseid,$domain,$username)=@_;
                   10969:     {
                   10970: 	use integer;
                   10971: 	# strings need to be an even # of cahracters long, it it is odd the
                   10972:         # last characters gets thrown away
                   10973: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10974: 	my $symbseed=numval2($symb) << 10;
                   10975: 	my $namechck=unpack("%32S*",$username.' ');
                   10976: 	
                   10977: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10978: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10979: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10980: 	
                   10981: 	my $num1=$symbchck+$symbseed+$namechck;
                   10982: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10983: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10984: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10985: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10986: 	
1.503     albertel 10987: 	return "$num1:$num2";
1.443     albertel 10988:     }
                   10989: }
                   10990: 
1.575     albertel 10991: sub rndseed_64bit4 {
                   10992:     my ($symb,$courseid,$domain,$username)=@_;
                   10993:     {
                   10994: 	use integer;
                   10995: 	# strings need to be an even # of cahracters long, it it is odd the
                   10996:         # last characters gets thrown away
                   10997: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10998: 	my $symbseed=numval3($symb) << 10;
                   10999: 	my $namechck=unpack("%32S*",$username.' ');
                   11000: 	
                   11001: 	my $nameseed=numval3($username) << 21;
                   11002: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11003: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11004: 	
                   11005: 	my $num1=$symbchck+$symbseed+$namechck;
                   11006: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11007: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11008: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11009: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11010: 	
1.575     albertel 11011: 	return "$num1:$num2";
                   11012:     }
                   11013: }
                   11014: 
1.675     albertel 11015: sub rndseed_64bit5 {
                   11016:     my ($symb,$courseid,$domain,$username)=@_;
                   11017:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11018:     return "$num1:$num2";
                   11019: }
                   11020: 
1.366     albertel 11021: sub rndseed_CODE_64bit {
                   11022:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11023:     {
1.366     albertel 11024: 	use integer;
1.443     albertel 11025: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11026: 	my $symbseed=numval2($symb);
1.491     albertel 11027: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11028: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11029: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11030: 	my $num1=$symbseed+$CODEchck;
                   11031: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11032: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11033: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11034: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11035: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11036: 	return "$num1:$num2";
1.366     albertel 11037:     }
                   11038: }
                   11039: 
1.575     albertel 11040: sub rndseed_CODE_64bit4 {
                   11041:     my ($symb,$courseid,$domain,$username)=@_;
                   11042:     {
                   11043: 	use integer;
                   11044: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11045: 	my $symbseed=numval3($symb);
                   11046: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11047: 	my $CODEseed=numval3(&getCODE());
                   11048: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11049: 	my $num1=$symbseed+$CODEchck;
                   11050: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11051: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11052: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11053: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11054: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11055: 	return "$num1:$num2";
                   11056:     }
                   11057: }
                   11058: 
1.675     albertel 11059: sub rndseed_CODE_64bit5 {
                   11060:     my ($symb,$courseid,$domain,$username)=@_;
                   11061:     my $code = &getCODE();
                   11062:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11063:     return "$num1:$num2";
                   11064: }
                   11065: 
1.366     albertel 11066: sub setup_random_from_rndseed {
                   11067:     my ($rndseed)=@_;
1.503     albertel 11068:     if ($rndseed =~/([,:])/) {
                   11069: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11070: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11071:     } else {
                   11072: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11073:     }
1.36      albertel 11074: }
                   11075: 
1.474     albertel 11076: sub latest_receipt_algorithm_id {
1.835     albertel 11077:     return 'receipt3';
1.474     albertel 11078: }
                   11079: 
1.480     www      11080: sub recunique {
                   11081:     my $fucourseid=shift;
                   11082:     my $unique;
1.835     albertel 11083:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11084: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11085: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11086:     } else {
                   11087: 	$unique=$perlvar{'lonReceipt'};
                   11088:     }
                   11089:     return unpack("%32C*",$unique);
                   11090: }
                   11091: 
                   11092: sub recprefix {
                   11093:     my $fucourseid=shift;
                   11094:     my $prefix;
1.835     albertel 11095:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11096: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11097: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11098:     } else {
                   11099: 	$prefix=$perlvar{'lonHostID'};
                   11100:     }
                   11101:     return unpack("%32C*",$prefix);
                   11102: }
                   11103: 
1.76      www      11104: sub ireceipt {
1.474     albertel 11105:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11106: 
                   11107:     my $return =&recprefix($fucourseid).'-';
                   11108: 
                   11109:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11110: 	$env{'request.state'} eq 'construct') {
                   11111: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11112: 	return $return;
                   11113:     }
                   11114: 
1.76      www      11115:     my $cuname=unpack("%32C*",$funame);
                   11116:     my $cudom=unpack("%32C*",$fudom);
                   11117:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11118:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11119:     my $cunique=&recunique($fucourseid);
1.474     albertel 11120:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11121:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11122: 
1.790     albertel 11123: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11124: 			       
                   11125: 	$return.= ($cunique%$cuname+
                   11126: 		   $cunique%$cudom+
                   11127: 		   $cusymb%$cuname+
                   11128: 		   $cusymb%$cudom+
                   11129: 		   $cucourseid%$cuname+
                   11130: 		   $cucourseid%$cudom+
                   11131: 		   $cpart%$cuname+
                   11132: 		   $cpart%$cudom);
                   11133:     } else {
                   11134: 	$return.= ($cunique%$cuname+
                   11135: 		   $cunique%$cudom+
                   11136: 		   $cusymb%$cuname+
                   11137: 		   $cusymb%$cudom+
                   11138: 		   $cucourseid%$cuname+
                   11139: 		   $cucourseid%$cudom);
                   11140:     }
                   11141:     return $return;
1.76      www      11142: }
                   11143: 
                   11144: sub receipt {
1.474     albertel 11145:     my ($part)=@_;
1.790     albertel 11146:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11147:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11148: }
1.260     ng       11149: 
1.790     albertel 11150: sub whichuser {
                   11151:     my ($passedsymb)=@_;
                   11152:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11153:     if (defined($env{'form.grade_symb'})) {
                   11154: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11155: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11156: 	if (!$allowed &&
                   11157: 	    exists($env{'request.course.sec'}) &&
                   11158: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11159: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11160: 			      '/'.$env{'request.course.sec'});
                   11161: 	}
                   11162: 	if ($allowed) {
                   11163: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11164: 	    $courseid=$tmp_courseid;
                   11165: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11166: 	    ($name)=&get_env_multiple('form.grade_username');
                   11167: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11168: 	}
                   11169:     }
                   11170:     if (!$passedsymb) {
                   11171: 	$symb=&symbread();
                   11172:     } else {
                   11173: 	$symb=$passedsymb;
                   11174:     }
                   11175:     $courseid=$env{'request.course.id'};
                   11176:     $domain=$env{'user.domain'};
                   11177:     $name=$env{'user.name'};
                   11178:     if ($name eq 'public' && $domain eq 'public') {
                   11179: 	if (!defined($env{'form.username'})) {
                   11180: 	    $env{'form.username'}.=time.rand(10000000);
                   11181: 	}
                   11182: 	$name.=$env{'form.username'};
                   11183:     }
                   11184:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11185: 
                   11186: }
                   11187: 
1.36      albertel 11188: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11189: # returns either the contents of the file or 
                   11190: # -1 if the file doesn't exist
1.481     raeburn  11191: #
                   11192: # if the target is a file that was uploaded via DOCS, 
                   11193: # a check will be made to see if a current copy exists on the local server,
                   11194: # if it does this will be served, otherwise a copy will be retrieved from
                   11195: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11196: # the local server.   
1.472     albertel 11197: 
1.36      albertel 11198: sub getfile {
1.538     albertel 11199:     my ($file) = @_;
1.609     banghart 11200:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11201:     &repcopy($file);
                   11202:     return &readfile($file);
                   11203: }
                   11204: 
                   11205: sub repcopy_userfile {
                   11206:     my ($file)=@_;
1.1142    raeburn  11207:     my $londocroot = $perlvar{'lonDocRoot'};
                   11208:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11209:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11210:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11211: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11212:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11213:     if (-e "$file") {
1.828     www      11214: # we already have a local copy, check it out
1.538     albertel 11215: 	my @fileinfo = stat($file);
1.828     www      11216: 	my $rtncode;
                   11217: 	my $info;
1.538     albertel 11218: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11219: 	if ($lwpresp ne 'ok') {
1.828     www      11220: # there is no such file anymore, even though we had a local copy
1.482     albertel 11221: 	    if ($rtncode eq '404') {
1.538     albertel 11222: 		unlink($file);
1.482     albertel 11223: 	    }
                   11224: 	    return -1;
                   11225: 	}
                   11226: 	if ($info < $fileinfo[9]) {
1.828     www      11227: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11228: 	    return 'ok';
1.828     www      11229: 	} else {
                   11230: # the file is outdated, get rid of it
                   11231: 	    unlink($file);
1.482     albertel 11232: 	}
1.828     www      11233:     }
                   11234: # one way or the other, at this point, we don't have the file
                   11235: # construct the correct path for the file
                   11236:     my @parts = ($cdom,$cnum); 
                   11237:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11238: 	push @parts, split(/\//,$1);
                   11239:     }
                   11240:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11241:     foreach my $part (@parts) {
                   11242: 	$path .= '/'.$part;
                   11243: 	if (!-e $path) {
                   11244: 	    mkdir($path,0770);
1.482     albertel 11245: 	}
                   11246:     }
1.828     www      11247: # now the path exists for sure
                   11248: # get a user agent
                   11249:     my $ua=new LWP::UserAgent;
                   11250:     my $transferfile=$file.'.in.transfer';
                   11251: # FIXME: this should flock
                   11252:     if (-e $transferfile) { return 'ok'; }
                   11253:     my $request;
                   11254:     $uri=~s/^\///;
1.980     raeburn  11255:     my $homeserver = &homeserver($cnum,$cdom);
                   11256:     my $protocol = $protocol{$homeserver};
                   11257:     $protocol = 'http' if ($protocol ne 'https');
                   11258:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11259:     my $response=$ua->request($request,$transferfile);
                   11260: # did it work?
                   11261:     if ($response->is_error()) {
                   11262: 	unlink($transferfile);
                   11263: 	&logthis("Userfile repcopy failed for $uri");
                   11264: 	return -1;
                   11265:     }
                   11266: # worked, rename the transfer file
                   11267:     rename($transferfile,$file);
1.607     raeburn  11268:     return 'ok';
1.481     raeburn  11269: }
                   11270: 
1.517     albertel 11271: sub tokenwrapper {
                   11272:     my $uri=shift;
1.980     raeburn  11273:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11274:     $uri=~s|^/||;
1.620     albertel 11275:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11276:     my $token=$1;
1.552     albertel 11277:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11278:     if ($udom && $uname && $file) {
                   11279: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11280:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11281:         my $homeserver = &homeserver($uname,$udom);
                   11282:         my $protocol = $protocol{$homeserver};
                   11283:         $protocol = 'http' if ($protocol ne 'https');
                   11284:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11285:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11286:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11287:     } else {
                   11288:         return '/adm/notfound.html';
                   11289:     }
                   11290: }
                   11291: 
1.828     www      11292: # call with reqtype HEAD: get last modification time
                   11293: # call with reqtype GET: get the file contents
                   11294: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11295: #
1.481     raeburn  11296: sub getuploaded {
                   11297:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11298:     $uri=~s/^\///;
1.980     raeburn  11299:     my $homeserver = &homeserver($cnum,$cdom);
                   11300:     my $protocol = $protocol{$homeserver};
                   11301:     $protocol = 'http' if ($protocol ne 'https');
                   11302:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11303:     my $ua=new LWP::UserAgent;
                   11304:     my $request=new HTTP::Request($reqtype,$uri);
                   11305:     my $response=$ua->request($request);
                   11306:     $$rtncode = $response->code;
1.482     albertel 11307:     if (! $response->is_success()) {
                   11308: 	return 'failed';
                   11309:     }      
                   11310:     if ($reqtype eq 'HEAD') {
1.486     www      11311: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11312:     } elsif ($reqtype eq 'GET') {
                   11313: 	$$info = $response->content;
1.472     albertel 11314:     }
1.482     albertel 11315:     return 'ok';
1.36      albertel 11316: }
                   11317: 
1.481     raeburn  11318: sub readfile {
                   11319:     my $file = shift;
                   11320:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11321:     my $fh;
                   11322:     open($fh,"<$file");
                   11323:     my $a='';
1.800     albertel 11324:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11325:     return $a;
                   11326: }
                   11327: 
1.36      albertel 11328: sub filelocation {
1.590     banghart 11329:     my ($dir,$file) = @_;
                   11330:     my $location;
                   11331:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11332: 
                   11333:     if ($file =~ m-^/adm/-) {
                   11334: 	$file=~s-^/adm/wrapper/-/-;
                   11335: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11336:     }
1.882     albertel 11337: 
1.1139    www      11338:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11339:         $location = $file;
1.609     banghart 11340:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11341:         my ($udom,$uname,$filename)=
1.811     albertel 11342:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11343:         my $home=&homeserver($uname,$udom);
                   11344:         my $is_me=0;
                   11345:         my @ids=&current_machine_ids();
                   11346:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11347:         if ($is_me) {
1.1117    foxr     11348:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11349:         } else {
                   11350:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11351:   	      $udom.'/'.$uname.'/'.$filename;
                   11352:         }
1.882     albertel 11353:     } elsif ($file =~ m-^/adm/-) {
                   11354: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11355:     } else {
                   11356:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11357:         $file=~s:^/(res|priv)/:/:;
                   11358:         my $space=$1;
1.590     banghart 11359:         if ( !( $file =~ m:^/:) ) {
                   11360:             $location = $dir. '/'.$file;
                   11361:         } else {
1.1142    raeburn  11362:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11363:         }
1.59      albertel 11364:     }
1.590     banghart 11365:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11366:     while ($location=~m{/\.\./}) {
                   11367: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11368: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11369: 	} else {
                   11370: 	    $location=~ s{/\.\./}{/}g;
                   11371: 	}
                   11372:     } #remove dir/..
1.590     banghart 11373:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11374:     return $location;
1.46      www      11375: }
1.36      albertel 11376: 
1.46      www      11377: sub hreflocation {
                   11378:     my ($dir,$file)=@_;
1.980     raeburn  11379:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11380: 	$file=filelocation($dir,$file);
1.700     albertel 11381:     } elsif ($file=~m-^/adm/-) {
                   11382: 	$file=~s-^/adm/wrapper/-/-;
                   11383: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11384:     }
                   11385:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11386: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11387:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11388: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11389: 	        {/uploaded/$1/$2/}x;
1.46      www      11390:     }
1.913     albertel 11391:     if ($file=~ m{^/userfiles/}) {
                   11392: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11393:     }
1.462     albertel 11394:     return $file;
1.465     albertel 11395: }
                   11396: 
1.1139    www      11397: 
                   11398: 
                   11399: 
                   11400: 
1.465     albertel 11401: sub current_machine_domains {
1.853     albertel 11402:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11403: }
                   11404: 
                   11405: sub machine_domains {
                   11406:     my ($hostname) = @_;
1.465     albertel 11407:     my @domains;
1.838     albertel 11408:     my %hostname = &all_hostnames();
1.465     albertel 11409:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11410: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11411: 	if ($hostname eq $name) {
1.844     albertel 11412: 	    push(@domains,&host_domain($id));
1.465     albertel 11413: 	}
                   11414:     }
                   11415:     return @domains;
                   11416: }
                   11417: 
                   11418: sub current_machine_ids {
1.853     albertel 11419:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11420: }
                   11421: 
                   11422: sub machine_ids {
                   11423:     my ($hostname) = @_;
                   11424:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11425:     my @ids;
1.888     albertel 11426:     my %name_to_host = &all_names();
1.889     albertel 11427:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11428: 	return @{ $name_to_host{$hostname} };
                   11429:     }
                   11430:     return;
1.31      www      11431: }
                   11432: 
1.824     raeburn  11433: sub additional_machine_domains {
                   11434:     my @domains;
                   11435:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11436:     while( my $line = <$fh>) {
                   11437:         $line =~ s/\s//g;
                   11438:         push(@domains,$line);
                   11439:     }
                   11440:     return @domains;
                   11441: }
                   11442: 
                   11443: sub default_login_domain {
                   11444:     my $domain = $perlvar{'lonDefDomain'};
                   11445:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11446:     foreach my $posdom (&current_machine_domains(),
                   11447:                         &additional_machine_domains()) {
                   11448:         if (lc($posdom) eq lc($testdomain)) {
                   11449:             $domain=$posdom;
                   11450:             last;
                   11451:         }
                   11452:     }
                   11453:     return $domain;
                   11454: }
                   11455: 
1.31      www      11456: # ------------------------------------------------------------- Declutters URLs
                   11457: 
                   11458: sub declutter {
                   11459:     my $thisfn=shift;
1.569     albertel 11460:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11461:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11462:     $thisfn=~s/^\///;
1.697     albertel 11463:     $thisfn=~s|^adm/wrapper/||;
                   11464:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11465:     $thisfn=~s/^res\///;
1.1172    bisitz   11466:     $thisfn=~s/^priv\///;
1.1032    raeburn  11467:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11468:         $thisfn=~s/\?.+$//;
                   11469:     }
1.268     www      11470:     return $thisfn;
                   11471: }
                   11472: 
                   11473: # ------------------------------------------------------------- Clutter up URLs
                   11474: 
                   11475: sub clutter {
                   11476:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11477:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11478: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11479:        $thisfn='/res'.$thisfn; 
                   11480:     }
1.1031    raeburn  11481:     if ($thisfn !~m|^/adm|) {
                   11482: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11483: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11484: 	} else {
                   11485: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11486: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11487: 	    if ($embstyle eq 'ssi'
                   11488: 		|| ($embstyle eq 'hdn')
                   11489: 		|| ($embstyle eq 'rat')
                   11490: 		|| ($embstyle eq 'prv')
                   11491: 		|| ($embstyle eq 'ign')) {
                   11492: 		#do nothing with these
                   11493: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11494: 		|| ($embstyle eq 'emb')
                   11495: 		|| ($embstyle eq 'wrp')) {
                   11496: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11497: 	    } elsif ($embstyle eq 'unk'
                   11498: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11499: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11500: 	    } else {
1.718     www      11501: #		&logthis("Got a blank emb style");
1.695     albertel 11502: 	    }
1.694     albertel 11503: 	}
                   11504:     }
1.31      www      11505:     return $thisfn;
1.12      www      11506: }
                   11507: 
1.787     albertel 11508: sub clutter_with_no_wrapper {
                   11509:     my $uri = &clutter(shift);
                   11510:     if ($uri =~ m-^/adm/-) {
                   11511: 	$uri =~ s-^/adm/wrapper/-/-;
                   11512: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11513:     }
                   11514:     return $uri;
                   11515: }
                   11516: 
1.557     albertel 11517: sub freeze_escape {
                   11518:     my ($value)=@_;
                   11519:     if (ref($value)) {
                   11520: 	$value=&nfreeze($value);
                   11521: 	return '__FROZEN__'.&escape($value);
                   11522:     }
                   11523:     return &escape($value);
                   11524: }
                   11525: 
1.11      www      11526: 
1.557     albertel 11527: sub thaw_unescape {
                   11528:     my ($value)=@_;
                   11529:     if ($value =~ /^__FROZEN__/) {
                   11530: 	substr($value,0,10,undef);
                   11531: 	$value=&unescape($value);
                   11532: 	return &thaw($value);
                   11533:     }
                   11534:     return &unescape($value);
                   11535: }
                   11536: 
1.436     albertel 11537: sub correct_line_ends {
                   11538:     my ($result)=@_;
                   11539:     $$result =~s/\r\n/\n/mg;
                   11540:     $$result =~s/\r/\n/mg;
1.415     albertel 11541: }
1.1       albertel 11542: # ================================================================ Main Program
                   11543: 
1.184     www      11544: sub goodbye {
1.204     albertel 11545:    &logthis("Starting Shut down");
1.443     albertel 11546: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11547:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11548: #converted
1.599     albertel 11549: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11550:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11551: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11552: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11553: #1.1 only
1.870     albertel 11554: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11555: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11556: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11557: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11558:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11559:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11560:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11561:    &flushcourselogs();
                   11562:    &logthis("Shutting down");
                   11563: }
                   11564: 
1.852     albertel 11565: sub get_dns {
1.1210    raeburn  11566:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11567:     if (!$ignore_cache) {
                   11568: 	my ($content,$cached)=
                   11569: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11570: 	if ($cached) {
1.1210    raeburn  11571: 	    &$func($content,$hashref);
1.869     albertel 11572: 	    return;
                   11573: 	}
                   11574:     }
                   11575: 
                   11576:     my %alldns;
1.852     albertel 11577:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11578:     foreach my $dns (<$config>) {
                   11579: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11580:         my $line = $1;
                   11581:         my ($host,$protocol) = split(/:/,$line);
                   11582:         if ($protocol ne 'https') {
                   11583:             $protocol = 'http';
                   11584:         }
                   11585: 	$alldns{$host} = $protocol;
1.869     albertel 11586:     }
                   11587:     while (%alldns) {
                   11588: 	my ($dns) = keys(%alldns);
1.852     albertel 11589: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11590:         $ua->timeout(30);
1.979     raeburn  11591: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11592: 	my $response=$ua->request($request);
1.979     raeburn  11593:         delete($alldns{$dns});
1.852     albertel 11594: 	next if ($response->is_error());
                   11595: 	my @content = split("\n",$response->content);
1.1210    raeburn  11596: 	unless ($nocache) {
                   11597: 	    &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
                   11598: 	}
                   11599: 	&$func(\@content,$hashref);
1.869     albertel 11600: 	return;
1.852     albertel 11601:     }
                   11602:     close($config);
1.871     albertel 11603:     my $which = (split('/',$url))[3];
                   11604:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11605:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11606:     my @content = <$config>;
1.1210    raeburn  11607:     &$func(\@content,$hashref);
                   11608:     return;
                   11609: }
                   11610: 
                   11611: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11612: sub parse_dns_checksums_tab {
1.1210    raeburn  11613:     my ($lines,$hashref) = @_;
                   11614:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11615:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11616:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11617:     my (%chksum,%revnum);
                   11618:     if (ref($lines) eq 'ARRAY') {
                   11619:         chomp(@{$lines});
                   11620:         my $versions = shift(@{$lines});
                   11621:         my %supported;
                   11622:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11623:             my $releaseslist = $1;
                   11624:             if ($releaseslist =~ /,/) {
                   11625:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11626:             } elsif ($releaseslist) {
                   11627:                 $supported{$releaseslist} = 1;
                   11628:             }
                   11629:         }
                   11630:         if ($supported{$release}) {  
                   11631:             my $matchthis = 0;
                   11632:             foreach my $line (@{$lines}) {
                   11633:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11634:                     if ($matchthis) {
                   11635:                         last;
                   11636:                     } elsif ($1 eq $release) {
                   11637:                         $matchthis = 1;
                   11638:                     }
                   11639:                 } elsif ($matchthis) {
                   11640:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11641:                     $chksum{$file} = $shasum;
                   11642:                     $revnum{$file} = $version;
                   11643:                 }
                   11644:             }
                   11645:             if (ref($hashref) eq 'HASH') {
                   11646:                 %{$hashref} = (
                   11647:                                 sums     => \%chksum,
                   11648:                                 versions => \%revnum,
                   11649:                               );
                   11650:             }
                   11651:         }
                   11652:     }
1.869     albertel 11653:     return;
1.852     albertel 11654: }
1.1210    raeburn  11655: 
                   11656: sub fetch_dns_checksums {
                   11657:     my %checksums; 
1.1211    raeburn  11658:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11659:              \%checksums);
1.1210    raeburn  11660:     return \%checksums;
                   11661: }
                   11662: 
1.327     albertel 11663: # ------------------------------------------------------------ Read domain file
                   11664: {
1.852     albertel 11665:     my $loaded;
1.846     albertel 11666:     my %domain;
                   11667: 
1.852     albertel 11668:     sub parse_domain_tab {
                   11669: 	my ($lines) = @_;
                   11670: 	foreach my $line (@$lines) {
                   11671: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11672: 
1.846     albertel 11673: 	    chomp($line);
1.852     albertel 11674: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11675: 	    my %this_domain;
                   11676: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11677: 			       'lang_def', 'city', 'longi', 'lati',
                   11678: 			       'primary') {
                   11679: 		$this_domain{$field} = shift(@elements);
                   11680: 	    }
                   11681: 	    $domain{$name} = \%this_domain;
1.852     albertel 11682: 	}
                   11683:     }
1.864     albertel 11684: 
                   11685:     sub reset_domain_info {
                   11686: 	undef($loaded);
                   11687: 	undef(%domain);
                   11688:     }
                   11689: 
1.852     albertel 11690:     sub load_domain_tab {
1.869     albertel 11691: 	my ($ignore_cache) = @_;
                   11692: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11693: 	my $fh;
                   11694: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11695: 	    my @lines = <$fh>;
                   11696: 	    &parse_domain_tab(\@lines);
1.448     albertel 11697: 	}
1.852     albertel 11698: 	close($fh);
                   11699: 	$loaded = 1;
1.327     albertel 11700:     }
1.846     albertel 11701: 
                   11702:     sub domain {
1.852     albertel 11703: 	&load_domain_tab() if (!$loaded);
                   11704: 
1.846     albertel 11705: 	my ($name,$what) = @_;
                   11706: 	return if ( !exists($domain{$name}) );
                   11707: 
                   11708: 	if (!$what) {
                   11709: 	    return $domain{$name}{'description'};
                   11710: 	}
                   11711: 	return $domain{$name}{$what};
                   11712:     }
1.974     raeburn  11713: 
                   11714:     sub domain_info {
                   11715:         &load_domain_tab() if (!$loaded);
                   11716:         return %domain;
                   11717:     }
                   11718: 
1.327     albertel 11719: }
                   11720: 
                   11721: 
1.1       albertel 11722: # ------------------------------------------------------------- Read hosts file
                   11723: {
1.838     albertel 11724:     my %hostname;
1.844     albertel 11725:     my %hostdom;
1.845     albertel 11726:     my %libserv;
1.852     albertel 11727:     my $loaded;
1.888     albertel 11728:     my %name_to_host;
1.1074    raeburn  11729:     my %internetdom;
1.1107    raeburn  11730:     my %LC_dns_serv;
1.852     albertel 11731: 
                   11732:     sub parse_hosts_tab {
                   11733: 	my ($file) = @_;
                   11734: 	foreach my $configline (@$file) {
                   11735: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11736:             chomp($configline);
                   11737: 	    if ($configline =~ /^\^/) {
                   11738:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11739:                     $LC_dns_serv{$1} = 1;
                   11740:                 }
                   11741:                 next;
                   11742:             }
1.1074    raeburn  11743: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11744: 	    $name=~s/\s//g;
                   11745: 	    if ($id && $domain && $role && $name) {
                   11746: 		$hostname{$id}=$name;
1.888     albertel 11747: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11748: 		$hostdom{$id}=$domain;
                   11749: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11750:                 if (defined($protocol)) {
                   11751:                     if ($protocol eq 'https') {
                   11752:                         $protocol{$id} = $protocol;
                   11753:                     } else {
                   11754:                         $protocol{$id} = 'http'; 
                   11755:                     }
1.968     raeburn  11756:                 } else {
1.969     raeburn  11757:                     $protocol{$id} = 'http';
1.968     raeburn  11758:                 }
1.1074    raeburn  11759:                 if (defined($intdom)) {
                   11760:                     $internetdom{$id} = $intdom;
                   11761:                 }
1.852     albertel 11762: 	    }
                   11763: 	}
                   11764:     }
1.864     albertel 11765:     
                   11766:     sub reset_hosts_info {
1.897     albertel 11767: 	&purge_remembered();
1.864     albertel 11768: 	&reset_domain_info();
                   11769: 	&reset_hosts_ip_info();
1.892     albertel 11770: 	undef(%name_to_host);
1.864     albertel 11771: 	undef(%hostname);
                   11772: 	undef(%hostdom);
                   11773: 	undef(%libserv);
                   11774: 	undef($loaded);
                   11775:     }
1.1       albertel 11776: 
1.852     albertel 11777:     sub load_hosts_tab {
1.869     albertel 11778: 	my ($ignore_cache) = @_;
                   11779: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11780: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11781: 	my @config = <$config>;
                   11782: 	&parse_hosts_tab(\@config);
                   11783: 	close($config);
                   11784: 	$loaded=1;
1.1       albertel 11785:     }
1.852     albertel 11786: 
1.838     albertel 11787:     sub hostname {
1.852     albertel 11788: 	&load_hosts_tab() if (!$loaded);
                   11789: 
1.838     albertel 11790: 	my ($lonid) = @_;
                   11791: 	return $hostname{$lonid};
                   11792:     }
1.845     albertel 11793: 
1.838     albertel 11794:     sub all_hostnames {
1.852     albertel 11795: 	&load_hosts_tab() if (!$loaded);
                   11796: 
1.838     albertel 11797: 	return %hostname;
                   11798:     }
1.845     albertel 11799: 
1.888     albertel 11800:     sub all_names {
                   11801: 	&load_hosts_tab() if (!$loaded);
                   11802: 
                   11803: 	return %name_to_host;
                   11804:     }
                   11805: 
1.974     raeburn  11806:     sub all_host_domain {
                   11807:         &load_hosts_tab() if (!$loaded);
                   11808:         return %hostdom;
                   11809:     }
                   11810: 
1.845     albertel 11811:     sub is_library {
1.852     albertel 11812: 	&load_hosts_tab() if (!$loaded);
                   11813: 
1.845     albertel 11814: 	return exists($libserv{$_[0]});
                   11815:     }
                   11816: 
                   11817:     sub all_library {
1.852     albertel 11818: 	&load_hosts_tab() if (!$loaded);
                   11819: 
1.845     albertel 11820: 	return %libserv;
                   11821:     }
                   11822: 
1.1062    droeschl 11823:     sub unique_library {
                   11824: 	#2x reverse removes all hostnames that appear more than once
                   11825:         my %unique = reverse &all_library();
                   11826:         return reverse %unique;
                   11827:     }
                   11828: 
1.841     albertel 11829:     sub get_servers {
1.852     albertel 11830: 	&load_hosts_tab() if (!$loaded);
                   11831: 
1.841     albertel 11832: 	my ($domain,$type) = @_;
                   11833: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11834: 	                                          : %hostname;
                   11835: 	my %result;
1.842     albertel 11836: 	if (ref($domain) eq 'ARRAY') {
                   11837: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11838: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11839: 		    $result{$host} = $hostname;
                   11840: 		}
                   11841: 	    }
                   11842: 	} else {
                   11843: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11844: 		if ($hostdom{$host} eq $domain) {
                   11845: 		    $result{$host} = $hostname;
                   11846: 		}
1.841     albertel 11847: 	    }
                   11848: 	}
                   11849: 	return %result;
                   11850:     }
1.845     albertel 11851: 
1.1062    droeschl 11852:     sub get_unique_servers {
                   11853:         my %unique = reverse &get_servers(@_);
                   11854: 	return reverse %unique;
                   11855:     }
                   11856: 
1.844     albertel 11857:     sub host_domain {
1.852     albertel 11858: 	&load_hosts_tab() if (!$loaded);
                   11859: 
1.844     albertel 11860: 	my ($lonid) = @_;
                   11861: 	return $hostdom{$lonid};
                   11862:     }
                   11863: 
1.841     albertel 11864:     sub all_domains {
1.852     albertel 11865: 	&load_hosts_tab() if (!$loaded);
                   11866: 
1.841     albertel 11867: 	my %seen;
                   11868: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11869: 	return @uniq;
                   11870:     }
1.1074    raeburn  11871: 
                   11872:     sub internet_dom {
                   11873:         &load_hosts_tab() if (!$loaded);
                   11874: 
                   11875:         my ($lonid) = @_;
                   11876:         return $internetdom{$lonid};
                   11877:     }
1.1107    raeburn  11878: 
                   11879:     sub is_LC_dns {
                   11880:         &load_hosts_tab() if (!$loaded);
                   11881: 
                   11882:         my ($hostname) = @_;
                   11883:         return exists($LC_dns_serv{$hostname});
                   11884:     }
                   11885: 
1.1       albertel 11886: }
                   11887: 
1.847     albertel 11888: { 
                   11889:     my %iphost;
1.856     albertel 11890:     my %name_to_ip;
                   11891:     my %lonid_to_ip;
1.869     albertel 11892: 
1.847     albertel 11893:     sub get_hosts_from_ip {
                   11894: 	my ($ip) = @_;
                   11895: 	my %iphosts = &get_iphost();
                   11896: 	if (ref($iphosts{$ip})) {
                   11897: 	    return @{$iphosts{$ip}};
                   11898: 	}
                   11899: 	return;
1.839     albertel 11900:     }
1.864     albertel 11901:     
                   11902:     sub reset_hosts_ip_info {
                   11903: 	undef(%iphost);
                   11904: 	undef(%name_to_ip);
                   11905: 	undef(%lonid_to_ip);
                   11906:     }
1.856     albertel 11907: 
                   11908:     sub get_host_ip {
                   11909: 	my ($lonid) = @_;
                   11910: 	if (exists($lonid_to_ip{$lonid})) {
                   11911: 	    return $lonid_to_ip{$lonid};
                   11912: 	}
                   11913: 	my $name=&hostname($lonid);
                   11914:    	my $ip = gethostbyname($name);
                   11915: 	return if (!$ip || length($ip) ne 4);
                   11916: 	$ip=inet_ntoa($ip);
                   11917: 	$name_to_ip{$name}   = $ip;
                   11918: 	$lonid_to_ip{$lonid} = $ip;
                   11919: 	return $ip;
                   11920:     }
1.847     albertel 11921:     
                   11922:     sub get_iphost {
1.869     albertel 11923: 	my ($ignore_cache) = @_;
1.894     albertel 11924: 
1.869     albertel 11925: 	if (!$ignore_cache) {
                   11926: 	    if (%iphost) {
                   11927: 		return %iphost;
                   11928: 	    }
                   11929: 	    my ($ip_info,$cached)=
                   11930: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11931: 	    if ($cached) {
                   11932: 		%iphost      = %{$ip_info->[0]};
                   11933: 		%name_to_ip  = %{$ip_info->[1]};
                   11934: 		%lonid_to_ip = %{$ip_info->[2]};
                   11935: 		return %iphost;
                   11936: 	    }
                   11937: 	}
1.894     albertel 11938: 
                   11939: 	# get yesterday's info for fallback
                   11940: 	my %old_name_to_ip;
                   11941: 	my ($ip_info,$cached)=
                   11942: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11943: 	if ($cached) {
                   11944: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11945: 	}
                   11946: 
1.888     albertel 11947: 	my %name_to_host = &all_names();
                   11948: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11949: 	    my $ip;
                   11950: 	    if (!exists($name_to_ip{$name})) {
                   11951: 		$ip = gethostbyname($name);
                   11952: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11953: 		    if (defined($old_name_to_ip{$name})) {
                   11954: 			$ip = $old_name_to_ip{$name};
                   11955: 			&logthis("Can't find $name defaulting to old $ip");
                   11956: 		    } else {
                   11957: 			&logthis("Name $name no IP found");
                   11958: 			next;
                   11959: 		    }
                   11960: 		} else {
                   11961: 		    $ip=inet_ntoa($ip);
1.847     albertel 11962: 		}
                   11963: 		$name_to_ip{$name} = $ip;
                   11964: 	    } else {
                   11965: 		$ip = $name_to_ip{$name};
1.653     albertel 11966: 	    }
1.888     albertel 11967: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11968: 		$lonid_to_ip{$id} = $ip;
                   11969: 	    }
                   11970: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11971: 	}
1.869     albertel 11972: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11973: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11974: 				      48*60*60);
1.869     albertel 11975: 
1.847     albertel 11976: 	return %iphost;
1.598     albertel 11977:     }
                   11978: 
1.992     raeburn  11979:     #
                   11980:     #  Given a DNS returns the loncapa host name for that DNS 
                   11981:     # 
                   11982:     sub host_from_dns {
                   11983:         my ($dns) = @_;
                   11984:         my @hosts;
                   11985:         my $ip;
                   11986: 
1.993     raeburn  11987:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11988:             $ip = $name_to_ip{$dns};
                   11989:         }
                   11990:         if (!$ip) {
                   11991:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11992:             if (length($ip) == 4) { 
                   11993: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11994:             }
                   11995:         }
                   11996:         if ($ip) {
                   11997: 	    @hosts = get_hosts_from_ip($ip);
                   11998: 	    return $hosts[0];
                   11999:         }
                   12000:         return undef;
1.986     foxr     12001:     }
1.992     raeburn  12002: 
1.1074    raeburn  12003:     sub get_internet_names {
                   12004:         my ($lonid) = @_;
                   12005:         return if ($lonid eq '');
                   12006:         my ($idnref,$cached)=
                   12007:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12008:         if ($cached) {
                   12009:             return $idnref;
                   12010:         }
                   12011:         my $ip = &get_host_ip($lonid);
                   12012:         my @hosts = &get_hosts_from_ip($ip);
                   12013:         my %iphost = &get_iphost();
                   12014:         my (@idns,%seen);
                   12015:         foreach my $id (@hosts) {
                   12016:             my $dom = &host_domain($id);
                   12017:             my $prim_id = &domain($dom,'primary');
                   12018:             my $prim_ip = &get_host_ip($prim_id);
                   12019:             next if ($seen{$prim_ip});
                   12020:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12021:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12022:                     my $intdom = &internet_dom($id);
                   12023:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12024:                         push(@idns,$intdom);
                   12025:                     }
                   12026:                 }
                   12027:             }
                   12028:             $seen{$prim_ip} = 1;
                   12029:         }
                   12030:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   12031:     }
                   12032: 
1.986     foxr     12033: }
                   12034: 
1.1079    raeburn  12035: sub all_loncaparevs {
                   12036:     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);
                   12037: }
                   12038: 
1.862     albertel 12039: BEGIN {
                   12040: 
                   12041: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12042:     unless ($readit) {
                   12043: {
                   12044:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12045:     %perlvar = (%perlvar,%{$configvars});
                   12046: }
                   12047: 
                   12048: 
1.1       albertel 12049: # ------------------------------------------------------ Read spare server file
                   12050: {
1.448     albertel 12051:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12052: 
                   12053:     while (my $configline=<$config>) {
                   12054:        chomp($configline);
1.284     matthew  12055:        if ($configline) {
1.784     albertel 12056: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12057: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12058: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12059:        }
                   12060:     }
1.448     albertel 12061:     close($config);
1.1       albertel 12062: }
1.11      www      12063: # ------------------------------------------------------------ Read permissions
                   12064: {
1.448     albertel 12065:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12066: 
                   12067:     while (my $configline=<$config>) {
1.448     albertel 12068: 	chomp($configline);
                   12069: 	if ($configline) {
                   12070: 	    my ($role,$perm)=split(/ /,$configline);
                   12071: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12072: 	}
1.11      www      12073:     }
1.448     albertel 12074:     close($config);
1.11      www      12075: }
                   12076: 
                   12077: # -------------------------------------------- Read plain texts for permissions
                   12078: {
1.448     albertel 12079:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12080: 
                   12081:     while (my $configline=<$config>) {
1.448     albertel 12082: 	chomp($configline);
                   12083: 	if ($configline) {
1.742     raeburn  12084: 	    my ($short,@plain)=split(/:/,$configline);
                   12085:             %{$prp{$short}} = ();
                   12086: 	    if (@plain > 0) {
                   12087:                 $prp{$short}{'std'} = $plain[0];
                   12088:                 for (my $i=1; $i<@plain; $i++) {
                   12089:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12090:                 }
                   12091:             }
1.448     albertel 12092: 	}
1.135     www      12093:     }
1.448     albertel 12094:     close($config);
1.135     www      12095: }
                   12096: 
                   12097: # ---------------------------------------------------------- Read package table
                   12098: {
1.448     albertel 12099:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12100: 
                   12101:     while (my $configline=<$config>) {
1.483     albertel 12102: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12103: 	chomp($configline);
                   12104: 	my ($short,$plain)=split(/:/,$configline);
                   12105: 	my ($pack,$name)=split(/\&/,$short);
                   12106: 	if ($plain ne '') {
                   12107: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12108: 	    $packagetab{$short}=$plain; 
                   12109: 	}
1.11      www      12110:     }
1.448     albertel 12111:     close($config);
1.329     matthew  12112: }
                   12113: 
1.1073    raeburn  12114: # ---------------------------------------------------------- Read loncaparev table
                   12115: {
                   12116:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12117:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12118:             while (my $configline=<$config>) {
                   12119:                 chomp($configline);
                   12120:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12121:                 $loncaparevs{$hostid}=$loncaparev;
                   12122:             }
                   12123:             close($config);
                   12124:         }
                   12125:     }
                   12126: }
                   12127: 
1.1074    raeburn  12128: # ---------------------------------------------------------- Read serverhostID table
                   12129: {
                   12130:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12131:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12132:             while (my $configline=<$config>) {
                   12133:                 chomp($configline);
                   12134:                 my ($name,$id)=split(/:/,$configline);
                   12135:                 $serverhomeIDs{$name}=$id;
                   12136:             }
                   12137:             close($config);
                   12138:         }
                   12139:     }
                   12140: }
                   12141: 
1.1079    raeburn  12142: {
                   12143:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12144:     if (-e $file) {
                   12145:         my $parser = HTML::LCParser->new($file);
                   12146:         while (my $token = $parser->get_token()) {
                   12147:             if ($token->[0] eq 'S') {
                   12148:                 my $item = $token->[1];
                   12149:                 my $name = $token->[2]{'name'};
                   12150:                 my $value = $token->[2]{'value'};
                   12151:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12152:                     my $release = $parser->get_text();
                   12153:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12154:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12155:                 }
                   12156:             }
                   12157:         }
                   12158:     }
1.1073    raeburn  12159: }
                   12160: 
1.1138    raeburn  12161: # ---------------------------------------------------------- Read managers table
                   12162: {
                   12163:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12164:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12165:             while (my $configline=<$config>) {
                   12166:                 chomp($configline);
                   12167:                 next if ($configline =~ /^\#/);
                   12168:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12169:                     $managerstab{$configline} = 1;
                   12170:                 }
                   12171:             }
                   12172:             close($config);
                   12173:         }
                   12174:     }
                   12175: }
                   12176: 
1.329     matthew  12177: # ------------- set up temporary directory
                   12178: {
1.1117    foxr     12179:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12180: 
1.11      www      12181: }
                   12182: 
1.794     albertel 12183: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12184: 				'compress_threshold'=> 20_000,
                   12185:  			        });
1.185     www      12186: 
1.281     www      12187: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12188: $dumpcount=0;
1.958     www      12189: $locknum=0;
1.22      www      12190: 
1.163     harris41 12191: &logtouch();
1.672     albertel 12192: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12193: $readit=1;
1.564     albertel 12194:     {
                   12195: 	use integer;
                   12196: 	my $test=(2**32)+1;
1.568     albertel 12197: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12198: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12199:     }
1.195     www      12200: }
1.1       albertel 12201: }
1.179     www      12202: 
1.1       albertel 12203: 1;
1.191     harris41 12204: __END__
                   12205: 
1.243     albertel 12206: =pod
                   12207: 
1.191     harris41 12208: =head1 NAME
                   12209: 
1.243     albertel 12210: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12211: 
                   12212: =head1 SYNOPSIS
                   12213: 
1.243     albertel 12214: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12215: 
                   12216:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12217: 
1.243     albertel 12218: Common parameters:
                   12219: 
                   12220: =over 4
                   12221: 
                   12222: =item *
                   12223: 
                   12224: $uname : an internal username (if $cname expecting a course Id specifically)
                   12225: 
                   12226: =item *
                   12227: 
                   12228: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12229: 
                   12230: =item *
                   12231: 
                   12232: $symb : a resource instance identifier
                   12233: 
                   12234: =item *
                   12235: 
                   12236: $namespace : the name of a .db file that contains the data needed or
                   12237: being set.
                   12238: 
                   12239: =back
                   12240: 
1.394     bowersj2 12241: =head1 OVERVIEW
1.191     harris41 12242: 
1.394     bowersj2 12243: lonnet provides subroutines which interact with the
                   12244: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12245: about classes, users, and resources.
1.243     albertel 12246: 
                   12247: For many of these objects you can also use this to store data about
                   12248: them or modify them in various ways.
1.191     harris41 12249: 
1.394     bowersj2 12250: =head2 Symbs
1.191     harris41 12251: 
1.394     bowersj2 12252: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12253: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12254: map, the resource number of the resource in the map, and the URL of
                   12255: the resource itself. The latter is somewhat redundant, but might help
                   12256: if maps change.
                   12257: 
                   12258: An example is
                   12259: 
                   12260:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12261: 
                   12262: The respective map entry is
                   12263: 
                   12264:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12265:   title="Problem 2">
                   12266:  </resource>
                   12267: 
                   12268: Symbs are used by the random number generator, as well as to store and
                   12269: restore data specific to a certain instance of for example a problem.
                   12270: 
                   12271: =head2 Storing And Retrieving Data
                   12272: 
                   12273: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12274: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12275: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12276: is is the non-critical message twin of cstore. These functions are for
                   12277: handlers to store a perl hash to a user's permanent data space in an
                   12278: easy manner, and to retrieve it again on another call. It is expected
                   12279: that a handler would use this once at the beginning to retrieve data,
                   12280: and then again once at the end to send only the new data back.
                   12281: 
                   12282: The data is stored in the user's data directory on the user's
                   12283: homeserver under the ID of the course.
                   12284: 
                   12285: The hash that is returned by restore will have all of the previous
                   12286: value for all of the elements of the hash.
                   12287: 
                   12288: Example:
                   12289: 
                   12290:  #creating a hash
                   12291:  my %hash;
                   12292:  $hash{'foo'}='bar';
                   12293: 
                   12294:  #storing it
                   12295:  &Apache::lonnet::cstore(\%hash);
                   12296: 
                   12297:  #changing a value
                   12298:  $hash{'foo'}='notbar';
                   12299: 
                   12300:  #adding a new value
                   12301:  $hash{'bar'}='foo';
                   12302:  &Apache::lonnet::cstore(\%hash);
                   12303: 
                   12304:  #retrieving the hash
                   12305:  my %history=&Apache::lonnet::restore();
                   12306: 
                   12307:  #print the hash
                   12308:  foreach my $key (sort(keys(%history))) {
                   12309:    print("\%history{$key} = $history{$key}");
                   12310:  }
                   12311: 
                   12312: Will print out:
1.191     harris41 12313: 
1.394     bowersj2 12314:  %history{1:foo} = bar
                   12315:  %history{1:keys} = foo:timestamp
                   12316:  %history{1:timestamp} = 990455579
                   12317:  %history{2:bar} = foo
                   12318:  %history{2:foo} = notbar
                   12319:  %history{2:keys} = foo:bar:timestamp
                   12320:  %history{2:timestamp} = 990455580
                   12321:  %history{bar} = foo
                   12322:  %history{foo} = notbar
                   12323:  %history{timestamp} = 990455580
                   12324:  %history{version} = 2
                   12325: 
                   12326: Note that the special hash entries C<keys>, C<version> and
                   12327: C<timestamp> were added to the hash. C<version> will be equal to the
                   12328: total number of versions of the data that have been stored. The
                   12329: C<timestamp> attribute will be the UNIX time the hash was
                   12330: stored. C<keys> is available in every historical section to list which
                   12331: keys were added or changed at a specific historical revision of a
                   12332: hash.
                   12333: 
                   12334: B<Warning>: do not store the hash that restore returns directly. This
                   12335: will cause a mess since it will restore the historical keys as if the
                   12336: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12337: 
1.394     bowersj2 12338: Calling convention:
1.191     harris41 12339: 
1.394     bowersj2 12340:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12341:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12342: 
1.394     bowersj2 12343: For more detailed information, see lonnet specific documentation.
1.191     harris41 12344: 
1.394     bowersj2 12345: =head1 RETURN MESSAGES
1.191     harris41 12346: 
1.394     bowersj2 12347: =over 4
1.191     harris41 12348: 
1.394     bowersj2 12349: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12350: 
1.394     bowersj2 12351: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12352: when the connection is brought back up
1.191     harris41 12353: 
1.394     bowersj2 12354: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12355: for later delivery
1.191     harris41 12356: 
1.967     bisitz   12357: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12358: 
1.394     bowersj2 12359: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12360: that was requested
1.191     harris41 12361: 
1.243     albertel 12362: =back
1.191     harris41 12363: 
1.243     albertel 12364: =head1 PUBLIC SUBROUTINES
1.191     harris41 12365: 
1.243     albertel 12366: =head2 Session Environment Functions
1.191     harris41 12367: 
1.243     albertel 12368: =over 4
1.191     harris41 12369: 
1.394     bowersj2 12370: =item * 
                   12371: X<appenv()>
1.949     raeburn  12372: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12373: the user envirnoment file, and will be restored for each access this
1.620     albertel 12374: user makes during this session, also modifies the %env for the current
1.949     raeburn  12375: process. Optional rolesarrayref - if defined contains a reference to an array
                   12376: of roles which are exempt from the restriction on modifying user.role entries 
                   12377: in the user's environment.db and in %env.    
1.191     harris41 12378: 
                   12379: =item *
1.394     bowersj2 12380: X<delenv()>
1.987     raeburn  12381: B<delenv($delthis,$regexp)>: removes all items from the session
                   12382: environment file that begin with $delthis. If the 
                   12383: optional second arg - $regexp - is true, $delthis is treated as a 
                   12384: regular expression, otherwise \Q$delthis\E is used. 
                   12385: The values are also deleted from the current processes %env.
1.191     harris41 12386: 
1.795     albertel 12387: =item * get_env_multiple($name) 
                   12388: 
                   12389: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12390: values may be defined and end up as an array ref.
                   12391: 
                   12392: returns an array of values
                   12393: 
1.243     albertel 12394: =back
                   12395: 
                   12396: =head2 User Information
1.191     harris41 12397: 
1.243     albertel 12398: =over 4
1.191     harris41 12399: 
                   12400: =item *
1.394     bowersj2 12401: X<queryauthenticate()>
                   12402: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12403: authentication scheme
                   12404: 
                   12405: =item *
1.394     bowersj2 12406: X<authenticate()>
1.1073    raeburn  12407: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12408: authenticate user from domain's lib servers (first use the current
                   12409: one). C<$upass> should be the users password.
1.1073    raeburn  12410: $checkdefauth is optional (value is 1 if a check should be made to
                   12411:    authenticate user using default authentication method, and allow
                   12412:    account creation if username does not have account in the domain).
                   12413: $clientcancheckhost is optional (value is 1 if checking whether the
                   12414:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12415: 
                   12416: =item *
1.394     bowersj2 12417: X<homeserver()>
                   12418: B<homeserver($uname,$udom)>: find the server which has
                   12419: the user's directory and files (there must be only one), this caches
                   12420: the answer, and also caches if there is a borken connection.
1.191     harris41 12421: 
                   12422: =item *
1.394     bowersj2 12423: X<idget()>
                   12424: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12425: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12426: username, and only 1 username per ID in a specific domain) (returns
                   12427: hash: id=>name,id=>name)
1.191     harris41 12428: 
                   12429: =item *
1.394     bowersj2 12430: X<idrget()>
                   12431: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12432: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12433: 
                   12434: =item *
1.394     bowersj2 12435: X<idput()>
                   12436: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12437: 
                   12438: =item *
1.394     bowersj2 12439: X<rolesinit()>
1.1169    droeschl 12440: B<rolesinit($udom,$username)>: get user privileges.
                   12441: returns user role, first access and timer interval hashes
1.243     albertel 12442: 
                   12443: =item *
1.1171    droeschl 12444: X<privileged()>
                   12445: B<privileged($username,$domain)>: returns a true if user has a
                   12446: privileged and active role (i.e. su or dc), false otherwise.
                   12447: 
                   12448: =item *
1.551     albertel 12449: X<getsection()>
                   12450: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12451: course $cname, return section name/number or '' for "not in course"
                   12452: and '-1' for "no section"
                   12453: 
                   12454: =item *
1.394     bowersj2 12455: X<userenvironment()>
                   12456: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12457: passed in @what from the requested user's environment, returns a hash
                   12458: 
1.858     raeburn  12459: =item * 
                   12460: X<userlog_query()>
1.859     albertel 12461: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12462: activity.log file. %filters defines filters applied when parsing the
                   12463: log file. These can be start or end timestamps, or the type of action
                   12464: - log to look for Login or Logout events, check for Checkin or
                   12465: Checkout, role for role selection. The response is in the form
                   12466: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12467: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12468: 
1.243     albertel 12469: =back
                   12470: 
                   12471: =head2 User Roles
                   12472: 
                   12473: =over 4
                   12474: 
                   12475: =item *
                   12476: 
1.810     raeburn  12477: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12478:  F: full access
                   12479:  U,I,K: authentication modes (cxx only)
                   12480:  '': forbidden
                   12481:  1: user needs to choose course
                   12482:  2: browse allowed
1.766     albertel 12483:  A: passphrase authentication needed
1.243     albertel 12484: 
                   12485: =item *
                   12486: 
1.1192    raeburn  12487: constructaccess($url,$setpriv) : check for access to construction space URL
                   12488: 
                   12489: See if the owner domain and name in the URL match those in the
                   12490: expected environment.  If so, return three element list
                   12491: ($ownername,$ownerdomain,$ownerhome).
                   12492: 
                   12493: Otherwise return the null string.
                   12494: 
                   12495: If second argument 'setpriv' is true, it assigns the privileges,
                   12496: and returns the same three element list, unless the owner has
                   12497: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12498: in which case the null string is returned.
                   12499: 
                   12500: =item *
                   12501: 
1.243     albertel 12502: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12503: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12504: and course level
                   12505: 
                   12506: =item *
                   12507: 
1.988     raeburn  12508: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12509: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12510: $type is Course (default) or Community.
1.988     raeburn  12511: If $forcedefault evaluates to true, text returned will be default 
                   12512: text for $type. Otherwise, if this is a course, the text returned 
                   12513: will be a custom name for the role (if defined in the course's 
                   12514: environment).  If no custom name is defined the default is returned.
                   12515:    
1.832     raeburn  12516: =item *
                   12517: 
1.935     raeburn  12518: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12519: All arguments are optional. Returns a hash of a roles, either for
                   12520: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12521: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12522: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12523: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12524: For each key, value is set to colon-separated start and end times for
                   12525: the role.  If no username and domain are specified, will default to
1.934     raeburn  12526: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12527: of role statuses (active, future or previous), roles 
                   12528: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12529: to restrict the list of roles reported. If no array ref is 
                   12530: provided for types, will default to return only active roles.
1.834     albertel 12531: 
1.1195    raeburn  12532: =item *
                   12533: 
                   12534: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12535: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12536: 
                   12537: Additional optional arguments are: $type (if role checking is to be restricted 
                   12538: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12539: available roles) or future (roles available in the future), and
                   12540: $hideprivileged -- if true will not report course roles for users who
                   12541: have active Domain Coordinator or Super User roles.
                   12542: 
1.243     albertel 12543: =back
                   12544: 
                   12545: =head2 User Modification
                   12546: 
                   12547: =over 4
                   12548: 
                   12549: =item *
                   12550: 
1.957     raeburn  12551: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12552: user for the level given by URL.  Optional start and end dates (leave empty
                   12553: string or zero for "no date")
1.191     harris41 12554: 
                   12555: =item *
                   12556: 
1.243     albertel 12557: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12558: change a users, password, possible return values are: ok,
                   12559: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12560: refused
1.191     harris41 12561: 
                   12562: =item *
                   12563: 
1.243     albertel 12564: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12565: 
                   12566: =item *
                   12567: 
1.1058    raeburn  12568: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12569:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12570: 
                   12571: will update user information (firstname,middlename,lastname,generation,
                   12572: permanentemail), and if forceid is true, student/employee ID also.
                   12573: A user's institutional affiliation(s) can also be updated.
                   12574: User information fields will not be overwritten with empty entries 
                   12575: unless the field is included in the $candelete array reference.
                   12576: This array is included when a single user is modified via "Manage Users",
                   12577: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12578: 
                   12579: =item *
                   12580: 
1.286     matthew  12581: modifystudent
                   12582: 
1.957     raeburn  12583: modify a student's enrollment and identification information.
1.286     matthew  12584: The course id is resolved based on the current users environment.  
                   12585: This means the envoking user must be a course coordinator or otherwise
                   12586: associated with a course.
                   12587: 
1.297     matthew  12588: This call is essentially a wrapper for lonnet::modifyuser and
                   12589: lonnet::modify_student_enrollment
1.286     matthew  12590: 
                   12591: Inputs: 
                   12592: 
                   12593: =over 4
                   12594: 
1.957     raeburn  12595: =item B<$udom> Student's loncapa domain
1.286     matthew  12596: 
1.957     raeburn  12597: =item B<$uname> Student's loncapa login name
1.286     matthew  12598: 
1.964     bisitz   12599: =item B<$uid> Student/Employee ID
1.286     matthew  12600: 
1.957     raeburn  12601: =item B<$umode> Student's authentication mode
1.286     matthew  12602: 
1.957     raeburn  12603: =item B<$upass> Student's password
1.286     matthew  12604: 
1.957     raeburn  12605: =item B<$first> Student's first name
1.286     matthew  12606: 
1.957     raeburn  12607: =item B<$middle> Student's middle name
1.286     matthew  12608: 
1.957     raeburn  12609: =item B<$last> Student's last name
1.286     matthew  12610: 
1.957     raeburn  12611: =item B<$gene> Student's generation
1.286     matthew  12612: 
1.957     raeburn  12613: =item B<$usec> Student's section in course
1.286     matthew  12614: 
                   12615: =item B<$end> Unix time of the roles expiration
                   12616: 
                   12617: =item B<$start> Unix time of the roles start date
                   12618: 
                   12619: =item B<$forceid> If defined, allow $uid to be changed
                   12620: 
                   12621: =item B<$desiredhome> server to use as home server for student
                   12622: 
1.957     raeburn  12623: =item B<$email> Student's permanent e-mail address
                   12624: 
                   12625: =item B<$type> Type of enrollment (auto or manual)
                   12626: 
1.963     raeburn  12627: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12628: 
                   12629: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12630: 
1.963     raeburn  12631: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12632: 
1.963     raeburn  12633: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12634: 
1.963     raeburn  12635: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  12636: 
1.286     matthew  12637: =back
1.297     matthew  12638: 
                   12639: =item *
                   12640: 
                   12641: modify_student_enrollment
                   12642: 
                   12643: Change a students enrollment status in a class.  The environment variable
                   12644: 'role.request.course' must be defined for this function to proceed.
                   12645: 
                   12646: Inputs:
                   12647: 
                   12648: =over 4
                   12649: 
                   12650: =item $udom, students domain
                   12651: 
                   12652: =item $uname, students name
                   12653: 
                   12654: =item $uid, students user id
                   12655: 
                   12656: =item $first, students first name
                   12657: 
                   12658: =item $middle
                   12659: 
                   12660: =item $last
                   12661: 
                   12662: =item $gene
                   12663: 
                   12664: =item $usec
                   12665: 
                   12666: =item $end
                   12667: 
                   12668: =item $start
                   12669: 
1.957     raeburn  12670: =item $type
                   12671: 
                   12672: =item $locktype
                   12673: 
                   12674: =item $cid
                   12675: 
                   12676: =item $selfenroll
                   12677: 
                   12678: =item $context
                   12679: 
1.297     matthew  12680: =back
                   12681: 
1.191     harris41 12682: 
                   12683: =item *
                   12684: 
1.243     albertel 12685: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12686: custom role; give a custom role to a user for the level given by URL.  Specify
                   12687: name and domain of role author, and role name
1.191     harris41 12688: 
                   12689: =item *
                   12690: 
1.243     albertel 12691: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12692: 
                   12693: =item *
                   12694: 
1.243     albertel 12695: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12696: 
                   12697: =back
                   12698: 
                   12699: =head2 Course Infomation
                   12700: 
                   12701: =over 4
1.191     harris41 12702: 
                   12703: =item *
                   12704: 
1.1118    foxr     12705: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12706: specified course id, including all environment settings for the
                   12707: course, the description of the course will be in the hash under the
                   12708: key 'description'
1.191     harris41 12709: 
1.1118    foxr     12710: $options is an optional parameter that if supplied is a hash reference that controls
                   12711: what how this function works.  It has the following key/values:
                   12712: 
                   12713: =over 4
                   12714: 
                   12715: =item freshen_cache
                   12716: 
                   12717: If defined, and the environment cache for the course is valid, it is 
                   12718: returned in the returned hash.
                   12719: 
                   12720: =item one_time
                   12721: 
                   12722: If defined, the last cache time is set to _now_
                   12723: 
                   12724: =item user
                   12725: 
                   12726: If defined, the supplied username is used instead of the current user.
                   12727: 
                   12728: 
                   12729: =back
                   12730: 
1.191     harris41 12731: =item *
                   12732: 
1.624     albertel 12733: resdata($name,$domain,$type,@which) : request for current parameter
                   12734: setting for a specific $type, where $type is either 'course' or 'user',
                   12735: @what should be a list of parameters to ask about. This routine caches
                   12736: answers for 5 minutes.
1.243     albertel 12737: 
1.877     foxr     12738: =item *
                   12739: 
                   12740: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12741: data base, returning a hash that is keyed by the resource name and has
                   12742: values that are the resource value.  I believe that the timestamps and
                   12743: versions are also returned.
                   12744: 
1.243     albertel 12745: =back
                   12746: 
                   12747: =head2 Course Modification
                   12748: 
                   12749: =over 4
1.191     harris41 12750: 
                   12751: =item *
                   12752: 
1.243     albertel 12753: writecoursepref($courseid,%prefs) : write preferences (environment
                   12754: database) for a course
1.191     harris41 12755: 
                   12756: =item *
                   12757: 
1.1011    raeburn  12758: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12759: 
                   12760: =item *
                   12761: 
1.1038    raeburn  12762: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12763: 
1.1167    droeschl 12764: =item *
                   12765: 
                   12766: is_course($courseid), is_course($cdom, $cnum)
                   12767: 
                   12768: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12769: two component version $cdom, $cnum. It checks if the specified course exists.
                   12770: 
                   12771: Returns:
                   12772:     undef if the course doesn't exist, otherwise
                   12773:     in scalar context the combined courseid.
                   12774:     in list context the two components of the course identifier, domain and 
                   12775:     courseid.    
                   12776: 
1.243     albertel 12777: =back
                   12778: 
                   12779: =head2 Resource Subroutines
                   12780: 
                   12781: =over 4
1.191     harris41 12782: 
                   12783: =item *
                   12784: 
1.243     albertel 12785: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12786: 
                   12787: =item *
                   12788: 
1.243     albertel 12789: repcopy($filename) : subscribes to the requested file, and attempts to
                   12790: replicate from the owning library server, Might return
1.607     raeburn  12791: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12792: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12793: resource. Expects the local filesystem pathname
                   12794: (/home/httpd/html/res/....)
                   12795: 
                   12796: =back
                   12797: 
                   12798: =head2 Resource Information
                   12799: 
                   12800: =over 4
1.191     harris41 12801: 
                   12802: =item *
                   12803: 
1.243     albertel 12804: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12805: a vairety of different possible values, $varname should be a request
                   12806: string, and the other parameters can be used to specify who and what
                   12807: one is asking about.
                   12808: 
                   12809: Possible values for $varname are environment.lastname (or other item
                   12810: from the envirnment hash), user.name (or someother aspect about the
                   12811: user), resource.0.maxtries (or some other part and parameter of a
                   12812: resource)
1.204     albertel 12813: 
                   12814: =item *
                   12815: 
1.243     albertel 12816: directcondval($number) : get current value of a condition; reads from a state
                   12817: string
1.204     albertel 12818: 
                   12819: =item *
                   12820: 
1.243     albertel 12821: condval($condidx) : value of condition index based on state
1.204     albertel 12822: 
                   12823: =item *
                   12824: 
1.243     albertel 12825: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12826: resource's metadata, $what should be either a specific key, or either
                   12827: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12828: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12829: 
                   12830: this function automatically caches all requests
1.191     harris41 12831: 
                   12832: =item *
                   12833: 
1.243     albertel 12834: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12835: network of library servers; returns file handle of where SQL and regex results
                   12836: will be stored for query
1.191     harris41 12837: 
                   12838: =item *
                   12839: 
1.243     albertel 12840: symbread($filename) : return symbolic list entry (filename argument optional);
                   12841: returns the data handle
1.191     harris41 12842: 
                   12843: =item *
                   12844: 
1.1190    raeburn  12845: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12846: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12847: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12848: on failure, user must be in a course, as it assumes the existence of
                   12849: the course initial hash, and uses $env('request.course.id'}.  The third
                   12850: arg is an optional reference to a scalar.  If this arg is passed in the 
                   12851: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12852: encrypted; otherwise it will be null.  
1.191     harris41 12853: 
                   12854: =item *
                   12855: 
1.243     albertel 12856: symbclean($symb) : removes versions numbers from a symb, returns the
                   12857: cleaned symb
1.191     harris41 12858: 
                   12859: =item *
                   12860: 
1.243     albertel 12861: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12862: course map, user must be in a course for it to work.
1.191     harris41 12863: 
                   12864: =item *
                   12865: 
1.243     albertel 12866: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12867: 
                   12868: =item *
                   12869: 
1.243     albertel 12870: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12871: a random seed, all arguments are optional, if they aren't sent it uses the
                   12872: environment to derive them. Note: if symb isn't sent and it can't get one
                   12873: from &symbread it will use the current time as its return value
1.191     harris41 12874: 
                   12875: =item *
                   12876: 
1.243     albertel 12877: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12878: unfakeable, receipt
1.191     harris41 12879: 
                   12880: =item *
                   12881: 
1.620     albertel 12882: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12883: 
                   12884: =item *
                   12885: 
1.243     albertel 12886: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12887: 
                   12888: =item *
                   12889: 
1.243     albertel 12890: 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 12891: 
                   12892: =item *
                   12893: 
1.243     albertel 12894: 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 12895: 
                   12896: =item *
                   12897: 
1.243     albertel 12898: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12899: 
                   12900: =item *
                   12901: 
1.243     albertel 12902: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12903: forcing spreadsheet to reevaluate the resource scores next time.
                   12904: 
1.1195    raeburn  12905: =item * 
                   12906: 
1.1196    raeburn  12907: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12908: when viewing in course context.
1.1195    raeburn  12909: 
1.1196    raeburn  12910:  input: six args -- filename (decluttered), course number, course domain,
                   12911:                     url, symb (if registered) and group (if this is a 
                   12912:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  12913: 
1.1196    raeburn  12914:  output: array of five scalars --
1.1195    raeburn  12915:          $cfile -- url for file editing if editable on current server
                   12916:          $home -- homeserver of resource (i.e., for author if published,
                   12917:                                           or course if uploaded.).
                   12918:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  12919:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   12920:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  12921: 
                   12922: =item *
                   12923: 
                   12924: is_course_upload($file,$cnum,$cdom)
                   12925: 
                   12926: Used in course context to determine if current file was uploaded to 
                   12927: the course (i.e., would be found in /userfiles/docs on the course's 
                   12928: homeserver.
                   12929: 
                   12930:   input: 3 args -- filename (decluttered), course number and course domain.
                   12931:   output: boolean -- 1 if file was uploaded.
                   12932: 
1.243     albertel 12933: =back
                   12934: 
                   12935: =head2 Storing/Retreiving Data
                   12936: 
                   12937: =over 4
1.191     harris41 12938: 
                   12939: =item *
                   12940: 
1.243     albertel 12941: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12942: for this url; hashref needs to be given and should be a \%hashname; the
                   12943: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12944: be derived from the env
1.191     harris41 12945: 
                   12946: =item *
                   12947: 
1.243     albertel 12948: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12949: uses critical subroutine
1.191     harris41 12950: 
                   12951: =item *
                   12952: 
1.243     albertel 12953: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12954: all args are optional
1.191     harris41 12955: 
                   12956: =item *
                   12957: 
1.717     albertel 12958: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12959: dumps the complete (or key matching regexp) namespace into a hash
                   12960: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12961: normally &store()ed into
                   12962: 
                   12963: $range should be either an integer '100' (give me the first 100
                   12964:                                            matching records)
                   12965:               or be  two integers sperated by a - with no spaces
                   12966:                  '30-50' (give me the 30th through the 50th matching
                   12967:                           records)
                   12968: 
                   12969: 
                   12970: =item *
                   12971: 
                   12972: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12973: replaces a &store() version of data with a replacement set of data
                   12974: for a particular resource in a namespace passed in the $storehash hash 
                   12975: reference
                   12976: 
                   12977: =item *
                   12978: 
1.243     albertel 12979: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12980: works very similar to store/cstore, but all data is stored in a
                   12981: temporary location and can be reset using tmpreset, $storehash should
                   12982: be a hash reference, returns nothing on success
1.191     harris41 12983: 
                   12984: =item *
                   12985: 
1.243     albertel 12986: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12987: similar to restore, but all data is stored in a temporary location and
                   12988: can be reset using tmpreset. Returns a hash of values on success,
                   12989: error string otherwise.
1.191     harris41 12990: 
                   12991: =item *
                   12992: 
1.243     albertel 12993: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12994: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12995: 
                   12996: =item *
                   12997: 
1.243     albertel 12998: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12999: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13000: 
                   13001: =item *
                   13002: 
1.243     albertel 13003: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13004: namesp ($udom and $uname are optional)
1.191     harris41 13005: 
                   13006: =item *
                   13007: 
1.702     albertel 13008: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13009: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13010: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13011: 
1.702     albertel 13012: $range should be either an integer '100' (give me the first 100
                   13013:                                            matching records)
                   13014:               or be  two integers sperated by a - with no spaces
                   13015:                  '30-50' (give me the 30th through the 50th matching
                   13016:                           records)
1.449     matthew  13017: =item *
                   13018: 
                   13019: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13020: $store can be a scalar, an array reference, or if the amount to be 
                   13021: incremented is > 1, a hash reference.
                   13022: 
                   13023: ($udom and $uname are optional)
1.191     harris41 13024: 
                   13025: =item *
                   13026: 
1.243     albertel 13027: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13028: ($udom and $uname are optional)
1.191     harris41 13029: 
                   13030: =item *
                   13031: 
1.243     albertel 13032: cput($namespace,$storehash,$udom,$uname) : critical put
                   13033: ($udom and $uname are optional)
1.191     harris41 13034: 
                   13035: =item *
                   13036: 
1.748     albertel 13037: newput($namespace,$storehash,$udom,$uname) :
                   13038: 
                   13039: Attempts to store the items in the $storehash, but only if they don't
                   13040: currently exist, if this succeeds you can be certain that you have 
                   13041: successfully created a new key value pair in the $namespace db.
                   13042: 
                   13043: 
                   13044: Args:
                   13045:  $namespace: name of database to store values to
                   13046:  $storehash: hashref to store to the db
                   13047:  $udom: (optional) domain of user containing the db
                   13048:  $uname: (optional) name of user caontaining the db
                   13049: 
                   13050: Returns:
                   13051:  'ok' -> succeeded in storing all keys of $storehash
                   13052:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13053:                         least <key> already existed in the db (other
                   13054:                         requested keys may also already exist)
1.967     bisitz   13055:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13056:  'con_lost' -> unable to contact request server
                   13057:  'refused' -> action was not allowed by remote machine
                   13058: 
                   13059: 
                   13060: =item *
                   13061: 
1.243     albertel 13062: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13063: reference filled in from namesp (encrypts the return communication)
                   13064: ($udom and $uname are optional)
1.191     harris41 13065: 
                   13066: =item *
                   13067: 
1.243     albertel 13068: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13069: critical subroutine
                   13070: 
1.806     raeburn  13071: =item *
                   13072: 
1.860     raeburn  13073: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13074: array reference filled in from namespace found in domain level on either
                   13075: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13076: 
                   13077: =item *
                   13078: 
1.860     raeburn  13079: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13080: domain level either on specified domain server ($uhome) or primary domain 
                   13081: server ($udom and $uhome are optional)
1.806     raeburn  13082: 
1.943     raeburn  13083: =item * 
                   13084: 
                   13085: get_domain_defaults($target_domain) : returns hash with defaults for
                   13086: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13087: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13088: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13089: Values are retrieved from cache (if current), or from domain's configuration.db
                   13090: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13091: or lonTabs/domain.tab. 
                   13092: 
                   13093: %domdefaults = &get_auth_defaults($target_domain);
                   13094: 
1.243     albertel 13095: =back
                   13096: 
                   13097: =head2 Network Status Functions
                   13098: 
                   13099: =over 4
1.191     harris41 13100: 
                   13101: =item *
                   13102: 
1.1137    raeburn  13103: dirlist() : return directory list based on URI (first arg).
                   13104: 
                   13105: Inputs: 1 required, 5 optional.
                   13106: 
                   13107: =over
                   13108: 
                   13109: =item 
                   13110: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13111: 
                   13112: =item
                   13113: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13114: 
                   13115: =item
                   13116: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13117: 
                   13118: =item
                   13119: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13120: 
                   13121: =item
                   13122: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13123: 
                   13124: =item 
                   13125: $alternateRoot - path to prepend in place of path from $uri.
                   13126: 
                   13127: =back
                   13128: 
                   13129: Returns: Array of up to two items.
                   13130: 
                   13131: =over
                   13132: 
                   13133: a reference to an array of files/subdirectories
                   13134: 
                   13135: =over
                   13136: 
                   13137: Each element in the array of files/subdirectories is a & separated list of
                   13138: item name and the result of running stat on the item.  If dirlist was requested
                   13139: for a file instead of a directory, the item name will be ''. For a directory 
                   13140: listing, if the item is a metadata file, the element will end &N&M 
                   13141: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13142: default copyright set (1).  
                   13143: 
                   13144: =back
                   13145: 
                   13146: a scalar containing error condition (if encountered).
                   13147: 
                   13148: =over
                   13149: 
                   13150: =item 
                   13151: no_host (no homeserver identified for $username:$domain).
                   13152: 
                   13153: =item 
                   13154: no_such_host (server contacted for listing not identified as valid host).
                   13155: 
                   13156: =item 
                   13157: con_lost (connection to remote server failed).
                   13158: 
                   13159: =item 
                   13160: refused (invalid $username:$domain received on lond side).
                   13161: 
                   13162: =item 
                   13163: no_such_dir (directory at specified path on lond side does not exist). 
                   13164: 
                   13165: =item 
                   13166: empty (directory at specified path on lond side is empty).
                   13167: 
                   13168: =over
                   13169: 
                   13170: This is currently not encountered because the &ls3, &ls2, 
                   13171: &ls (_handler) routines on the lond side do not filter out
                   13172: . and .. from a directory listing. 
                   13173: 
                   13174: =back
                   13175: 
                   13176: =back
                   13177: 
                   13178: =back
1.191     harris41 13179: 
                   13180: =item *
                   13181: 
1.243     albertel 13182: spareserver() : find server with least workload from spare.tab
                   13183: 
1.986     foxr     13184: 
                   13185: =item *
                   13186: 
                   13187: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13188: if there is no corresponding loncapa host.
                   13189: 
1.243     albertel 13190: =back
                   13191: 
1.986     foxr     13192: 
1.243     albertel 13193: =head2 Apache Request
                   13194: 
                   13195: =over 4
1.191     harris41 13196: 
                   13197: =item *
                   13198: 
1.243     albertel 13199: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13200: localhost, posts hash
                   13201: 
                   13202: =back
                   13203: 
                   13204: =head2 Data to String to Data
                   13205: 
                   13206: =over 4
1.191     harris41 13207: 
                   13208: =item *
                   13209: 
1.243     albertel 13210: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13211: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13212: 
                   13213: =item *
                   13214: 
1.243     albertel 13215: hashref2str($hashref) : convert a hashref into a string complete with
                   13216: escaping and '=' and '&' separators, supports elements that are
                   13217: arrayrefs and hashrefs
1.191     harris41 13218: 
                   13219: =item *
                   13220: 
1.243     albertel 13221: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13222: with escaping and '&' separators, supports elements that are arrayrefs
                   13223: and hashrefs
1.191     harris41 13224: 
                   13225: =item *
                   13226: 
1.243     albertel 13227: str2hash($string) : convert string to hash using unescaping and
                   13228: splitting on '=' and '&', supports elements that are arrayrefs and
                   13229: hashrefs
1.191     harris41 13230: 
                   13231: =item *
                   13232: 
1.243     albertel 13233: str2array($string) : convert string to hash using unescaping and
                   13234: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13235: 
                   13236: =back
                   13237: 
                   13238: =head2 Logging Routines
                   13239: 
                   13240: 
                   13241: These routines allow one to make log messages in the lonnet.log and
                   13242: lonnet.perm logfiles.
1.191     harris41 13243: 
1.1119    foxr     13244: =over 4
                   13245: 
1.191     harris41 13246: =item *
                   13247: 
1.243     albertel 13248: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13249: 
                   13250: =item *
                   13251: 
1.243     albertel 13252: logthis() : append message to the normal lonnet.log file, it gets
                   13253: preiodically rolled over and deleted.
1.191     harris41 13254: 
                   13255: =item *
                   13256: 
1.243     albertel 13257: logperm() : append a permanent message to lonnet.perm.log, this log
                   13258: file never gets deleted by any automated portion of the system, only
                   13259: messages of critical importance should go in here.
                   13260: 
1.1119    foxr     13261: 
1.243     albertel 13262: =back
                   13263: 
                   13264: =head2 General File Helper Routines
                   13265: 
                   13266: =over 4
1.191     harris41 13267: 
                   13268: =item *
                   13269: 
1.481     raeburn  13270: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13271: (a) files in /uploaded
                   13272:   (i) If a local copy of the file exists - 
                   13273:       compares modification date of local copy with last-modified date for 
                   13274:       definitive version stored on home server for course. If local copy is 
                   13275:       stale, requests a new version from the home server and stores it. 
                   13276:       If the original has been removed from the home server, then local copy 
                   13277:       is unlinked.
                   13278:   (ii) If local copy does not exist -
                   13279:       requests the file from the home server and stores it. 
                   13280:   
                   13281:   If $caller is 'uploadrep':  
                   13282:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13283:     for request for files originally uploaded via DOCS. 
                   13284:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13285:   
                   13286:   Otherwise:
                   13287:      This indicates a call from the content generation phase of the request.
                   13288:      -  returns the entire contents of the file or -1.
                   13289:      
                   13290: (b) files in /res
                   13291:    - returns the entire contents of a file or -1; 
                   13292:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13293: 
1.712     albertel 13294: 
                   13295: =item *
                   13296: 
                   13297: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13298:                   reference
                   13299: 
                   13300: returns either a stat() list of data about the file or an empty list
                   13301: if the file doesn't exist or couldn't find out about it (connection
                   13302: problems or user unknown)
                   13303: 
1.191     harris41 13304: =item *
                   13305: 
1.243     albertel 13306: filelocation($dir,$file) : returns file system location of a file
                   13307: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13308: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13309: and a file of ../bob will become /a/bob)
1.191     harris41 13310: 
                   13311: =item *
                   13312: 
                   13313: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13314: filelocation except for hrefs
                   13315: 
                   13316: =item *
                   13317: 
                   13318: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13319: 
1.243     albertel 13320: =back
                   13321: 
1.608     albertel 13322: =head2 Usererfile file routines (/uploaded*)
                   13323: 
                   13324: =over 4
                   13325: 
                   13326: =item *
                   13327: 
                   13328: userfileupload(): main rotine for putting a file in a user or course's
                   13329:                   filespace, arguments are,
                   13330: 
1.620     albertel 13331:  formname - required - this is the name of the element in $env where the
1.608     albertel 13332:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13333:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13334:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13335:  context - if coursedoc, store the file in the course of the active role
                   13336:              of the current user; 
                   13337:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13338:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13339:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13340:          if undefined, it will be placed in "unknown"
                   13341: 
                   13342:  (This routine calls clean_filename() to remove any dangerous
                   13343:  characters from the filename, and then calls finuserfileupload() to
                   13344:  complete the transaction)
                   13345: 
                   13346:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13347:  and /adm/notfound.html if unsuccessful
                   13348: 
                   13349: =item *
                   13350: 
                   13351: clean_filename(): routine for cleaing a filename up for storage in
                   13352:                  userfile space, argument is:
                   13353: 
                   13354:  filename - proposed filename
                   13355: 
                   13356: returns: the new clean filename
                   13357: 
                   13358: =item *
                   13359: 
1.1090    raeburn  13360: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13361: userspace, probably shouldn't be called directly
                   13362: 
                   13363:   docuname: username or courseid of destination for the file
                   13364:   docudom: domain of user/course of destination for the file
                   13365:   formname: same as for userfileupload()
1.1090    raeburn  13366:   fname: filename (including subdirectories) for the file
                   13367:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13368:   allfiles: reference to hash used to store objects found by parser
                   13369:   codebase: reference to hash used for codebases of java objects found by parser
                   13370:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13371:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13372:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13373:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13374:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13375:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13376:   mimetype: reference to scalar to accommodate mime type determined
                   13377:             from File::MMagic if $parser = parse.
1.608     albertel 13378: 
                   13379:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13380:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13381:  was 'overwrite').
                   13382:  
1.608     albertel 13383: 
                   13384: =item *
                   13385: 
                   13386: renameuserfile(): renames an existing userfile to a new name
                   13387: 
                   13388:   Args:
                   13389:    docuname: username or courseid of destination for the file
                   13390:    docudom: domain of user/course of destination for the file
                   13391:    old: current file name (including any subdirs under userfiles)
                   13392:    new: desired file name (including any subdirs under userfiles)
                   13393: 
                   13394: =item *
                   13395: 
                   13396: mkdiruserfile(): creates a directory is a userfiles dir
                   13397: 
                   13398:   Args:
                   13399:    docuname: username or courseid of destination for the file
                   13400:    docudom: domain of user/course of destination for the file
                   13401:    dir: dir to create (including any subdirs under userfiles)
                   13402: 
                   13403: =item *
                   13404: 
                   13405: removeuserfile(): removes a file that exists in userfiles
                   13406: 
                   13407:   Args:
                   13408:    docuname: username or courseid of destination for the file
                   13409:    docudom: domain of user/course of destination for the file
                   13410:    fname: filname to delete (including any subdirs under userfiles)
                   13411: 
                   13412: =item *
                   13413: 
                   13414: removeuploadedurl(): convience function for removeuserfile()
                   13415: 
                   13416:   Args:
                   13417:    url:  a full /uploaded/... url to delete
                   13418: 
1.747     albertel 13419: =item * 
                   13420: 
                   13421: get_portfile_permissions():
                   13422:   Args:
                   13423:     domain: domain of user or course contain the portfolio files
                   13424:     user: name of user or num of course contain the portfolio files
                   13425:   Returns:
                   13426:     hashref of a dump of the proper file_permissions.db
                   13427:    
                   13428: 
                   13429: =item * 
                   13430: 
                   13431: get_access_controls():
                   13432: 
                   13433: Args:
                   13434:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13435:   group: (optional) the group you want the files associated with
                   13436:   file: (optional) the file you want access info on
                   13437: 
                   13438: Returns:
1.749     raeburn  13439:     a hash (keys are file names) of hashes containing
                   13440:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13441:         values are XML containing access control settings (see below) 
1.747     albertel 13442: 
                   13443: Internal notes:
                   13444: 
1.749     raeburn  13445:  access controls are stored in file_permissions.db as key=value pairs.
                   13446:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13447:         where scope -> public,guest,course,group,domains or users.
                   13448:               end -> UNIX time for end of access (0 -> no end date)
                   13449:               start -> UNIX time for start of access
                   13450: 
                   13451:     value -> XML description of access control
                   13452:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13453:             <start></start>
                   13454:             <end></end>
                   13455: 
                   13456:             <password></password>  for scope type = guest
                   13457: 
                   13458:             <domain></domain>     for scope type = course or group
                   13459:             <number></number>
                   13460:             <roles id="">
                   13461:              <role></role>
                   13462:              <access></access>
                   13463:              <section></section>
                   13464:              <group></group>
                   13465:             </roles>
                   13466: 
                   13467:             <dom></dom>         for scope type = domains
                   13468: 
                   13469:             <users>             for scope type = users
                   13470:              <user>
                   13471:               <uname></uname>
                   13472:               <udom></udom>
                   13473:              </user>
                   13474:             </users>
                   13475:            </scope> 
                   13476:               
                   13477:  Access data is also aggregated for each file in an additional key=value pair:
                   13478:  key -> path to file/file_name\0accesscontrol 
                   13479:  value -> reference to hash
                   13480:           hash contains key = value pairs
                   13481:           where key = uniqueID:scope_end_start
                   13482:                 value = UNIX time record was last updated
                   13483: 
                   13484:           Used to improve speed of look-ups of access controls for each file.  
                   13485:  
                   13486:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13487: 
1.1198    raeburn  13488: =item *
                   13489: 
1.749     raeburn  13490: modify_access_controls():
                   13491: 
                   13492: Modifies access controls for a portfolio file
                   13493: Args
                   13494: 1. file name
                   13495: 2. reference to hash of required changes,
                   13496: 3. domain
                   13497: 4. username
                   13498:   where domain,username are the domain of the portfolio owner 
                   13499:   (either a user or a course) 
                   13500: 
                   13501: Returns:
                   13502: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13503: 2. result of deletions ('ok' or 'error', with error message).
                   13504: 3. reference to hash of any new or updated access controls.
                   13505: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13506:    key = integer (inbound ID)
1.1198    raeburn  13507:    value = uniqueID
                   13508: 
                   13509: =item *
                   13510: 
                   13511: get_timebased_id():
                   13512: 
                   13513: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13514: course via the Course Editor (e.g., folders, composite pages, 
                   13515: group bulletin boards).
                   13516: 
                   13517: Args: (first three required; six others optional)
                   13518: 
                   13519: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13520:    docssequence, or name of group
                   13521: 
                   13522: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13523:    e.g., num, boardids
                   13524: 
                   13525: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   13526:    file will be named nohist_namespace.db
                   13527: 
                   13528: 4. cdom: domain of course; default is current course domain from %env
                   13529: 
                   13530: 5. cnum: course number; default is current course number from %env
                   13531: 
                   13532: 6. idtype: set to concat if an additional digit is to be appended to the 
                   13533:    unix timestamp to form the suffix, if the plain timestamp is already
                   13534:    in use.  Default is to not do this, but simply increment the unix 
                   13535:    timestamp by 1 until a unique key is obtained.
                   13536: 
                   13537: 7. who: holder of locking key; defaults to user:domain for user.
                   13538: 
                   13539: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   13540:    retrying); default is 3.
                   13541: 
                   13542: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   13543: 
                   13544: Returns:
                   13545: 
                   13546: 1. suffix obtained (numeric)
                   13547: 
                   13548: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13549: 
                   13550: 3. error: contains (localized) error message if an error occurred.
                   13551: 
1.747     albertel 13552: 
1.608     albertel 13553: =back
                   13554: 
1.243     albertel 13555: =head2 HTTP Helper Routines
                   13556: 
                   13557: =over 4
                   13558: 
1.191     harris41 13559: =item *
                   13560: 
                   13561: escape() : unpack non-word characters into CGI-compatible hex codes
                   13562: 
                   13563: =item *
                   13564: 
                   13565: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13566: 
1.243     albertel 13567: =back
                   13568: 
                   13569: =head1 PRIVATE SUBROUTINES
                   13570: 
                   13571: =head2 Underlying communication routines (Shouldn't call)
                   13572: 
                   13573: =over 4
                   13574: 
                   13575: =item *
                   13576: 
                   13577: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13578: 
                   13579: =item *
                   13580: 
                   13581: reply() : uses subreply to send a message to remote machine, logs all failures
                   13582: 
                   13583: =item *
                   13584: 
                   13585: critical() : passes a critical message to another server; if cannot
                   13586: get through then place message in connection buffer directory and
                   13587: returns con_delayed, if incapable of saving message, returns
                   13588: con_failed
                   13589: 
                   13590: =item *
                   13591: 
                   13592: reconlonc() : tries to reconnect lonc client processes.
                   13593: 
                   13594: =back
                   13595: 
                   13596: =head2 Resource Access Logging
                   13597: 
                   13598: =over 4
                   13599: 
                   13600: =item *
                   13601: 
                   13602: flushcourselogs() : flush (save) buffer logs and access logs
                   13603: 
                   13604: =item *
                   13605: 
                   13606: courselog($what) : save message for course in hash
                   13607: 
                   13608: =item *
                   13609: 
                   13610: courseacclog($what) : save message for course using &courselog().  Perform
                   13611: special processing for specific resource types (problems, exams, quizzes, etc).
                   13612: 
1.191     harris41 13613: =item *
                   13614: 
                   13615: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13616: as a PerlChildExitHandler
1.243     albertel 13617: 
                   13618: =back
                   13619: 
                   13620: =head2 Other
                   13621: 
                   13622: =over 4
                   13623: 
                   13624: =item *
                   13625: 
                   13626: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13627: 
                   13628: =back
                   13629: 
                   13630: =cut
1.877     foxr     13631: 

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