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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1193  ! raeburn     4: # $Id: lonnet.pm,v 1.1192 2012/10/29 17:39:02 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.871     albertel   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.539     albertel   95: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.550     foxr      108: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.993     raeburn   232: sub get_server_loncaparev {
1.1073    raeburn   233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   234:     if (defined($lonhost)) {
                    235:         if (!defined(&hostname($lonhost))) {
                    236:             undef($lonhost);
                    237:         }
                    238:     }
                    239:     if (!defined($lonhost)) {
                    240:         if (defined(&domain($dom,'primary'))) {
                    241:             $lonhost=&domain($dom,'primary');
                    242:             if ($lonhost eq 'no_host') {
                    243:                 undef($lonhost);
                    244:             }
                    245:         }
                    246:     }
                    247:     if (defined($lonhost)) {
1.1073    raeburn   248:         my $cachetime = 12*3600;
                    249:         if (!$ignore_cache) {
                    250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    251:             if (defined($cached)) {
                    252:                 return $loncaparev;
                    253:             }
                    254:         }
                    255:         my ($answer,$loncaparev);
                    256:         my @ids=&current_machine_ids();
                    257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    258:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   260:                 $loncaparev = $1;
                    261:             }
                    262:         } else {
                    263:             $answer = &reply('serverloncaparev',$lonhost);
                    264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    265:                 if ($caller eq 'loncron') {
                    266:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   267:                     $ua->timeout(4);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
                    270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
                    359:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   361:     return $response;
                    362: }
                    363: 
1.1       albertel  364: # -------------------------------------------------- Non-critical communication
                    365: sub subreply {
                    366:     my ($cmd,$server)=@_;
1.838     albertel  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      368:     #
                    369:     #  With loncnew process trimming, there's a timing hole between lonc server
                    370:     #  process exit and the master server picking up the listen on the AF_UNIX
                    371:     #  socket.  In that time interval, a lock file will exist:
                    372: 
                    373:     my $lockfile=$peerfile.".lock";
                    374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    375: 	sleep(1);
                    376:     }
                    377:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      378:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      379:     #
1.550     foxr      380:     #   We'll give the connection a few tries before abandoning it.  If
                    381:     #   connection is not possible, we'll con_lost back to the client.
                    382:     #   
                    383:     my $client;
                    384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    386: 				      Type    => SOCK_STREAM,
                    387: 				      Timeout => 10);
1.869     albertel  388: 	if ($client) {
1.550     foxr      389: 	    last;		# Connected!
1.850     albertel  390: 	} else {
1.853     albertel  391: 	    &create_connection(&hostname($server),$server);
1.550     foxr      392: 	}
1.850     albertel  393:         sleep(1);		# Try again later if failed connection.
1.550     foxr      394:     }
                    395:     my $answer;
                    396:     if ($client) {
1.704     albertel  397: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      398: 	$answer=<$client>;
                    399: 	if (!$answer) { $answer="con_lost"; }
                    400: 	chomp($answer);
                    401:     } else {
                    402: 	$answer = 'con_lost';	# Failed connection.
                    403:     }
1.1       albertel  404:     return $answer;
                    405: }
                    406: 
                    407: sub reply {
                    408:     my ($cmd,$server)=@_;
1.838     albertel  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  410:     my $answer=subreply($cmd,$server);
1.65      www       411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  412:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       413:                 " $cmd to $server returned $answer</font>");
                    414:     }
1.1       albertel  415:     return $answer;
                    416: }
                    417: 
                    418: # ----------------------------------------------------------- Send USR1 to lonc
                    419: 
                    420: sub reconlonc {
1.891     albertel  421:     my ($lonid) = @_;
                    422:     my $hostname = &hostname($lonid);
                    423:     if ($lonid) {
                    424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    425: 	if ($hostname && -e $peerfile) {
                    426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    428: 					     Type    => SOCK_STREAM,
                    429: 					     Timeout => 10);
                    430: 	    if ($client) {
                    431: 		print $client ("reset_retries\n");
                    432: 		my $answer=<$client>;
                    433: 		#reset just this one.
                    434: 	    }
                    435: 	}
                    436: 	return;
                    437:     }
                    438: 
1.836     www       439:     &logthis("Trying to reconnect lonc");
1.1       albertel  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  441:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  442: 	my $loncpid=<$fh>;
                    443:         chomp($loncpid);
                    444:         if (kill 0 => $loncpid) {
                    445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    446:             kill USR1 => $loncpid;
                    447:             sleep 1;
1.836     www       448:          } else {
1.12      www       449: 	    &logthis(
1.672     albertel  450:                "<font color=\"blue\">WARNING:".
1.12      www       451:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  452:         }
                    453:     } else {
1.836     www       454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  455:     }
                    456: }
                    457: 
                    458: # ------------------------------------------------------ Critical communication
1.12      www       459: 
1.1       albertel  460: sub critical {
                    461:     my ($cmd,$server)=@_;
1.838     albertel  462:     unless (&hostname($server)) {
1.672     albertel  463:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       464:                " Critical message to unknown server ($server)</font>");
                    465:         return 'no_such_host';
                    466:     }
1.1       albertel  467:     my $answer=reply($cmd,$server);
                    468:     if ($answer eq 'con_lost') {
                    469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  470: 	my $answer=reply($cmd,$server);
1.1       albertel  471:         if ($answer eq 'con_lost') {
                    472:             my $now=time;
                    473:             my $middlename=$cmd;
1.5       www       474:             $middlename=substr($middlename,0,16);
1.1       albertel  475:             $middlename=~s/\W//g;
                    476:             my $dfilename=
1.305     www       477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    478:             $dumpcount++;
1.1       albertel  479:             {
1.448     albertel  480: 		my $dfh;
                    481: 		if (open($dfh,">$dfilename")) {
                    482: 		    print $dfh "$cmd\n"; 
                    483: 		    close($dfh);
                    484: 		}
1.1       albertel  485:             }
                    486:             sleep 2;
                    487:             my $wcmd='';
                    488:             {
1.448     albertel  489: 		my $dfh;
                    490: 		if (open($dfh,"<$dfilename")) {
                    491: 		    $wcmd=<$dfh>; 
                    492: 		    close($dfh);
                    493: 		}
1.1       albertel  494:             }
                    495:             chomp($wcmd);
1.7       www       496:             if ($wcmd eq $cmd) {
1.672     albertel  497: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       498:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  499:                 &logperm("D:$server:$cmd");
                    500: 	        return 'con_delayed';
                    501:             } else {
1.672     albertel  502:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       503:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  504:                 &logperm("F:$server:$cmd");
                    505:                 return 'con_failed';
                    506:             }
                    507:         }
                    508:     }
                    509:     return $answer;
1.405     albertel  510: }
                    511: 
1.755     albertel  512: # ------------------------------------------- check if return value is an error
                    513: 
                    514: sub error {
                    515:     my ($result) = @_;
1.756     albertel  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  517: 	if ($2 == 2) { return undef; }
                    518: 	return $1;
                    519:     }
                    520:     return undef;
                    521: }
                    522: 
1.783     albertel  523: sub convert_and_load_session_env {
                    524:     my ($lonidsdir,$handle)=@_;
                    525:     my @profile;
                    526:     {
1.917     albertel  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    528: 	if (!$opened) {
1.915     albertel  529: 	    return 0;
                    530: 	}
1.783     albertel  531: 	flock($idf,LOCK_SH);
                    532: 	@profile=<$idf>;
                    533: 	close($idf);
                    534:     }
                    535:     my %temp_env;
                    536:     foreach my $line (@profile) {
1.786     albertel  537: 	if ($line !~ m/=/) {
                    538: 	    return 0;
                    539: 	}
1.783     albertel  540: 	chomp($line);
                    541: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    543:     }
                    544:     unlink("$lonidsdir/$handle.id");
                    545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    546: 	    0640)) {
                    547: 	%disk_env = %temp_env;
                    548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    549: 	untie(%disk_env);
                    550:     }
1.786     albertel  551:     return 1;
1.783     albertel  552: }
                    553: 
1.374     www       554: # ------------------------------------------- Transfer profile into environment
1.780     albertel  555: my $env_loaded;
                    556: sub transfer_profile_to_env {
1.788     albertel  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    558:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       559: 
1.720     albertel  560:     if (!defined($lonidsdir)) {
                    561: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    562:     }
                    563:     if (!defined($handle)) {
                    564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    565:     }
                    566: 
1.786     albertel  567:     my $convert;
                    568:     {
1.917     albertel  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    570: 	if (!$opened) {
1.915     albertel  571: 	    return;
                    572: 	}
1.786     albertel  573: 	flock($idf,LOCK_SH);
                    574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    575: 		&GDBM_READER(),0640)) {
                    576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    577: 	    untie(%disk_env);
                    578: 	} else {
                    579: 	    $convert = 1;
                    580: 	}
                    581:     }
                    582:     if ($convert) {
                    583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    584: 	    &logthis("Failed to load session, or convert session.");
                    585: 	}
1.374     www       586:     }
1.783     albertel  587: 
1.786     albertel  588:     my %remove;
1.783     albertel  589:     while ( my $envname = each(%env) ) {
1.433     matthew   590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    591:             if ($time < time-300) {
1.783     albertel  592:                 $remove{$key}++;
1.433     matthew   593:             }
                    594:         }
                    595:     }
1.783     albertel  596: 
1.619     albertel  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  598:     $env_loaded=1;
1.783     albertel  599:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   600:         &delenv($expired_key);
1.374     www       601:     }
1.1       albertel  602: }
                    603: 
1.916     albertel  604: # ---------------------------------------------------- Check for valid session 
                    605: sub check_for_valid_session {
1.1155    raeburn   606:     my ($r,$name) = @_;
1.916     albertel  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   608:     if ($name eq '') {
                    609:         $name = 'lonID';
                    610:     }
                    611:     my $lonid=$cookies{$name};
1.916     albertel  612:     return undef if (!$lonid);
                    613: 
                    614:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   615:     my $lonidsdir;
                    616:     if ($name eq 'lonDAV') {
                    617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    618:     } else {
                    619:         $lonidsdir=$r->dir_config('lonIDsDir');
                    620:     }
1.916     albertel  621:     return undef if (!-e "$lonidsdir/$handle.id");
                    622: 
1.917     albertel  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    624:     return undef if (!$opened);
1.916     albertel  625: 
                    626:     flock($idf,LOCK_SH);
                    627:     my %disk_env;
                    628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    629: 	    &GDBM_READER(),0640)) {
                    630: 	return undef;	
                    631:     }
                    632: 
                    633:     if (!defined($disk_env{'user.name'})
                    634: 	|| !defined($disk_env{'user.domain'})) {
                    635: 	return undef;
                    636:     }
                    637:     return $handle;
                    638: }
                    639: 
1.830     albertel  640: sub timed_flock {
                    641:     my ($file,$lock_type) = @_;
                    642:     my $failed=0;
                    643:     eval {
                    644: 	local $SIG{__DIE__}='DEFAULT';
                    645: 	local $SIG{ALRM}=sub {
                    646: 	    $failed=1;
                    647: 	    die("failed lock");
                    648: 	};
                    649: 	alarm(13);
                    650: 	flock($file,$lock_type);
                    651: 	alarm(0);
                    652:     };
                    653:     if ($failed) {
                    654: 	return undef;
                    655:     } else {
                    656: 	return 1;
                    657:     }
                    658: }
                    659: 
1.5       www       660: # ---------------------------------------------------------- Append Environment
                    661: 
                    662: sub appenv {
1.949     raeburn   663:     my ($newenv,$roles) = @_;
                    664:     if (ref($newenv) eq 'HASH') {
                    665:         foreach my $key (keys(%{$newenv})) {
                    666:             my $refused = 0;
                    667: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    668:                 $refused = 1;
                    669:                 if (ref($roles) eq 'ARRAY') {
                    670:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    671:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    672:                         $refused = 0;
                    673:                     }
                    674:                 }
                    675:             }
                    676:             if ($refused) {
                    677:                 &logthis("<font color=\"blue\">WARNING: ".
                    678:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    679:                          .'</font>');
                    680: 	        delete($newenv->{$key});
                    681:             } else {
                    682:                 $env{$key}=$newenv->{$key};
                    683:             }
                    684:         }
                    685:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    686:         if ($opened
                    687: 	    && &timed_flock($env_file,LOCK_EX)
                    688: 	    &&
                    689: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    690: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    691: 	    while (my ($key,$value) = each(%{$newenv})) {
                    692: 	        $disk_env{$key} = $value;
                    693: 	    }
                    694: 	    untie(%disk_env);
1.35      www       695:         }
1.191     harris41  696:     }
1.56      www       697:     return 'ok';
                    698: }
                    699: # ----------------------------------------------------- Delete from Environment
                    700: 
                    701: sub delenv {
1.1104    raeburn   702:     my ($delthis,$regexp,$roles) = @_;
                    703:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    704:         my $refused = 1;
                    705:         if (ref($roles) eq 'ARRAY') {
                    706:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    707:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    708:                 $refused = 0;
                    709:             }
                    710:         }
                    711:         if ($refused) {
                    712:             &logthis("<font color=\"blue\">WARNING: ".
                    713:                      "Attempt to delete from environment ".$delthis);
                    714:             return 'error';
                    715:         }
1.56      www       716:     }
1.917     albertel  717:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    718:     if ($opened
1.915     albertel  719: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  720: 	&&
                    721: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    722: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  723: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   724: 	    if ($regexp) {
                    725:                 if ($key=~/^$delthis/) {
                    726:                     delete($env{$key});
                    727:                     delete($disk_env{$key});
                    728:                 } 
                    729:             } else {
                    730:                 if ($key=~/^\Q$delthis\E/) {
                    731: 		    delete($env{$key});
                    732: 		    delete($disk_env{$key});
                    733: 	        }
                    734:             }
1.448     albertel  735: 	}
1.783     albertel  736: 	untie(%disk_env);
1.5       www       737:     }
                    738:     return 'ok';
1.369     albertel  739: }
                    740: 
1.790     albertel  741: sub get_env_multiple {
                    742:     my ($name) = @_;
                    743:     my @values;
                    744:     if (defined($env{$name})) {
                    745:         # exists is it an array
                    746:         if (ref($env{$name})) {
                    747:             @values=@{ $env{$name} };
                    748:         } else {
                    749:             $values[0]=$env{$name};
                    750:         }
                    751:     }
                    752:     return(@values);
                    753: }
                    754: 
1.958     www       755: # ------------------------------------------------------------------- Locking
                    756: 
                    757: sub set_lock {
                    758:     my ($text)=@_;
                    759:     $locknum++;
                    760:     my $id=$$.'-'.$locknum;
                    761:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    762:              'session.lock.'.$id => $text});
                    763:     return $id;
                    764: }
                    765: 
                    766: sub get_locks {
                    767:     my $num=0;
                    768:     my %texts=();
                    769:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    770:        if ($lock=~/\w/) {
                    771:           $num++;
                    772:           $texts{$lock}=$env{'session.lock.'.$lock};
                    773:        }
                    774:    }
                    775:    return ($num,%texts);
                    776: }
                    777: 
                    778: sub remove_lock {
                    779:     my ($id)=@_;
                    780:     my $newlocks='';
                    781:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    782:        if (($lock=~/\w/) && ($lock ne $id)) {
                    783:           $newlocks.=','.$lock;
                    784:        }
                    785:     }
                    786:     &appenv({'session.locks' => $newlocks});
                    787:     &delenv('session.lock.'.$id);
                    788: }
                    789: 
                    790: sub remove_all_locks {
                    791:     my $activelocks=$env{'session.locks'};
                    792:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    793:        if ($lock=~/\w/) {
                    794:           &remove_lock($lock);
                    795:        }
                    796:     }
                    797: }
                    798: 
                    799: 
1.369     albertel  800: # ------------------------------------------ Find out current server userload
                    801: sub userload {
                    802:     my $numusers=0;
                    803:     {
                    804: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    805: 	my $filename;
                    806: 	my $curtime=time;
                    807: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  808: 	    next if ($filename eq '.' || $filename eq '..');
                    809: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  810: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  811: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  812: 	}
                    813: 	closedir(LONIDS);
                    814:     }
                    815:     my $userloadpercent=0;
                    816:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    817:     if ($maxuserload) {
1.371     albertel  818: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  819:     }
1.372     albertel  820:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  821:     return $userloadpercent;
1.283     www       822: }
                    823: 
1.1       albertel  824: # ------------------------------ Find server with least workload from spare.tab
1.11      www       825: 
1.1       albertel  826: sub spareserver {
1.1083    raeburn   827:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  828:     my $spare_server;
1.370     albertel  829:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  830:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    831:                                                      :  $userloadpercent;
1.1083    raeburn   832:     my ($uint_dom,$remotesessions);
                    833:     if (($udom ne '') && (&domain($udom) ne '')) {
                    834:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    835:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    836:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    837:         $remotesessions = $udomdefaults{'remotesessions'};
                    838:     }
1.1123    raeburn   839:     my $spareshash = &this_host_spares($udom);
                    840:     if (ref($spareshash) eq 'HASH') {
                    841:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    842:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    843:                 if ($uint_dom) {
                    844:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    845:                                                  $try_server));
                    846:                 }
                    847: 	        ($spare_server, $lowest_load) =
                    848: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    849:             }
1.1083    raeburn   850:         }
1.784     albertel  851: 
1.1123    raeburn   852:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    853: 
                    854:         if (!$found_server) {
                    855:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    856: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    857:                     if ($uint_dom) {
                    858:                         next unless (&spare_can_host($udom,$uint_dom,
                    859:                                                      $remotesessions,$try_server));
                    860:                     }
                    861: 	            ($spare_server, $lowest_load) =
                    862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:                 }
                    864: 	    }
                    865:         }
1.784     albertel  866:     }
                    867: 
                    868:     if (!$want_server_name) {
1.968     raeburn   869:         my $protocol = 'http';
                    870:         if ($protocol{$spare_server} eq 'https') {
                    871:             $protocol = $protocol{$spare_server};
                    872:         }
1.1001    raeburn   873:         if (defined($spare_server)) {
                    874:             my $hostname = &hostname($spare_server);
1.1083    raeburn   875:             if (defined($hostname)) {
1.1001    raeburn   876: 	        $spare_server = $protocol.'://'.$hostname;
                    877:             }
                    878:         }
1.784     albertel  879:     }
                    880:     return $spare_server;
                    881: }
                    882: 
                    883: sub compare_server_load {
                    884:     my ($try_server, $spare_server, $lowest_load) = @_;
                    885: 
                    886:     my $loadans     = &reply('load',    $try_server);
                    887:     my $userloadans = &reply('userload',$try_server);
                    888: 
                    889:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   890: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  891:     }
                    892: 
                    893:     my $load;
                    894:     if ($loadans =~ /\d/) {
                    895: 	if ($userloadans =~ /\d/) {
                    896: 	    #both are numbers, pick the bigger one
                    897: 	    $load = ($loadans > $userloadans) ? $loadans 
                    898: 		                              : $userloadans;
1.411     albertel  899: 	} else {
1.784     albertel  900: 	    $load = $loadans;
1.411     albertel  901: 	}
1.784     albertel  902:     } else {
                    903: 	$load = $userloadans;
                    904:     }
                    905: 
                    906:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    907: 	$spare_server = $try_server;
                    908: 	$lowest_load  = $load;
1.370     albertel  909:     }
1.784     albertel  910:     return ($spare_server,$lowest_load);
1.202     matthew   911: }
1.914     albertel  912: 
                    913: # --------------------------- ask offload servers if user already has a session
                    914: sub find_existing_session {
                    915:     my ($udom,$uname) = @_;
1.1123    raeburn   916:     my $spareshash = &this_host_spares($udom);
                    917:     if (ref($spareshash) eq 'HASH') {
                    918:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    919:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    920:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    921:             }
                    922:         }
                    923:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    924:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    926:             }
                    927:         }
1.914     albertel  928:     }
                    929:     return;
                    930: }
                    931: 
                    932: # -------------------------------- ask if server already has a session for user
                    933: sub has_user_session {
                    934:     my ($lonid,$udom,$uname) = @_;
                    935:     my $result = &reply(join(':','userhassession',
                    936: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    937:     return 1 if ($result eq 'ok');
                    938: 
                    939:     return 0;
                    940: }
                    941: 
1.1076    raeburn   942: # --------- determine least loaded server in a user's domain which allows login
                    943: 
                    944: sub choose_server {
1.1115    raeburn   945:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   946:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   947:     my %servers = &get_servers($udom);
1.1076    raeburn   948:     my $lowest_load = 30000;
1.1151    raeburn   949:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   950:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   951:         my $loginvia;
                    952:         if ($checkloginvia) {
                    953:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   954:             if ($loginvia) {
                    955:                 my ($server,$path) = split(/:/,$loginvia);
                    956:                 ($login_host, $lowest_load) =
                    957:                     &compare_server_load($server, $login_host, $lowest_load);
                    958:                 if ($login_host eq $server) {
                    959:                     $portal_path = $path;
1.1151    raeburn   960:                     $isredirect = 1;
1.1116    raeburn   961:                 }
                    962:             } else {
                    963:                 ($login_host, $lowest_load) =
                    964:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    965:                 if ($login_host eq $lonhost) {
                    966:                     $portal_path = '';
1.1151    raeburn   967:                     $isredirect = ''; 
1.1116    raeburn   968:                 }
                    969:             }
                    970:         } else {
1.1076    raeburn   971:             ($login_host, $lowest_load) =
1.1116    raeburn   972:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   973:         }
                    974:     }
                    975:     if ($login_host ne '') {
1.1116    raeburn   976:         $hostname = &hostname($login_host);
1.1076    raeburn   977:     }
1.1151    raeburn   978:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   979: }
                    980: 
1.202     matthew   981: # --------------------------------------------- Try to change a user's password
                    982: 
                    983: sub changepass {
1.799     raeburn   984:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   985:     $currentpass = &escape($currentpass);
                    986:     $newpass     = &escape($newpass);
1.1030    raeburn   987:     my $lonhost = $perlvar{'lonHostID'};
                    988:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   989: 		       $server);
                    990:     if (! $answer) {
                    991: 	&logthis("No reply on password change request to $server ".
                    992: 		 "by $uname in domain $udom.");
                    993:     } elsif ($answer =~ "^ok") {
                    994:         &logthis("$uname in $udom successfully changed their password ".
                    995: 		 "on $server.");
                    996:     } elsif ($answer =~ "^pwchange_failure") {
                    997: 	&logthis("$uname in $udom was unable to change their password ".
                    998: 		 "on $server.  The action was blocked by either lcpasswd ".
                    999: 		 "or pwchange");
                   1000:     } elsif ($answer =~ "^non_authorized") {
                   1001:         &logthis("$uname in $udom did not get their password correct when ".
                   1002: 		 "attempting to change it on $server.");
                   1003:     } elsif ($answer =~ "^auth_mode_error") {
                   1004:         &logthis("$uname in $udom attempted to change their password despite ".
                   1005: 		 "not being locally or internally authenticated on $server.");
                   1006:     } elsif ($answer =~ "^unknown_user") {
                   1007:         &logthis("$uname in $udom attempted to change their password ".
                   1008: 		 "on $server but were unable to because $server is not ".
                   1009: 		 "their home server.");
                   1010:     } elsif ($answer =~ "^refused") {
                   1011: 	&logthis("$server refused to change $uname in $udom password because ".
                   1012: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1013:     } elsif ($answer =~ "invalid_client") {
                   1014:         &logthis("$server refused to change $uname in $udom password because ".
                   1015:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1016:     }
                   1017:     return $answer;
1.1       albertel 1018: }
                   1019: 
1.169     harris41 1020: # ----------------------- Try to determine user's current authentication scheme
                   1021: 
                   1022: sub queryauthenticate {
                   1023:     my ($uname,$udom)=@_;
1.456     albertel 1024:     my $uhome=&homeserver($uname,$udom);
                   1025:     if (!$uhome) {
                   1026: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1027: 	return 'no_host';
                   1028:     }
                   1029:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1030:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1031: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1032:     }
1.456     albertel 1033:     return $answer;
1.169     harris41 1034: }
                   1035: 
1.1       albertel 1036: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1037: 
1.1       albertel 1038: sub authenticate {
1.1073    raeburn  1039:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1040:     $upass=&escape($upass);
                   1041:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1042:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1043:     my $newhome;
1.836     www      1044:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1045: # Maybe the machine was offline and only re-appeared again recently?
                   1046:         &reconlonc();
                   1047: # One more
1.952     raeburn  1048: 	$uhome=&homeserver($uname,$udom,1);
                   1049:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1050:             if (defined(&domain($udom,'primary'))) {
                   1051:                 $newhome=&domain($udom,'primary');
                   1052:             }
                   1053:             if ($newhome ne '') {
                   1054:                 $uhome = $newhome;
                   1055:             }
                   1056:         }
1.836     www      1057: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1058: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1059: 	    return 'no_host';
                   1060:         }
1.1       albertel 1061:     }
1.1073    raeburn  1062:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1063:     if ($answer eq 'authorized') {
1.952     raeburn  1064:         if ($newhome) {
                   1065:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1066:             return 'no_account_on_host'; 
                   1067:         } else {
                   1068:             &logthis("User $uname at $udom authorized by $uhome");
                   1069:             return $uhome;
                   1070:         }
1.471     albertel 1071:     }
                   1072:     if ($answer eq 'non_authorized') {
                   1073: 	&logthis("User $uname at $udom rejected by $uhome");
                   1074: 	return 'no_host'; 
1.9       www      1075:     }
1.471     albertel 1076:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1077:     return 'no_host';
                   1078: }
                   1079: 
1.1073    raeburn  1080: sub can_host_session {
1.1074    raeburn  1081:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1082:     my $canhost = 1;
1.1074    raeburn  1083:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1084:     if (ref($remotesessions) eq 'HASH') {
                   1085:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1087:                 $canhost = 0;
                   1088:             } else {
                   1089:                 $canhost = 1;
                   1090:             }
                   1091:         }
                   1092:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1094:                 $canhost = 1;
                   1095:             } else {
                   1096:                 $canhost = 0;
                   1097:             }
                   1098:         }
                   1099:         if ($canhost) {
                   1100:             if ($remotesessions->{'version'} ne '') {
                   1101:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1102:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1103:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1104:                         my $major = $1;
                   1105:                         my $minor = $2;
                   1106:                         if (($major < $reqmajor ) ||
                   1107:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1108:                             $canhost = 0;
                   1109:                         }
                   1110:                     } else {
                   1111:                         $canhost = 0;
                   1112:                     }
                   1113:                 }
                   1114:             }
                   1115:         }
                   1116:     }
                   1117:     if ($canhost) {
                   1118:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1119:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1120:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1121:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1122:                 if (($uint_dom ne '') && 
                   1123:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1124:                     $canhost = 0;
                   1125:                 } else {
                   1126:                     $canhost = 1;
                   1127:                 }
                   1128:             }
                   1129:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1130:                 if (($uint_dom ne '') && 
                   1131:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1132:                     $canhost = 1;
                   1133:                 } else {
                   1134:                     $canhost = 0;
                   1135:                 }
                   1136:             }
                   1137:         }
                   1138:     }
                   1139:     return $canhost;
                   1140: }
                   1141: 
1.1083    raeburn  1142: sub spare_can_host {
                   1143:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1144:     my $canhost=1;
                   1145:     my @intdoms;
                   1146:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1147:     if (ref($internet_names) eq 'ARRAY') {
                   1148:         @intdoms = @{$internet_names};
                   1149:     }
                   1150:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1151:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1152:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1153:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1154:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1155:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1156:                                      $remotesessions,
                   1157:                                      $defdomdefaults{'hostedsessions'});
                   1158:     }
                   1159:     return $canhost;
                   1160: }
                   1161: 
1.1123    raeburn  1162: sub this_host_spares {
                   1163:     my ($dom) = @_;
1.1126    raeburn  1164:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1165:     my @hosts = &current_machine_ids();
                   1166:     foreach my $lonhost (@hosts) {
                   1167:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1168:             $dom_in_use = $dom;
                   1169:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1170:             last;
                   1171:         }
                   1172:     }
1.1126    raeburn  1173:     if ($dom_in_use ne '') {
                   1174:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1175:     }
                   1176:     if (ref($result) ne 'HASH') {
                   1177:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1178:         $dom_in_use = &host_domain($lonhost_in_use);
                   1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1180:         if (ref($result) ne 'HASH') {
                   1181:             $result = \%spareid;
                   1182:         }
                   1183:     }
                   1184:     return $result;
                   1185: }
                   1186: 
                   1187: sub spares_for_offload  {
                   1188:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1189:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1190:     if (defined($cached)) {
                   1191:         return $result;
                   1192:     } else {
1.1126    raeburn  1193:         my $cachetime = 60*60*24;
                   1194:         my %domconfig =
                   1195:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1196:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1197:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1198:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1199:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1200:                 }
                   1201:             }
                   1202:         }
                   1203:     }
1.1126    raeburn  1204:     return;
1.1123    raeburn  1205: }
                   1206: 
1.1129    raeburn  1207: sub get_lonbalancer_config {
                   1208:     my ($servers) = @_;
                   1209:     my ($currbalancer,$currtargets);
                   1210:     if (ref($servers) eq 'HASH') {
                   1211:         foreach my $server (keys(%{$servers})) {
                   1212:             my %what = (
                   1213:                          spareid => 1,
                   1214:                          perlvar => 1,
                   1215:                        );
                   1216:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1217:             if ($result eq 'ok') {
                   1218:                 if (ref($returnhash) eq 'HASH') {
                   1219:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1220:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1221:                             $currbalancer = $server;
                   1222:                             $currtargets = {};
                   1223:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1224:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1225:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1226:                                 }
                   1227:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1228:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1229:                                 }
                   1230:                             }
                   1231:                             last;
                   1232:                         }
                   1233:                     }
                   1234:                 }
                   1235:             }
                   1236:         }
                   1237:     }
                   1238:     return ($currbalancer,$currtargets);
                   1239: }
                   1240: 
                   1241: sub check_loadbalancing {
                   1242:     my ($uname,$udom) = @_;
1.1191    raeburn  1243:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1244:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1245:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1246:     my @hosts = &current_machine_ids();
1.1129    raeburn  1247:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1248:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1249:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1250:     my $serverhomedom = &host_domain($lonhost);
                   1251: 
                   1252:     my $cachetime = 60*60*24;
                   1253: 
                   1254:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1255:         $dom_in_use = $udom;
                   1256:         $homeintdom = 1;
                   1257:     } else {
                   1258:         $dom_in_use = $serverhomedom;
                   1259:     }
                   1260:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1261:     unless (defined($cached)) {
                   1262:         my %domconfig =
                   1263:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1264:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1265:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1266:         }
                   1267:     }
                   1268:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1269:         ($is_balancer,$currtargets,$currrules) = 
                   1270:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1271:         if ($is_balancer) {
                   1272:             if (ref($currrules) eq 'HASH') {
                   1273:                 if ($homeintdom) {
                   1274:                     if ($uname ne '') {
                   1275:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1276:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1277:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1278:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1279:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1280:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1281:                             }
                   1282:                         }
                   1283:                         if ($rule_in_effect eq '') {
                   1284:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1285:                             if ($userenv{'inststatus'} ne '') {
                   1286:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1287:                                 my ($othertitle,$usertypes,$types) =
                   1288:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1289:                                 if (ref($types) eq 'ARRAY') {
                   1290:                                     foreach my $type (@{$types}) {
                   1291:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1292:                                             if (exists($currrules->{$type})) {
                   1293:                                                 $rule_in_effect = $currrules->{$type};
                   1294:                                             }
                   1295:                                         }
                   1296:                                     }
                   1297:                                 }
                   1298:                             } else {
                   1299:                                 if (exists($currrules->{'default'})) {
                   1300:                                     $rule_in_effect = $currrules->{'default'};
                   1301:                                 }
                   1302:                             }
                   1303:                         }
                   1304:                     } else {
                   1305:                         if (exists($currrules->{'default'})) {
                   1306:                             $rule_in_effect = $currrules->{'default'};
                   1307:                         }
                   1308:                     }
                   1309:                 } else {
                   1310:                     if ($currrules->{'_LC_external'} ne '') {
                   1311:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1312:                     }
                   1313:                 }
                   1314:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1315:                                                        $uname,$udom);
                   1316:             }
                   1317:         }
                   1318:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1319:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1320:         unless (defined($cached)) {
                   1321:             my %domconfig =
                   1322:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1323:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1324:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1325:             }
                   1326:         }
                   1327:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1328:             ($is_balancer,$currtargets,$currrules) = 
                   1329:                 &check_balancer_result($result,@hosts);
                   1330:             if ($is_balancer) {
1.1129    raeburn  1331:                 if (ref($currrules) eq 'HASH') {
                   1332:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1333:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1334:                     }
                   1335:                 }
                   1336:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1337:                                                        $uname,$udom);
                   1338:             }
                   1339:         } else {
                   1340:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1341:                 $is_balancer = 1;
                   1342:                 $offloadto = &this_host_spares($dom_in_use);
                   1343:             }
                   1344:         }
                   1345:     } else {
                   1346:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1347:             $is_balancer = 1;
                   1348:             $offloadto = &this_host_spares($dom_in_use);
                   1349:         }
                   1350:     }
1.1176    raeburn  1351:     if ($is_balancer) {
                   1352:         my $lowest_load = 30000;
                   1353:         if (ref($offloadto) eq 'HASH') {
                   1354:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1355:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1356:                     ($otherserver,$lowest_load) =
                   1357:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1358:                 }
1.1129    raeburn  1359:             }
1.1176    raeburn  1360:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1361: 
1.1176    raeburn  1362:             if (!$found_server) {
                   1363:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1364:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1365:                         ($otherserver,$lowest_load) =
                   1366:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1367:                     }
                   1368:                 }
                   1369:             }
                   1370:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1371:             if (@{$offloadto} == 1) {
                   1372:                 $otherserver = $offloadto->[0];
                   1373:             } elsif (@{$offloadto} > 1) {
                   1374:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1375:                     ($otherserver,$lowest_load) =
                   1376:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1377:                 }
                   1378:             }
                   1379:         }
1.1176    raeburn  1380:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1381:             $is_balancer = 0;
                   1382:             if ($uname ne '' && $udom ne '') {
                   1383:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1384:                     
                   1385:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1386:                              'user.loadbalcheck.time' => time});
                   1387:                 }
1.1129    raeburn  1388:             }
                   1389:         }
                   1390:     }
                   1391:     return ($is_balancer,$otherserver);
                   1392: }
                   1393: 
1.1191    raeburn  1394: sub check_balancer_result {
                   1395:     my ($result,@hosts) = @_;
                   1396:     my ($is_balancer,$currtargets,$currrules);
                   1397:     if (ref($result) eq 'HASH') {
                   1398:         if ($result->{'lonhost'} ne '') {
                   1399:             my $currbalancer = $result->{'lonhost'};
                   1400:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1401:                 $is_balancer = 1;
                   1402:                 $currtargets = $result->{'targets'};
                   1403:                 $currrules = $result->{'rules'};
                   1404:             }
                   1405:         } else {
                   1406:             foreach my $key (keys(%{$result})) {
                   1407:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1408:                     (ref($result->{$key}) eq 'HASH')) {
                   1409:                     $is_balancer = 1;
                   1410:                     $currrules = $result->{$key}{'rules'};
                   1411:                     $currtargets = $result->{$key}{'targets'};
                   1412:                     last;
                   1413:                 }
                   1414:             }
                   1415:         }
                   1416:     }
                   1417:     return ($is_balancer,$currtargets,$currrules);
                   1418: }
                   1419: 
1.1129    raeburn  1420: sub get_loadbalancer_targets {
                   1421:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1422:     my $offloadto;
1.1175    raeburn  1423:     if ($rule_in_effect eq 'none') {
                   1424:         return [$perlvar{'lonHostID'}];
                   1425:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1426:         $offloadto = $currtargets;
                   1427:     } else {
                   1428:         if ($rule_in_effect eq 'homeserver') {
                   1429:             my $homeserver = &homeserver($uname,$udom);
                   1430:             if ($homeserver ne 'no_host') {
                   1431:                 $offloadto = [$homeserver];
                   1432:             }
                   1433:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1434:             my %domconfig =
                   1435:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1436:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1437:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1438:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1439:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1440:                     }
                   1441:                 }
                   1442:             } else {
1.1178    raeburn  1443:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1444:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1445:                 if (&hostname($remotebalancer) ne '') {
                   1446:                     $offloadto = [$remotebalancer];
                   1447:                 }
                   1448:             }
                   1449:         } elsif (&hostname($rule_in_effect) ne '') {
                   1450:             $offloadto = [$rule_in_effect];
                   1451:         }
                   1452:     }
                   1453:     return $offloadto;
                   1454: }
                   1455: 
1.1127    raeburn  1456: sub internet_dom_servers {
                   1457:     my ($dom) = @_;
                   1458:     my (%uniqservers,%servers);
                   1459:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1460:     my @machinedoms = &machine_domains($primaryserver);
                   1461:     foreach my $mdom (@machinedoms) {
                   1462:         my %currservers = %servers;
                   1463:         my %server = &get_servers($mdom);
                   1464:         %servers = (%currservers,%server);
                   1465:     }
                   1466:     my %by_hostname;
                   1467:     foreach my $id (keys(%servers)) {
                   1468:         push(@{$by_hostname{$servers{$id}}},$id);
                   1469:     }
                   1470:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1471:         if (@{$by_hostname{$hostname}} > 1) {
                   1472:             my $match = 0;
                   1473:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1474:                 if (&host_domain($id) eq $dom) {
                   1475:                     $uniqservers{$id} = $hostname;
                   1476:                     $match = 1;
                   1477:                 }
                   1478:             }
                   1479:             unless ($match) {
                   1480:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1481:             }
                   1482:         } else {
                   1483:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1484:         }
                   1485:     }
                   1486:     return %uniqservers;
                   1487: }
                   1488: 
1.1       albertel 1489: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1490: 
1.599     albertel 1491: my %homecache;
1.1       albertel 1492: sub homeserver {
1.230     stredwic 1493:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1494:     my $index="$uname:$udom";
1.426     albertel 1495: 
1.599     albertel 1496:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1497: 
                   1498:     my %servers = &get_servers($udom,'library');
                   1499:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1500:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1501: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1502: 
                   1503: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1504: 	if ($answer eq 'found') {
                   1505: 	    delete($badServerCache{$tryserver}); 
                   1506: 	    return $homecache{$index}=$tryserver;
                   1507: 	} elsif ($answer eq 'no_host') {
                   1508: 	    $badServerCache{$tryserver}=1;
                   1509: 	}
1.1       albertel 1510:     }    
                   1511:     return 'no_host';
1.70      www      1512: }
                   1513: 
                   1514: # ------------------------------------- Find the usernames behind a list of IDs
                   1515: 
                   1516: sub idget {
                   1517:     my ($udom,@ids)=@_;
                   1518:     my %returnhash=();
                   1519:     
1.841     albertel 1520:     my %servers = &get_servers($udom,'library');
                   1521:     foreach my $tryserver (keys(%servers)) {
                   1522: 	my $idlist=join('&',@ids);
                   1523: 	$idlist=~tr/A-Z/a-z/; 
                   1524: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1525: 	my @answer=();
                   1526: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1527: 	    @answer=split(/\&/,$reply);
                   1528: 	}                    ;
                   1529: 	my $i;
                   1530: 	for ($i=0;$i<=$#ids;$i++) {
                   1531: 	    if ($answer[$i]) {
                   1532: 		$returnhash{$ids[$i]}=$answer[$i];
                   1533: 	    } 
                   1534: 	}
                   1535:     } 
1.70      www      1536:     return %returnhash;
                   1537: }
                   1538: 
                   1539: # ------------------------------------- Find the IDs behind a list of usernames
                   1540: 
                   1541: sub idrget {
                   1542:     my ($udom,@unames)=@_;
                   1543:     my %returnhash=();
1.800     albertel 1544:     foreach my $uname (@unames) {
                   1545:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1546:     }
1.70      www      1547:     return %returnhash;
                   1548: }
                   1549: 
                   1550: # ------------------------------- Store away a list of names and associated IDs
                   1551: 
                   1552: sub idput {
                   1553:     my ($udom,%ids)=@_;
                   1554:     my %servers=();
1.800     albertel 1555:     foreach my $uname (keys(%ids)) {
                   1556: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1557:         my $uhom=&homeserver($uname,$udom);
1.70      www      1558:         if ($uhom ne 'no_host') {
1.800     albertel 1559:             my $id=&escape($ids{$uname});
1.70      www      1560:             $id=~tr/A-Z/a-z/;
1.800     albertel 1561:             my $esc_unam=&escape($uname);
1.70      www      1562: 	    if ($servers{$uhom}) {
1.800     albertel 1563: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1564:             } else {
1.800     albertel 1565:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1566:             }
                   1567:         }
1.191     harris41 1568:     }
1.800     albertel 1569:     foreach my $server (keys(%servers)) {
                   1570:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1571:     }
1.344     www      1572: }
                   1573: 
1.1023    raeburn  1574: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1575: sub dump_dom {
1.1165    droeschl 1576:     my ($namespace, $udom, $regexp) = @_;
                   1577: 
                   1578:     $udom ||= $env{'user.domain'};
                   1579: 
                   1580:     return () unless $udom;
                   1581: 
                   1582:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1583: }
                   1584: 
1.1023    raeburn  1585: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1586: 
                   1587: sub get_dom {
1.860     raeburn  1588:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1589:     my $items='';
                   1590:     foreach my $item (@$storearr) {
                   1591:         $items.=&escape($item).'&';
                   1592:     }
                   1593:     $items=~s/\&$//;
1.860     raeburn  1594:     if (!$udom) {
                   1595:         $udom=$env{'user.domain'};
                   1596:         if (defined(&domain($udom,'primary'))) {
                   1597:             $uhome=&domain($udom,'primary');
                   1598:         } else {
1.874     albertel 1599:             undef($uhome);
1.860     raeburn  1600:         }
                   1601:     } else {
                   1602:         if (!$uhome) {
                   1603:             if (defined(&domain($udom,'primary'))) {
                   1604:                 $uhome=&domain($udom,'primary');
                   1605:             }
                   1606:         }
                   1607:     }
                   1608:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1609:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1610:         my %returnhash;
1.875     albertel 1611:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1612:             return %returnhash;
                   1613:         }
1.806     raeburn  1614:         my @pairs=split(/\&/,$rep);
                   1615:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1616:             return @pairs;
                   1617:         }
                   1618:         my $i=0;
                   1619:         foreach my $item (@$storearr) {
                   1620:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1621:             $i++;
                   1622:         }
                   1623:         return %returnhash;
                   1624:     } else {
1.880     banghart 1625:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1626:     }
                   1627: }
                   1628: 
                   1629: # -------------------------------------------- put items in domain db files 
                   1630: 
                   1631: sub put_dom {
1.860     raeburn  1632:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1633:     if (!$udom) {
                   1634:         $udom=$env{'user.domain'};
                   1635:         if (defined(&domain($udom,'primary'))) {
                   1636:             $uhome=&domain($udom,'primary');
                   1637:         } else {
1.874     albertel 1638:             undef($uhome);
1.860     raeburn  1639:         }
                   1640:     } else {
                   1641:         if (!$uhome) {
                   1642:             if (defined(&domain($udom,'primary'))) {
                   1643:                 $uhome=&domain($udom,'primary');
                   1644:             }
                   1645:         }
                   1646:     } 
                   1647:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1648:         my $items='';
                   1649:         foreach my $item (keys(%$storehash)) {
                   1650:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1651:         }
                   1652:         $items=~s/\&$//;
                   1653:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1654:     } else {
1.860     raeburn  1655:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1656:     }
                   1657: }
                   1658: 
1.1023    raeburn  1659: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1660: sub newput_dom {
1.1023    raeburn  1661:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1662:     my $result;
                   1663:     if (!$udom) {
                   1664:         $udom=$env{'user.domain'};
                   1665:     }
1.1023    raeburn  1666:     if ($udom) {
                   1667:         my $uname = &get_domainconfiguser($udom);
                   1668:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1669:     }
                   1670:     return $result;
                   1671: }
                   1672: 
1.1023    raeburn  1673: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1674: sub del_dom {
1.1023    raeburn  1675:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1676:     if (ref($storearr) eq 'ARRAY') {
                   1677:         if (!$udom) {
                   1678:             $udom=$env{'user.domain'};
                   1679:         }
1.1023    raeburn  1680:         if ($udom) {
                   1681:             my $uname = &get_domainconfiguser($udom); 
                   1682:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1683:         }
                   1684:     }
                   1685: }
                   1686: 
1.1023    raeburn  1687: # ----------------------------------construct domainconfig user for a domain 
                   1688: sub get_domainconfiguser {
                   1689:     my ($udom) = @_;
                   1690:     return $udom.'-domainconfig';
                   1691: }
                   1692: 
1.837     raeburn  1693: sub retrieve_inst_usertypes {
                   1694:     my ($udom) = @_;
                   1695:     my (%returnhash,@order);
1.989     raeburn  1696:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1697:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1698:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1699:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1700:         @order = @{$domdefs{'inststatusorder'}};
                   1701:     } else {
                   1702:         if (defined(&domain($udom,'primary'))) {
                   1703:             my $uhome=&domain($udom,'primary');
                   1704:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1705:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1706:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1707:                 return (\%returnhash,\@order);
                   1708:             }
                   1709:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1710:             my @pairs=split(/\&/,$hashitems);
                   1711:             foreach my $item (@pairs) {
                   1712:                 my ($key,$value)=split(/=/,$item,2);
                   1713:                 $key = &unescape($key);
                   1714:                 next if ($key =~ /^error: 2 /);
                   1715:                 $returnhash{$key}=&thaw_unescape($value);
                   1716:             }
                   1717:             my @esc_order = split(/\&/,$orderitems);
                   1718:             foreach my $item (@esc_order) {
                   1719:                 push(@order,&unescape($item));
                   1720:             }
                   1721:         } else {
                   1722:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1723:         }
                   1724:     }
                   1725:     return (\%returnhash,\@order);
                   1726: }
                   1727: 
1.868     raeburn  1728: sub is_domainimage {
                   1729:     my ($url) = @_;
                   1730:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1731:         if (&domain($1) ne '') {
                   1732:             return '1';
                   1733:         }
                   1734:     }
                   1735:     return;
                   1736: }
                   1737: 
1.899     raeburn  1738: sub inst_directory_query {
                   1739:     my ($srch) = @_;
                   1740:     my $udom = $srch->{'srchdomain'};
                   1741:     my %results;
                   1742:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1743:     my $outcome;
1.899     raeburn  1744:     if ($homeserver ne '') {
1.904     albertel 1745: 	my $queryid=&reply("querysend:instdirsearch:".
                   1746: 			   &escape($srch->{'srchby'}).':'.
                   1747: 			   &escape($srch->{'srchterm'}).':'.
                   1748: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1749: 	my $host=&hostname($homeserver);
                   1750: 	if ($queryid !~/^\Q$host\E\_/) {
                   1751: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1752: 	    return;
                   1753: 	}
                   1754: 	my $response = &get_query_reply($queryid);
                   1755: 	my $maxtries = 5;
                   1756: 	my $tries = 1;
                   1757: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1758: 	    $response = &get_query_reply($queryid);
                   1759: 	    $tries ++;
                   1760: 	}
                   1761: 
                   1762:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1763:             if ($response eq 'unavailable') {
                   1764:                 $outcome = $response;
                   1765:             } else {
                   1766:                 $outcome = 'ok';
                   1767:                 my @matches = split(/\n/,$response);
                   1768:                 foreach my $match (@matches) {
                   1769:                     my ($key,$value) = split(/=/,$match);
                   1770:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1771:                 }
1.899     raeburn  1772:             }
                   1773:         }
                   1774:     }
1.909     raeburn  1775:     return ($outcome,%results);
1.899     raeburn  1776: }
                   1777: 
                   1778: sub usersearch {
                   1779:     my ($srch) = @_;
                   1780:     my $dom = $srch->{'srchdomain'};
                   1781:     my %results;
                   1782:     my %libserv = &all_library();
                   1783:     my $query = 'usersearch';
                   1784:     foreach my $tryserver (keys(%libserv)) {
                   1785:         if (&host_domain($tryserver) eq $dom) {
                   1786:             my $host=&hostname($tryserver);
                   1787:             my $queryid=
1.911     raeburn  1788:                 &reply("querysend:".&escape($query).':'.
                   1789:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1790:                        &escape($srch->{'srchtype'}).':'.
                   1791:                        &escape($srch->{'srchterm'}),$tryserver);
                   1792:             if ($queryid !~/^\Q$host\E\_/) {
                   1793:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1794:                 next;
1.899     raeburn  1795:             }
                   1796:             my $reply = &get_query_reply($queryid);
                   1797:             my $maxtries = 1;
                   1798:             my $tries = 1;
                   1799:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1800:                 $reply = &get_query_reply($queryid);
                   1801:                 $tries ++;
                   1802:             }
                   1803:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1804:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1805:             } else {
1.911     raeburn  1806:                 my @matches;
                   1807:                 if ($reply =~ /\n/) {
                   1808:                     @matches = split(/\n/,$reply);
                   1809:                 } else {
                   1810:                     @matches = split(/\&/,$reply);
                   1811:                 }
1.899     raeburn  1812:                 foreach my $match (@matches) {
                   1813:                     my ($uname,$udom,%userhash);
1.911     raeburn  1814:                     foreach my $entry (split(/:/,$match)) {
                   1815:                         my ($key,$value) =
                   1816:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1817:                         $userhash{$key} = $value;
                   1818:                         if ($key eq 'username') {
                   1819:                             $uname = $value;
                   1820:                         } elsif ($key eq 'domain') {
                   1821:                             $udom = $value;
1.911     raeburn  1822:                         }
1.899     raeburn  1823:                     }
                   1824:                     $results{$uname.':'.$udom} = \%userhash;
                   1825:                 }
                   1826:             }
                   1827:         }
                   1828:     }
                   1829:     return %results;
                   1830: }
                   1831: 
1.912     raeburn  1832: sub get_instuser {
                   1833:     my ($udom,$uname,$id) = @_;
                   1834:     my $homeserver = &domain($udom,'primary');
                   1835:     my ($outcome,%results);
                   1836:     if ($homeserver ne '') {
                   1837:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1838:                            &escape($id).':'.&escape($udom),$homeserver);
                   1839:         my $host=&hostname($homeserver);
                   1840:         if ($queryid !~/^\Q$host\E\_/) {
                   1841:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1842:             return;
                   1843:         }
                   1844:         my $response = &get_query_reply($queryid);
                   1845:         my $maxtries = 5;
                   1846:         my $tries = 1;
                   1847:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1848:             $response = &get_query_reply($queryid);
                   1849:             $tries ++;
                   1850:         }
                   1851:         if (!&error($response) && $response ne 'refused') {
                   1852:             if ($response eq 'unavailable') {
                   1853:                 $outcome = $response;
                   1854:             } else {
                   1855:                 $outcome = 'ok';
                   1856:                 my @matches = split(/\n/,$response);
                   1857:                 foreach my $match (@matches) {
                   1858:                     my ($key,$value) = split(/=/,$match);
                   1859:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1860:                 }
                   1861:             }
                   1862:         }
                   1863:     }
                   1864:     my %userinfo;
                   1865:     if (ref($results{$uname}) eq 'HASH') {
                   1866:         %userinfo = %{$results{$uname}};
                   1867:     } 
                   1868:     return ($outcome,%userinfo);
                   1869: }
                   1870: 
                   1871: sub inst_rulecheck {
1.923     raeburn  1872:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1873:     my %returnhash;
                   1874:     if ($udom ne '') {
                   1875:         if (ref($rules) eq 'ARRAY') {
                   1876:             @{$rules} = map {&escape($_);} (@{$rules});
                   1877:             my $rulestr = join(':',@{$rules});
                   1878:             my $homeserver=&domain($udom,'primary');
                   1879:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1880:                 my $response;
                   1881:                 if ($item eq 'username') {                
                   1882:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1883:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1884:                                               $homeserver));
1.923     raeburn  1885:                 } elsif ($item eq 'id') {
                   1886:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1887:                                               ':'.&escape($id).':'.$rulestr,
                   1888:                                               $homeserver));
1.945     raeburn  1889:                 } elsif ($item eq 'selfcreate') {
                   1890:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1891:                                                &escape($udom).':'.&escape($uname).
                   1892:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1893:                 }
1.912     raeburn  1894:                 if ($response ne 'refused') {
                   1895:                     my @pairs=split(/\&/,$response);
                   1896:                     foreach my $item (@pairs) {
                   1897:                         my ($key,$value)=split(/=/,$item,2);
                   1898:                         $key = &unescape($key);
                   1899:                         next if ($key =~ /^error: 2 /);
                   1900:                         $returnhash{$key}=&thaw_unescape($value);
                   1901:                     }
                   1902:                 }
                   1903:             }
                   1904:         }
                   1905:     }
                   1906:     return %returnhash;
                   1907: }
                   1908: 
                   1909: sub inst_userrules {
1.923     raeburn  1910:     my ($udom,$check) = @_;
1.912     raeburn  1911:     my (%ruleshash,@ruleorder);
                   1912:     if ($udom ne '') {
                   1913:         my $homeserver=&domain($udom,'primary');
                   1914:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1915:             my $response;
                   1916:             if ($check eq 'id') {
                   1917:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1918:                                  $homeserver);
1.943     raeburn  1919:             } elsif ($check eq 'email') {
                   1920:                 $response=&reply('instemailrules:'.&escape($udom),
                   1921:                                  $homeserver);
1.923     raeburn  1922:             } else {
                   1923:                 $response=&reply('instuserrules:'.&escape($udom),
                   1924:                                  $homeserver);
                   1925:             }
1.912     raeburn  1926:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1927:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1928:                 ($response ne 'no_such_host')) {
                   1929:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1930:                 my @pairs=split(/\&/,$hashitems);
                   1931:                 foreach my $item (@pairs) {
                   1932:                     my ($key,$value)=split(/=/,$item,2);
                   1933:                     $key = &unescape($key);
                   1934:                     next if ($key =~ /^error: 2 /);
                   1935:                     $ruleshash{$key}=&thaw_unescape($value);
                   1936:                 }
                   1937:                 my @esc_order = split(/\&/,$orderitems);
                   1938:                 foreach my $item (@esc_order) {
                   1939:                     push(@ruleorder,&unescape($item));
                   1940:                 }
                   1941:             }
                   1942:         }
                   1943:     }
                   1944:     return (\%ruleshash,\@ruleorder);
                   1945: }
                   1946: 
1.976     raeburn  1947: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1948: 
                   1949: sub get_domain_defaults {
                   1950:     my ($domain) = @_;
                   1951:     my $cachetime = 60*60*24;
                   1952:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1953:     if (defined($cached)) {
                   1954:         if (ref($result) eq 'HASH') {
                   1955:             return %{$result};
                   1956:         }
                   1957:     }
                   1958:     my %domdefaults;
                   1959:     my %domconfig =
1.989     raeburn  1960:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1961:                                   'requestcourses','inststatus',
1.1183    raeburn  1962:                                   'coursedefaults','usersessions',
                   1963:                                   'requestauthor'],$domain);
1.943     raeburn  1964:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1965:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1966:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1967:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1968:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1969:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1970:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1971:     } else {
                   1972:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1973:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1974:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1975:     }
1.976     raeburn  1976:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1977:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1978:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1979:         } else {
                   1980:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1981:         } 
1.1177    raeburn  1982:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1983:         foreach my $item (@usertools) {
                   1984:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1985:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1986:             }
                   1987:         }
                   1988:     }
1.985     raeburn  1989:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1990:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1991:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1992:         }
                   1993:     }
1.1183    raeburn  1994:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   1995:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   1996:     }
1.989     raeburn  1997:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1998:         foreach my $item ('inststatustypes','inststatusorder') {
                   1999:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2000:         }
                   2001:     }
1.1047    raeburn  2002:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   2003:         foreach my $item ('canuse_pdfforms') {
                   2004:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   2005:         }
                   2006:     }
1.1073    raeburn  2007:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2008:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2009:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2010:         }
                   2011:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2012:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2013:         }
                   2014:     }
1.943     raeburn  2015:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   2016:                                   $cachetime);
                   2017:     return %domdefaults;
                   2018: }
                   2019: 
1.344     www      2020: # --------------------------------------------------- Assign a key to a student
                   2021: 
                   2022: sub assign_access_key {
1.364     www      2023: #
                   2024: # a valid key looks like uname:udom#comments
                   2025: # comments are being appended
                   2026: #
1.498     www      2027:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2028:     $kdom=
1.620     albertel 2029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2030:     $knum=
1.620     albertel 2031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2032:     $cdom=
1.620     albertel 2033:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2034:     $cnum=
1.620     albertel 2035:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2036:     $udom=$env{'user.name'} unless (defined($udom));
                   2037:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2038:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2039:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2040:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2041:                                                   # assigned to this person
                   2042:                                                   # - this should not happen,
1.345     www      2043:                                                   # unless something went wrong
                   2044:                                                   # the first time around
                   2045: # ready to assign
1.364     www      2046:         $logentry=$1.'; '.$logentry;
1.496     www      2047:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2048:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2049: # key now belongs to user
1.346     www      2050: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2051:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2052:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2053:                 return 'ok';
                   2054:             } else {
                   2055:                 return 
                   2056:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2057: 	    }
                   2058:         } else {
                   2059:             return 'error: Could not assign key, try again later.';
                   2060:         }
1.364     www      2061:     } elsif (!$existing{$ckey}) {
1.345     www      2062: # the key does not exist
                   2063: 	return 'error: The key does not exist';
                   2064:     } else {
                   2065: # the key is somebody else's
                   2066: 	return 'error: The key is already in use';
                   2067:     }
1.344     www      2068: }
                   2069: 
1.364     www      2070: # ------------------------------------------ put an additional comment on a key
                   2071: 
                   2072: sub comment_access_key {
                   2073: #
                   2074: # a valid key looks like uname:udom#comments
                   2075: # comments are being appended
                   2076: #
                   2077:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2078:     $cdom=
1.620     albertel 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2080:     $cnum=
1.620     albertel 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2082:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2083:     if ($existing{$ckey}) {
                   2084:         $existing{$ckey}.='; '.$logentry;
                   2085: # ready to assign
1.367     www      2086:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2087:                                                  $cdom,$cnum) eq 'ok') {
                   2088: 	    return 'ok';
                   2089:         } else {
                   2090: 	    return 'error: Count not store comment.';
                   2091:         }
                   2092:     } else {
                   2093: # the key does not exist
                   2094: 	return 'error: The key does not exist';
                   2095:     }
                   2096: }
                   2097: 
1.344     www      2098: # ------------------------------------------------------ Generate a set of keys
                   2099: 
                   2100: sub generate_access_keys {
1.364     www      2101:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2102:     $cdom=
1.620     albertel 2103:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2104:     $cnum=
1.620     albertel 2105:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2106:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2107:     unless (($cdom) && ($cnum)) { return 0; }
                   2108:     if ($number>10000) { return 0; }
                   2109:     sleep(2); # make sure don't get same seed twice
                   2110:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2111:     my $total=0;
                   2112:     for (my $i=1;$i<=$number;$i++) {
                   2113:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2114:                   sprintf("%lx",int(100000*rand)).'-'.
                   2115:                   sprintf("%lx",int(100000*rand));
                   2116:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2117:        $newkey=~s/0/h/g; # and also 0 and O
                   2118:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2119:        if ($existing{$newkey}) {
                   2120:            $i--;
                   2121:        } else {
1.364     www      2122: 	  if (&put('accesskeys',
                   2123:               { $newkey => '# generated '.localtime().
1.620     albertel 2124:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2125:                            '; '.$logentry },
                   2126: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2127:               $total++;
                   2128: 	  }
                   2129:        }
                   2130:     }
1.620     albertel 2131:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2132:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2133:     return $total;
                   2134: }
                   2135: 
                   2136: # ------------------------------------------------------- Validate an accesskey
                   2137: 
                   2138: sub validate_access_key {
                   2139:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2140:     $cdom=
1.620     albertel 2141:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2142:     $cnum=
1.620     albertel 2143:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2144:     $udom=$env{'user.domain'} unless (defined($udom));
                   2145:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2146:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2147:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2148: }
                   2149: 
                   2150: # ------------------------------------- Find the section of student in a course
1.652     albertel 2151: sub devalidate_getsection_cache {
                   2152:     my ($udom,$unam,$courseid)=@_;
                   2153:     my $hashid="$udom:$unam:$courseid";
                   2154:     &devalidate_cache_new('getsection',$hashid);
                   2155: }
1.298     matthew  2156: 
1.815     albertel 2157: sub courseid_to_courseurl {
                   2158:     my ($courseid) = @_;
                   2159:     #already url style courseid
                   2160:     return $courseid if ($courseid =~ m{^/});
                   2161: 
                   2162:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2163: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2164: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2165: 	return "/$cdom/$cnum";
                   2166:     }
                   2167: 
                   2168:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2169:     if (exists($courseinfo{'num'})) {
                   2170: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2171:     }
                   2172: 
                   2173:     return undef;
                   2174: }
                   2175: 
1.298     matthew  2176: sub getsection {
                   2177:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2178:     my $cachetime=1800;
1.551     albertel 2179: 
                   2180:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2181:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2182:     if (defined($cached)) { return $result; }
                   2183: 
1.298     matthew  2184:     my %Pending; 
                   2185:     my %Expired;
                   2186:     #
                   2187:     # Each role can either have not started yet (pending), be active, 
                   2188:     #    or have expired.
                   2189:     #
                   2190:     # If there is an active role, we are done.
                   2191:     #
                   2192:     # If there is more than one role which has not started yet, 
                   2193:     #     choose the one which will start sooner
                   2194:     # If there is one role which has not started yet, return it.
                   2195:     #
                   2196:     # If there is more than one expired role, choose the one which ended last.
                   2197:     # If there is a role which has expired, return it.
                   2198:     #
1.815     albertel 2199:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2200:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2201:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2202:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2203:         my $section=$1;
                   2204:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2205:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2206:         my $now=time;
1.548     albertel 2207:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2208:             $Expired{$end}=$section;
                   2209:             next;
                   2210:         }
1.548     albertel 2211:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2212:             $Pending{$start}=$section;
                   2213:             next;
                   2214:         }
1.599     albertel 2215:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2216:     }
                   2217:     #
                   2218:     # Presumedly there will be few matching roles from the above
                   2219:     # loop and the sorting time will be negligible.
                   2220:     if (scalar(keys(%Pending))) {
                   2221:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2222:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2223:     } 
                   2224:     if (scalar(keys(%Expired))) {
                   2225:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2226:         my $time = pop(@sorted);
1.599     albertel 2227:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2228:     }
1.599     albertel 2229:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2230: }
1.70      www      2231: 
1.599     albertel 2232: sub save_cache {
                   2233:     &purge_remembered();
1.722     albertel 2234:     #&Apache::loncommon::validate_page();
1.620     albertel 2235:     undef(%env);
1.780     albertel 2236:     undef($env_loaded);
1.599     albertel 2237: }
1.452     albertel 2238: 
1.599     albertel 2239: my $to_remember=-1;
                   2240: my %remembered;
                   2241: my %accessed;
                   2242: my $kicks=0;
                   2243: my $hits=0;
1.849     albertel 2244: sub make_key {
                   2245:     my ($name,$id) = @_;
1.872     albertel 2246:     if (length($id) > 65 
                   2247: 	&& length(&escape($id)) > 200) {
                   2248: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2249:     }
1.849     albertel 2250:     return &escape($name.':'.$id);
                   2251: }
                   2252: 
1.599     albertel 2253: sub devalidate_cache_new {
                   2254:     my ($name,$id,$debug) = @_;
                   2255:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2256:     $id=&make_key($name,$id);
1.599     albertel 2257:     $memcache->delete($id);
                   2258:     delete($remembered{$id});
                   2259:     delete($accessed{$id});
                   2260: }
                   2261: 
                   2262: sub is_cached_new {
                   2263:     my ($name,$id,$debug) = @_;
1.849     albertel 2264:     $id=&make_key($name,$id);
1.599     albertel 2265:     if (exists($remembered{$id})) {
1.1133    foxr     2266: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2267: 	$accessed{$id}=[&gettimeofday()];
                   2268: 	$hits++;
                   2269: 	return ($remembered{$id},1);
                   2270:     }
                   2271:     my $value = $memcache->get($id);
                   2272:     if (!(defined($value))) {
                   2273: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2274: 	return (undef,undef);
1.416     albertel 2275:     }
1.599     albertel 2276:     if ($value eq '__undef__') {
                   2277: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2278: 	$value=undef;
                   2279:     }
                   2280:     &make_room($id,$value,$debug);
                   2281:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2282:     return ($value,1);
                   2283: }
                   2284: 
                   2285: sub do_cache_new {
                   2286:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2287:     $id=&make_key($name,$id);
1.599     albertel 2288:     my $setvalue=$value;
                   2289:     if (!defined($setvalue)) {
                   2290: 	$setvalue='__undef__';
                   2291:     }
1.623     albertel 2292:     if (!defined($time) ) {
                   2293: 	$time=600;
                   2294:     }
1.599     albertel 2295:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2296:     my $result = $memcache->set($id,$setvalue,$time);
                   2297:     if (! $result) {
1.872     albertel 2298: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2299: 	$memcache->disconnect_all();
1.872     albertel 2300:     }
1.600     albertel 2301:     # need to make a copy of $value
1.919     albertel 2302:     &make_room($id,$value,$debug);
1.599     albertel 2303:     return $value;
                   2304: }
                   2305: 
                   2306: sub make_room {
                   2307:     my ($id,$value,$debug)=@_;
1.919     albertel 2308: 
                   2309:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2310:                                     : $value;
1.599     albertel 2311:     if ($to_remember<0) { return; }
                   2312:     $accessed{$id}=[&gettimeofday()];
                   2313:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2314:     my $to_kick;
                   2315:     my $max_time=0;
                   2316:     foreach my $other (keys(%accessed)) {
                   2317: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2318: 	    $to_kick=$other;
                   2319: 	    $max_time=&tv_interval($accessed{$other});
                   2320: 	}
                   2321:     }
                   2322:     delete($remembered{$to_kick});
                   2323:     delete($accessed{$to_kick});
                   2324:     $kicks++;
                   2325:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2326:     return;
                   2327: }
                   2328: 
1.599     albertel 2329: sub purge_remembered {
1.604     albertel 2330:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2331:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2332:     undef(%remembered);
                   2333:     undef(%accessed);
1.428     albertel 2334: }
1.70      www      2335: # ------------------------------------- Read an entry from a user's environment
                   2336: 
                   2337: sub userenvironment {
                   2338:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2339:     my $items;
                   2340:     foreach my $item (@what) {
                   2341:         $items.=&escape($item).'&';
                   2342:     }
                   2343:     $items=~s/\&$//;
1.70      www      2344:     my %returnhash=();
1.1009    raeburn  2345:     my $uhome = &homeserver($unam,$udom);
                   2346:     unless ($uhome eq 'no_host') {
                   2347:         my @answer=split(/\&/, 
                   2348:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2349:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2350:             return %returnhash;
                   2351:         }
1.1009    raeburn  2352:         my $i;
                   2353:         for ($i=0;$i<=$#what;$i++) {
                   2354: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2355:         }
1.70      www      2356:     }
                   2357:     return %returnhash;
1.1       albertel 2358: }
                   2359: 
1.617     albertel 2360: # ---------------------------------------------------------- Get a studentphoto
                   2361: sub studentphoto {
                   2362:     my ($udom,$unam,$ext) = @_;
                   2363:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2364:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2365:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2366:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2367:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2368:             } else {
                   2369:                 my ($result,$perm_reqd)=
1.707     albertel 2370: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2371:                 if ($result eq 'ok') {
                   2372:                     if (!($perm_reqd eq 'yes')) {
                   2373:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2374:                     }
                   2375:                 }
                   2376:             }
                   2377:         }
                   2378:     } else {
                   2379:         my ($result,$perm_reqd) = 
1.707     albertel 2380: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2381:         if ($result eq 'ok') {
                   2382:             if (!($perm_reqd eq 'yes')) {
                   2383:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2384:             }
                   2385:         }
                   2386:     }
                   2387:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2388: }
                   2389: 
                   2390: sub retrievestudentphoto {
                   2391:     my ($udom,$unam,$ext,$type) = @_;
                   2392:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2393:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2394:     if ($ret eq 'ok') {
                   2395:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2396:         if ($type eq 'thumbnail') {
                   2397:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2398:         }
                   2399:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2400:         return $tokenurl;
                   2401:     } else {
                   2402:         if ($type eq 'thumbnail') {
                   2403:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2404:         } else { 
                   2405:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2406:         }
1.617     albertel 2407:     }
                   2408: }
                   2409: 
1.263     www      2410: # -------------------------------------------------------------------- New chat
                   2411: 
                   2412: sub chatsend {
1.724     raeburn  2413:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2414:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2415:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2416:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2417:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2418: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2419: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2420: }
                   2421: 
                   2422: # ------------------------------------------ Find current version of a resource
                   2423: 
                   2424: sub getversion {
                   2425:     my $fname=&clutter(shift);
1.1189    raeburn  2426:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2427:     return &currentversion(&filelocation('',$fname));
                   2428: }
                   2429: 
                   2430: sub currentversion {
                   2431:     my $fname=shift;
                   2432:     my $author=$fname;
                   2433:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2434:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2435:     my $home=&homeserver($uname,$udom);
1.292     www      2436:     if ($home eq 'no_host') { 
                   2437:         return -1; 
                   2438:     }
1.1112    www      2439:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2440:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2441: 	return -1;
                   2442:     }
1.1112    www      2443:     return $answer;
1.263     www      2444: }
                   2445: 
1.1111    www      2446: #
                   2447: # Return special version number of resource if set by override, empty otherwise
                   2448: #
                   2449: sub usedversion {
                   2450:     my $fname=shift;
                   2451:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2452:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2453:     if ($urlversion) { return $urlversion; }
                   2454:     return '';
                   2455: }
                   2456: 
1.1       albertel 2457: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2458: 
1.1       albertel 2459: sub subscribe {
                   2460:     my $fname=shift;
1.761     raeburn  2461:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2462:     $fname=~s/[\n\r]//g;
1.1       albertel 2463:     my $author=$fname;
                   2464:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2465:     my ($udom,$uname)=split(/\//,$author);
                   2466:     my $home=homeserver($uname,$udom);
1.335     albertel 2467:     if ($home eq 'no_host') {
                   2468:         return 'not_found';
1.1       albertel 2469:     }
                   2470:     my $answer=reply("sub:$fname",$home);
1.64      www      2471:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2472: 	$answer.=' by '.$home;
                   2473:     }
1.1       albertel 2474:     return $answer;
                   2475: }
                   2476:     
1.8       www      2477: # -------------------------------------------------------------- Replicate file
                   2478: 
                   2479: sub repcopy {
                   2480:     my $filename=shift;
1.23      www      2481:     $filename=~s/\/+/\//g;
1.1142    raeburn  2482:     my $londocroot = $perlvar{'lonDocRoot'};
                   2483:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2484:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2485:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2486: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2487: 	return &repcopy_userfile($filename);
                   2488:     }
1.532     albertel 2489:     $filename=~s/[\n\r]//g;
1.8       www      2490:     my $transname="$filename.in.transfer";
1.828     www      2491: # FIXME: this should flock
1.607     raeburn  2492:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2493:     my $remoteurl=subscribe($filename);
1.64      www      2494:     if ($remoteurl =~ /^con_lost by/) {
                   2495: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2496:            return 'unavailable';
1.8       www      2497:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2498: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2499: 	   return 'not_found';
1.64      www      2500:     } elsif ($remoteurl =~ /^rejected by/) {
                   2501: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2502:            return 'forbidden';
1.20      www      2503:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2504:            return 'ok';
1.8       www      2505:     } else {
1.290     www      2506:         my $author=$filename;
                   2507:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2508:         my ($udom,$uname)=split(/\//,$author);
                   2509:         my $home=homeserver($uname,$udom);
                   2510:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2511:            my @parts=split(/\//,$filename);
                   2512:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2513:            if ($path ne "$londocroot/res") {
1.8       www      2514:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2515: 	       return 'bad_request';
1.8       www      2516:            }
                   2517:            my $count;
                   2518:            for ($count=5;$count<$#parts;$count++) {
                   2519:                $path.="/$parts[$count]";
                   2520:                if ((-e $path)!=1) {
                   2521: 		   mkdir($path,0777);
                   2522:                }
                   2523:            }
                   2524:            my $ua=new LWP::UserAgent;
                   2525:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2526:            my $response=$ua->request($request,$transname);
                   2527:            if ($response->is_error()) {
                   2528: 	       unlink($transname);
                   2529:                my $message=$response->status_line;
1.672     albertel 2530:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2531:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2532:                return 'unavailable';
1.8       www      2533:            } else {
1.16      www      2534: 	       if ($remoteurl!~/\.meta$/) {
                   2535:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2536:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2537:                   if ($mresponse->is_error()) {
                   2538: 		      unlink($filename.'.meta');
                   2539:                       &logthis(
1.672     albertel 2540:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2541:                   }
                   2542: 	       }
1.8       www      2543:                rename($transname,$filename);
1.607     raeburn  2544:                return 'ok';
1.8       www      2545:            }
1.290     www      2546:        }
1.8       www      2547:     }
1.330     www      2548: }
                   2549: 
                   2550: # ------------------------------------------------ Get server side include body
                   2551: sub ssi_body {
1.381     albertel 2552:     my ($filelink,%form)=@_;
1.606     matthew  2553:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2554:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2555:     }
1.953     www      2556:     my $output='';
                   2557:     my $response;
1.980     raeburn  2558:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2559:        ($output,$response)=&externalssi($filelink);
1.953     www      2560:     } else {
1.1004    droeschl 2561:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2562:        $filelink .= 'inhibitmenu=yes';
1.953     www      2563:        ($output,$response)=&ssi($filelink,%form);
                   2564:     }
1.778     albertel 2565:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2566:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2567:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2568:     if (wantarray) {
                   2569:         return ($output, $response);
                   2570:     } else {
                   2571:         return $output;
                   2572:     }
1.8       www      2573: }
                   2574: 
1.15      www      2575: # --------------------------------------------------------- Server Side Include
                   2576: 
1.782     albertel 2577: sub absolute_url {
                   2578:     my ($host_name) = @_;
                   2579:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2580:     if ($host_name eq '') {
                   2581: 	$host_name = $ENV{'SERVER_NAME'};
                   2582:     }
                   2583:     return $protocol.$host_name;
                   2584: }
                   2585: 
1.942     foxr     2586: #
                   2587: #   Server side include.
                   2588: # Parameters:
                   2589: #  fn     Possibly encrypted resource name/id.
                   2590: #  form   Hash that describes how the rendering should be done
                   2591: #         and other things.
1.944     foxr     2592: # Returns:
1.950     raeburn  2593: #   Scalar context: The content of the response.
                   2594: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2595: #     
1.15      www      2596: sub ssi {
                   2597: 
1.944     foxr     2598:     my ($fn,%form)=@_;
1.15      www      2599:     my $ua=new LWP::UserAgent;
1.23      www      2600:     my $request;
1.711     albertel 2601: 
                   2602:     $form{'no_update_last_known'}=1;
1.895     albertel 2603:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2604:     if (%form) {
1.782     albertel 2605:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2606:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2607:     } else {
1.782     albertel 2608:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2609:     }
                   2610: 
1.15      www      2611:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2612:     my $response= $ua->request($request);
1.1182    foxr     2613:     my $content = $response->content;
                   2614: 
                   2615: 
1.944     foxr     2616:     if (wantarray) {
1.1173    foxr     2617: 	return ($content, $response);
1.944     foxr     2618:     } else {
1.1173    foxr     2619: 	return $content;
1.942     foxr     2620:     }
1.324     www      2621: }
                   2622: 
                   2623: sub externalssi {
                   2624:     my ($url)=@_;
                   2625:     my $ua=new LWP::UserAgent;
                   2626:     my $request=new HTTP::Request('GET',$url);
                   2627:     my $response=$ua->request($request);
1.954     raeburn  2628:     if (wantarray) {
                   2629:         return ($response->content, $response);
                   2630:     } else {
                   2631:         return $response->content;
                   2632:     }
1.15      www      2633: }
1.254     www      2634: 
1.492     albertel 2635: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2636: 
                   2637: sub allowuploaded {
                   2638:     my ($srcurl,$url)=@_;
                   2639:     $url=&clutter(&declutter($url));
                   2640:     my $dir=$url;
                   2641:     $dir=~s/\/[^\/]+$//;
                   2642:     my %httpref=();
                   2643:     my $httpurl=&hreflocation('',$url);
                   2644:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2645:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2646: }
1.477     raeburn  2647: 
1.1193  ! raeburn  2648: #
        !          2649: # Determine if the current user should be able to edit a particular resource,
        !          2650: # when viewing in course context.
        !          2651: # (a) When viewing resource used to determine if "Edit" item is included in 
        !          2652: #     Functions.
        !          2653: # (b) When displaying folder contents in course editor, used to determine if
        !          2654: #     "Edit" link will be displayed alongside resource.
        !          2655: #
        !          2656: #  input: 3 args -- filename (decluttered), course number and course domain.
        !          2657: #  output: array of four scalars -- 
        !          2658: #          $cfile -- url for file editing if editable on current server
        !          2659: #          $home -- homeserver of resource (i.e., for author if published,
        !          2660: #                                           or course if uploaded.).
        !          2661: #          $switchserver --  1 if server switch will be needed.
        !          2662: #          $uploaded -- 1 if resource is a file uploaded to a course.
        !          2663: #
        !          2664: 
        !          2665: sub can_edit_resource {
        !          2666:     my ($file,$cnum,$cdom) = @_;
        !          2667:     my ($cfile,$home,$switchserver,$uploaded);
        !          2668:     if ($file ne '') {
        !          2669:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
        !          2670:             $uploaded = &is_course_upload($file,$cnum,$cdom);
        !          2671:             if ($uploaded) {
        !          2672:                 $home=&homeserver($cnum,$cdom);
        !          2673:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
        !          2674:                     $cfile = &hreflocation('',$file);
        !          2675:                 }
        !          2676:             }
        !          2677:         }
        !          2678:         unless ($uploaded) {
        !          2679:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
        !          2680:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
        !          2681:             # Check that the user has permission to edit this resource
        !          2682:             my $setpriv = 1;
        !          2683:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
        !          2684:             if (defined($cfudom)) {
        !          2685:                 $home=&homeserver($cfuname,$cfudom);
        !          2686:                 $cfile=$file;
        !          2687:             }
        !          2688:         }
        !          2689:         if (($cfile ne '') && (($home ne '') && ($home ne 'no_host'))) {
        !          2690:             my @ids=&current_machine_ids();
        !          2691:             unless (grep(/^\Q$home\E$/,@ids)) {
        !          2692:                 $switchserver=1;
        !          2693:             }
        !          2694:         }
        !          2695:     }
        !          2696:     return ($cfile,$home,$switchserver,$uploaded);
        !          2697: }
        !          2698: 
        !          2699: sub is_course_upload {
        !          2700:     my ($file,$cnum,$cdom) = @_;
        !          2701:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
        !          2702:     $uploadpath =~ s{^\/}{};
        !          2703:     if (($file =~ m{^\Q$uploadpath\E/userfiles/docs/}) ||
        !          2704:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/docs/})) {
        !          2705:         return 1;
        !          2706:     }
        !          2707:     return;
        !          2708: }
        !          2709: 
1.478     albertel 2710: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2711: # input: action, courseID, current domain, intended
1.637     raeburn  2712: #        path to file, source of file, instruction to parse file for objects,
                   2713: #        ref to hash for embedded objects,
                   2714: #        ref to hash for codebase of java objects.
1.1095    raeburn  2715: #        reference to scalar to accommodate mime type determined
                   2716: #          from File::MMagic if $parser = parse.
1.637     raeburn  2717: #
1.485     raeburn  2718: # output: url to file (if action was uploaddoc), 
                   2719: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2720: #
1.478     albertel 2721: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2722: # course.
1.477     raeburn  2723: #
1.478     albertel 2724: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2725: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2726: #          course's home server.
1.477     raeburn  2727: #
1.478     albertel 2728: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2729: #          be copied from $source (current location) to 
                   2730: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2731: #         and will then be copied to
                   2732: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2733: #         course's home server.
1.485     raeburn  2734: #
1.481     raeburn  2735: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2736: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2737: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2738: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2739: #         in course's home server.
1.637     raeburn  2740: #
1.477     raeburn  2741: 
                   2742: sub process_coursefile {
1.1095    raeburn  2743:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2744:         $mimetype)=@_;
1.477     raeburn  2745:     my $fetchresult;
1.638     albertel 2746:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2747:     if ($action eq 'propagate') {
1.638     albertel 2748:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2749: 			     $home);
1.481     raeburn  2750:     } else {
1.477     raeburn  2751:         my $fpath = '';
                   2752:         my $fname = $file;
1.478     albertel 2753:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2754:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2755:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2756:         if ($action eq 'copy') {
                   2757:             if ($source eq '') {
                   2758:                 $fetchresult = 'no source file';
                   2759:                 return $fetchresult;
                   2760:             } else {
                   2761:                 my $destination = $filepath.'/'.$fname;
                   2762:                 rename($source,$destination);
                   2763:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2764:                                  $home);
1.481     raeburn  2765:             }
                   2766:         } elsif ($action eq 'uploaddoc') {
                   2767:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2768:             print $fh $env{'form.'.$source};
1.481     raeburn  2769:             close($fh);
1.637     raeburn  2770:             if ($parser eq 'parse') {
1.1024    raeburn  2771:                 my $mm = new File::MMagic;
1.1095    raeburn  2772:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2773:                 if ($type eq 'text/html') {
1.1024    raeburn  2774:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2775:                     unless ($parse_result eq 'ok') {
                   2776:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2777:                     }
1.637     raeburn  2778:                 }
1.1095    raeburn  2779:                 if (ref($mimetype)) {
                   2780:                     $$mimetype = $type;
                   2781:                 } 
1.637     raeburn  2782:             }
1.477     raeburn  2783:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2784:                                  $home);
1.481     raeburn  2785:             if ($fetchresult eq 'ok') {
                   2786:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2787:             } else {
                   2788:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2789:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2790:                 return '/adm/notfound.html';
                   2791:             }
1.477     raeburn  2792:         }
                   2793:     }
1.485     raeburn  2794:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2795:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2796:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2797:     }
                   2798:     return $fetchresult;
                   2799: }
                   2800: 
1.637     raeburn  2801: sub build_filepath {
                   2802:     my ($fpath) = @_;
                   2803:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2804:     unless ($fpath eq '') {
                   2805:         my @parts=split('/',$fpath);
                   2806:         foreach my $part (@parts) {
                   2807:             $filepath.= '/'.$part;
                   2808:             if ((-e $filepath)!=1) {
                   2809:                 mkdir($filepath,0777);
                   2810:             }
                   2811:         }
                   2812:     }
                   2813:     return $filepath;
                   2814: }
                   2815: 
                   2816: sub store_edited_file {
1.638     albertel 2817:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2818:     my $file = $primary_url;
                   2819:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2820:     my $fpath = '';
                   2821:     my $fname = $file;
                   2822:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2823:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2824:     my $filepath = &build_filepath($fpath);
                   2825:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2826:     print $fh $content;
                   2827:     close($fh);
1.638     albertel 2828:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2829:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2830: 			  $home);
1.637     raeburn  2831:     if ($$fetchresult eq 'ok') {
                   2832:         return '/uploaded/'.$fpath.'/'.$fname;
                   2833:     } else {
1.638     albertel 2834:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2835: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2836:         return '/adm/notfound.html';
                   2837:     }
                   2838: }
                   2839: 
1.531     albertel 2840: sub clean_filename {
1.831     albertel 2841:     my ($fname,$args)=@_;
1.315     www      2842: # Replace Windows backslashes by forward slashes
1.257     www      2843:     $fname=~s/\\/\//g;
1.831     albertel 2844:     if (!$args->{'keep_path'}) {
                   2845:         # Get rid of everything but the actual filename
                   2846: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2847:     }
1.315     www      2848: # Replace spaces by underscores
                   2849:     $fname=~s/\s+/\_/g;
                   2850: # Replace all other weird characters by nothing
1.831     albertel 2851:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2852: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2853: # numbers
                   2854:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2855:     return $fname;
                   2856: }
1.1051    raeburn  2857: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2858: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2859: # image with the same aspect ratio as the original, but with dimensions which do 
                   2860: # not exceed $resizewidth and $resizeheight.
                   2861:  
1.984     neumanie 2862: sub resizeImage {
1.1051    raeburn  2863:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2864:     my $ima = Image::Magick->new;
                   2865:     my $resized;
                   2866:     if (-e $img_path) {
                   2867:         $ima->Read($img_path);
                   2868:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2869:             my $width = $ima->Get('width');
                   2870:             my $height = $ima->Get('height');
                   2871:             if ($width > $resizewidth) {
                   2872: 	        my $factor = $width/$resizewidth;
                   2873:                 my $newheight = $height/$factor;
                   2874:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2875:                 $resized = 1;
                   2876:             }
                   2877:         }
                   2878:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2879:             my $width = $ima->Get('width');
                   2880:             my $height = $ima->Get('height');
                   2881:             if ($height > $resizeheight) {
                   2882:                 my $factor = $height/$resizeheight;
                   2883:                 my $newwidth = $width/$factor;
                   2884:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2885:                 $resized = 1;
                   2886:             }
                   2887:         }
                   2888:         if ($resized) {
                   2889:             $ima->Write($img_path);
                   2890:         }
                   2891:     }
                   2892:     return;
1.977     amueller 2893: }
                   2894: 
1.608     albertel 2895: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2896: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2897: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2898: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2899: #                                    canceloverwrite, or ''. 
                   2900: #                   if 'coursedoc': upload to the current course
                   2901: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2902: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2903: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2904: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2905: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2906: #        $allfiles - reference to hash for embedded objects
                   2907: #        $codebase - reference to hash for codebase of java objects
                   2908: #        $desuname - username for permanent storage of uploaded file
                   2909: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2910: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2911: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2912: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2913: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2914: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2915: #                    from File::MMagic.
1.858     raeburn  2916: # 
1.686     albertel 2917: # output: url of file in userspace, or error: <message> 
                   2918: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2919: 
1.531     albertel 2920: sub userfileupload {
1.1090    raeburn  2921:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2922:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2923:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2924:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2925:     $fname=&clean_filename($fname);
1.1090    raeburn  2926:     # See if there is anything left
1.257     www      2927:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2928:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2929:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2930:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2931:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2932:         my $now = time;
1.1090    raeburn  2933:         my $filepath;
1.1095    raeburn  2934:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2935:              $filepath = 'tmp/helprequests/'.$now;
                   2936:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2937:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2938:                          '_'.$env{'user.domain'}.'/pending';
                   2939:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2940:             my ($docuname,$docudom);
                   2941:             if ($destudom) {
                   2942:                 $docudom = $destudom;
                   2943:             } else {
                   2944:                 $docudom = $env{'user.domain'};
                   2945:             }
                   2946:             if ($destuname) {
                   2947:                 $docuname = $destuname;
                   2948:             } else {
                   2949:                 $docuname = $env{'user.name'};
                   2950:             }
                   2951:             if (exists($env{'form.group'})) {
                   2952:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2953:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2954:             }
                   2955:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2956:             if ($context eq 'canceloverwrite') {
                   2957:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2958:                 if (-e  $tempfile) {
                   2959:                     my @info = stat($tempfile);
                   2960:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2961:                         unlink($tempfile);
                   2962:                     }
                   2963:                 }
                   2964:                 return;
1.523     raeburn  2965:             }
                   2966:         }
1.1090    raeburn  2967:         # Create the directory if not present
1.741     raeburn  2968:         my @parts=split(/\//,$filepath);
                   2969:         my $fullpath = $perlvar{'lonDaemons'};
                   2970:         for (my $i=0;$i<@parts;$i++) {
                   2971:             $fullpath .= '/'.$parts[$i];
                   2972:             if ((-e $fullpath)!=1) {
                   2973:                 mkdir($fullpath,0777);
                   2974:             }
                   2975:         }
                   2976:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2977:         print $fh $env{'form.'.$formname};
                   2978:         close($fh);
1.1090    raeburn  2979:         if ($context eq 'existingfile') {
                   2980:             my @info = stat($fullpath.'/'.$fname);
                   2981:             return ($fullpath.'/'.$fname,$info[9]);
                   2982:         } else {
                   2983:             return $fullpath.'/'.$fname;
                   2984:         }
1.523     raeburn  2985:     }
1.995     raeburn  2986:     if ($subdir eq 'scantron') {
                   2987:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2988:     } else {
1.995     raeburn  2989:         $fname="$subdir/$fname";
                   2990:     }
1.1090    raeburn  2991:     if ($context eq 'coursedoc') {
1.638     albertel 2992: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2993: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2994:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2995:             return &finishuserfileupload($docuname,$docudom,
                   2996: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2997: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2998:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2999:         } else {
1.620     albertel 3000:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 3001:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3002: 				       $fname,$formname,$parser,
1.1095    raeburn  3003: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3004:         }
1.719     banghart 3005:     } elsif (defined($destuname)) {
                   3006:         my $docuname=$destuname;
                   3007:         my $docudom=$destudom;
1.860     raeburn  3008: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3009: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3010:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3011:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3012:     } else {
1.638     albertel 3013:         my $docuname=$env{'user.name'};
                   3014:         my $docudom=$env{'user.domain'};
1.714     raeburn  3015:         if (exists($env{'form.group'})) {
                   3016:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3017:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3018:         }
1.860     raeburn  3019: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3020: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3021:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3022:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3023:     }
1.271     www      3024: }
                   3025: 
                   3026: sub finishuserfileupload {
1.860     raeburn  3027:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3028:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3029:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3030:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3031:   
1.860     raeburn  3032:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3033:     $file=$fname;
                   3034:     if ($fname=~m|/|) {
                   3035:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3036: 	$path.=$fnamepath.'/';
                   3037:     }
1.259     www      3038:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3039:     my $count;
                   3040:     for ($count=4;$count<=$#parts;$count++) {
                   3041:         $filepath.="/$parts[$count]";
                   3042:         if ((-e $filepath)!=1) {
                   3043: 	    mkdir($filepath,0777);
                   3044:         }
                   3045:     }
1.984     neumanie 3046: 
1.258     www      3047: # Save the file
                   3048:     {
1.701     albertel 3049: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3050: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3051: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3052: 	    return '/adm/notfound.html';
                   3053: 	}
1.1090    raeburn  3054:         if ($context eq 'overwrite') {
1.1117    foxr     3055:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3056:             my $target = $filepath.'/'.$file;
                   3057:             if (-e $source) {
                   3058:                 my @info = stat($source);
                   3059:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3060:                     unless (&File::Copy::move($source,$target)) {
                   3061:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3062:                         return "Moving from $source failed";
                   3063:                     }
                   3064:                 } else {
                   3065:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3066:                 }
                   3067:             } else {
                   3068:                 return "Temporary file: $source missing";
                   3069:             }
                   3070:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3071: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3072: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3073: 	    return '/adm/notfound.html';
                   3074: 	}
1.570     albertel 3075: 	close(FH);
1.1051    raeburn  3076:         if ($resizewidth && $resizeheight) {
                   3077:             my $mm = new File::MMagic;
                   3078:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3079:             if ($mime_type =~ m{^image/}) {
                   3080: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3081:             }  
1.977     amueller 3082: 	}
1.258     www      3083:     }
1.1152    raeburn  3084:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3085:         if (ref($mimetype)) {
                   3086:             if ($$mimetype eq '') {
                   3087:                 my $mm = new File::MMagic;
                   3088:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3089:                 $$mimetype = $type;
                   3090:             }
                   3091:         }
                   3092:     }
1.637     raeburn  3093:     if ($parser eq 'parse') {
1.1152    raeburn  3094:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3095:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3096:                                                        $allfiles,$codebase);
                   3097:             unless ($parse_result eq 'ok') {
                   3098:                 &logthis('Failed to parse '.$filepath.$file.
                   3099: 	   	         ' for embedded media: '.$parse_result); 
                   3100:             }
1.637     raeburn  3101:         }
                   3102:     }
1.860     raeburn  3103:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3104:         my $input = $filepath.'/'.$file;
                   3105:         my $output = $filepath.'/'.'tn-'.$file;
                   3106:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3107:         system("convert -sample $thumbsize $input $output");
                   3108:         if (-e $filepath.'/'.'tn-'.$file) {
                   3109:             $fetchthumb  = 1; 
                   3110:         }
                   3111:     }
1.858     raeburn  3112:  
1.259     www      3113: # Notify homeserver to grep it
                   3114: #
1.984     neumanie 3115:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3116:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3117:     if ($fetchresult eq 'ok') {
1.860     raeburn  3118:         if ($fetchthumb) {
                   3119:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3120:             if ($thumbresult ne 'ok') {
                   3121:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3122:                          $docuhome.': '.$thumbresult);
                   3123:             }
                   3124:         }
1.259     www      3125: #
1.258     www      3126: # Return the URL to it
1.494     albertel 3127:         return '/uploaded/'.$path.$file;
1.263     www      3128:     } else {
1.494     albertel 3129:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3130: 		 ': '.$fetchresult);
1.263     www      3131:         return '/adm/notfound.html';
1.858     raeburn  3132:     }
1.493     albertel 3133: }
                   3134: 
1.637     raeburn  3135: sub extract_embedded_items {
1.961     raeburn  3136:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3137:     my @state = ();
1.1164    raeburn  3138:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3139:     my %javafiles = (
                   3140:                       codebase => '',
                   3141:                       code => '',
                   3142:                       archive => ''
                   3143:                     );
                   3144:     my %mediafiles = (
                   3145:                       src => '',
                   3146:                       movie => '',
                   3147:                      );
1.648     raeburn  3148:     my $p;
                   3149:     if ($content) {
                   3150:         $p = HTML::LCParser->new($content);
                   3151:     } else {
1.961     raeburn  3152:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3153:     }
1.641     albertel 3154:     while (my $t=$p->get_token()) {
1.640     albertel 3155: 	if ($t->[0] eq 'S') {
                   3156: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3157: 	    push(@state, $tagname);
1.648     raeburn  3158:             if (lc($tagname) eq 'allow') {
                   3159:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3160:             }
1.640     albertel 3161: 	    if (lc($tagname) eq 'img') {
                   3162: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3163: 	    }
1.886     albertel 3164: 	    if (lc($tagname) eq 'a') {
                   3165: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3166: 	    }
1.645     raeburn  3167:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3168:                 my $src;
1.645     raeburn  3169:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3170:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3171:                 } else {
1.1164    raeburn  3172:                     if ($attr->{'src'} ne '') {
                   3173:                         $src = $attr->{'src'};
                   3174:                         &add_filetype($allfiles,$src,'src');
                   3175:                     }
                   3176:                 }
                   3177:                 my $text = $p->get_trimmed_text();
                   3178:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3179:                     my @swfargs = split(/,/,$1);
                   3180:                     foreach my $item (@swfargs) {
                   3181:                         $item =~ s/["']//g;
                   3182:                         $item =~ s/^\s+//;
                   3183:                         $item =~ s/\s+$//;
                   3184:                     }
                   3185:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3186:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3187:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3188:                         } else {
                   3189:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3190:                         }
                   3191:                     }
1.645     raeburn  3192:                 }
                   3193:             }
                   3194:             if (lc($tagname) eq 'link') {
                   3195:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3196:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3197:                 }
                   3198:             }
1.640     albertel 3199: 	    if (lc($tagname) eq 'object' ||
                   3200: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3201: 		foreach my $item (keys(%javafiles)) {
                   3202: 		    $javafiles{$item} = '';
                   3203: 		}
1.1164    raeburn  3204:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3205:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3206:                 }
1.640     albertel 3207: 	    }
                   3208: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3209: 		my $name = lc($attr->{'name'});
                   3210: 		foreach my $item (keys(%javafiles)) {
                   3211: 		    if ($name eq $item) {
                   3212: 			$javafiles{$item} = $attr->{'value'};
                   3213: 			last;
                   3214: 		    }
                   3215: 		}
1.1164    raeburn  3216:                 my $pathfrom;
1.640     albertel 3217: 		foreach my $item (keys(%mediafiles)) {
                   3218: 		    if ($name eq $item) {
1.1164    raeburn  3219:                         $pathfrom = $attr->{'value'};
                   3220:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3221: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3222: 			last;
                   3223: 		    }
                   3224: 		}
1.1164    raeburn  3225:                 if ($name eq 'flashvars') {
                   3226:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3227:                 }
                   3228:                 if ($pathfrom ne '') {
                   3229:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3230:                                          $pathfrom);
                   3231:                 }
1.640     albertel 3232: 	    }
                   3233: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3234: 		foreach my $item (keys(%javafiles)) {
                   3235: 		    if ($attr->{$item}) {
                   3236: 			$javafiles{$item} = $attr->{$item};
                   3237: 			last;
                   3238: 		    }
                   3239: 		}
                   3240: 		foreach my $item (keys(%mediafiles)) {
                   3241: 		    if ($attr->{$item}) {
                   3242: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3243: 			last;
                   3244: 		    }
                   3245: 		}
1.1164    raeburn  3246:                 if (lc($tagname) eq 'embed') {
                   3247:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3248:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3249:                                              $attr->{'src'});
                   3250:                     }
                   3251:                 }
1.640     albertel 3252: 	    }
1.1164    raeburn  3253:             if ($t->[4] =~ m{/>$}) {
                   3254:                 pop(@state);  
                   3255:             }
1.640     albertel 3256: 	} elsif ($t->[0] eq 'E') {
                   3257: 	    my ($tagname) = ($t->[1]);
                   3258: 	    if ($javafiles{'codebase'} ne '') {
                   3259: 		$javafiles{'codebase'} .= '/';
                   3260: 	    }  
                   3261: 	    if (lc($tagname) eq 'applet' ||
                   3262: 		lc($tagname) eq 'object' ||
                   3263: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3264: 		) {
                   3265: 		foreach my $item (keys(%javafiles)) {
                   3266: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3267: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3268: 			&add_filetype($allfiles,$file,$item);
                   3269: 		    }
                   3270: 		}
                   3271: 	    } 
                   3272: 	    pop @state;
                   3273: 	}
                   3274:     }
1.1164    raeburn  3275:     foreach my $id (sort(keys(%flashvars))) {
                   3276:         if ($shockwave{$id} ne '') {
                   3277:             my @pairs = split(/\&/,$flashvars{$id});
                   3278:             foreach my $pair (@pairs) {
                   3279:                 my ($key,$value) = split(/\=/,$pair);
                   3280:                 if ($key eq 'thumb') {
                   3281:                     &add_filetype($allfiles,$value,$key);
                   3282:                 } elsif ($key eq 'content') {
                   3283:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3284:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3285:                     if ($ext ne '') {
                   3286:                         &add_filetype($allfiles,$path.$value,$ext);
                   3287:                     }
                   3288:                 }
                   3289:             }
                   3290:         }
                   3291:     }
1.637     raeburn  3292:     return 'ok';
                   3293: }
                   3294: 
1.639     albertel 3295: sub add_filetype {
                   3296:     my ($allfiles,$file,$type)=@_;
                   3297:     if (exists($allfiles->{$file})) {
                   3298: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3299: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3300: 	}
                   3301:     } else {
                   3302: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3303:     }
                   3304: }
                   3305: 
1.1164    raeburn  3306: sub embedded_dependency {
                   3307:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3308:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3309:         if (($identifier ne '') &&
                   3310:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3311:             ($pathfrom ne '')) {
                   3312:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3313:             foreach my $dep (@{$related->{$identifier}}) {
                   3314:                 &add_filetype($allfiles,$path.$dep,'object');
                   3315:             }
                   3316:         }
                   3317:     }
                   3318:     return;
                   3319: }
                   3320: 
1.493     albertel 3321: sub removeuploadedurl {
1.984     neumanie 3322:     my ($url)=@_;	
                   3323:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3324:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3325: }
                   3326: 
                   3327: sub removeuserfile {
                   3328:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3329:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3330:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3331:     if ($result eq 'ok') {	
1.798     raeburn  3332:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3333:             my $metafile = $fname.'.meta';
                   3334:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3335: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3336:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3337:             my $sqlresult = 
1.823     albertel 3338:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3339:                                         'portfolio_metadata',$group,
                   3340:                                         'delete');
1.798     raeburn  3341:         }
                   3342:     }
                   3343:     return $result;
1.257     www      3344: }
1.15      www      3345: 
1.530     albertel 3346: sub mkdiruserfile {
                   3347:     my ($docuname,$docudom,$dir)=@_;
                   3348:     my $home=&homeserver($docuname,$docudom);
                   3349:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3350: }
                   3351: 
1.531     albertel 3352: sub renameuserfile {
                   3353:     my ($docuname,$docudom,$old,$new)=@_;
                   3354:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3355:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3356:                         &escape("$old").':'.&escape("$new"),$home);
                   3357:     if ($result eq 'ok') {
                   3358:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3359:             my $oldmeta = $old.'.meta';
                   3360:             my $newmeta = $new.'.meta';
                   3361:             my $metaresult = 
                   3362:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3363: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3364:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3365:             my $sqlresult = 
1.823     albertel 3366:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3367:                                         'portfolio_metadata',$group,
                   3368:                                         'delete');
1.798     raeburn  3369:         }
                   3370:     }
                   3371:     return $result;
1.531     albertel 3372: }
                   3373: 
1.14      www      3374: # ------------------------------------------------------------------------- Log
                   3375: 
                   3376: sub log {
                   3377:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3378:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3379: }
                   3380: 
                   3381: # ------------------------------------------------------------------ Course Log
1.352     www      3382: #
                   3383: # This routine flushes several buffers of non-mission-critical nature
                   3384: #
1.157     www      3385: 
                   3386: sub flushcourselogs {
1.352     www      3387:     &logthis('Flushing log buffers');
                   3388: #
                   3389: # course logs
                   3390: # This is a log of all transactions in a course, which can be used
                   3391: # for data mining purposes
                   3392: #
                   3393: # It also collects the courseid database, which lists last transaction
                   3394: # times and course titles for all courseids
                   3395: #
                   3396:     my %courseidbuffer=();
1.921     raeburn  3397:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3398:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3399: 		          &escape($courselogs{$crsid}),
                   3400: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3401: 	    delete $courselogs{$crsid};
                   3402:         } else {
                   3403:             &logthis('Failed to flush log buffer for '.$crsid);
                   3404:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3405:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3406:                         " exceeded maximum size, deleting.</font>");
                   3407:                delete $courselogs{$crsid};
                   3408:             }
1.352     www      3409:         }
1.920     raeburn  3410:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3411:             'description' => $coursedescrbuf{$crsid},
                   3412:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3413:             'type'        => $coursetypebuf{$crsid},
                   3414:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3415:         };
1.191     harris41 3416:     }
1.352     www      3417: #
                   3418: # Write course id database (reverse lookup) to homeserver of courses 
                   3419: # Is used in pickcourse
                   3420: #
1.840     albertel 3421:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3422:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3423:                                     $courseidbuffer{$crs_home},
                   3424:                                     $crs_home,'timeonly');
1.352     www      3425:     }
                   3426: #
                   3427: # File accesses
                   3428: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3429: #
1.449     matthew  3430:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3431:         if ($entry =~ /___count$/) {
                   3432:             my ($dom,$name);
1.807     albertel 3433:             ($dom,$name,undef)=
1.811     albertel 3434: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3435:             if (! defined($dom) || $dom eq '' || 
                   3436:                 ! defined($name) || $name eq '') {
1.620     albertel 3437:                 my $cid = $env{'request.course.id'};
                   3438:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3439:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3440:             }
1.450     matthew  3441:             my $value = $accesshash{$entry};
                   3442:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3443:             my %temphash=($url => $value);
1.449     matthew  3444:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3445:             if ($result eq 'ok') {
                   3446:                 delete $accesshash{$entry};
                   3447:             }
                   3448:         } else {
1.811     albertel 3449:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3450:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3451:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3452:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3453:                 delete $accesshash{$entry};
                   3454:             }
1.185     www      3455:         }
1.191     harris41 3456:     }
1.352     www      3457: #
                   3458: # Roles
                   3459: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3460: #
1.800     albertel 3461:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3462:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3463: 	    split(/\:/,$entry);
                   3464:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3465:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3466:                 $rudom,$runame) eq 'ok') {
                   3467: 	    delete $userrolehash{$entry};
                   3468:         }
                   3469:     }
1.662     raeburn  3470: #
                   3471: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3472: #
                   3473:     my %domrolebuffer = ();
1.1000    raeburn  3474:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3475:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3476:         if ($domrolebuffer{$rudom}) {
                   3477:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3478:                       '='.&escape($domainrolehash{$entry});
                   3479:         } else {
                   3480:             $domrolebuffer{$rudom}.=&escape($entry).
                   3481:                       '='.&escape($domainrolehash{$entry});
                   3482:         }
                   3483:         delete $domainrolehash{$entry};
                   3484:     }
                   3485:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3486: 	my %servers = &get_servers($dom,'library');
                   3487: 	foreach my $tryserver (keys(%servers)) {
                   3488: 	    unless (&reply('domroleput:'.$dom.':'.
                   3489: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3490: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3491: 	    }
1.662     raeburn  3492:         }
                   3493:     }
1.186     www      3494:     $dumpcount++;
1.157     www      3495: }
                   3496: 
                   3497: sub courselog {
                   3498:     my $what=shift;
1.158     www      3499:     $what=time.':'.$what;
1.620     albertel 3500:     unless ($env{'request.course.id'}) { return ''; }
                   3501:     $coursedombuf{$env{'request.course.id'}}=
                   3502:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3503:     $coursenumbuf{$env{'request.course.id'}}=
                   3504:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3505:     $coursehombuf{$env{'request.course.id'}}=
                   3506:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3507:     $coursedescrbuf{$env{'request.course.id'}}=
                   3508:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3509:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3510:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3511:     $courseownerbuf{$env{'request.course.id'}}=
                   3512:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3513:     $coursetypebuf{$env{'request.course.id'}}=
                   3514:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3515:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3516: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3517:     } else {
1.620     albertel 3518: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3519:     }
1.620     albertel 3520:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3521: 	&flushcourselogs();
                   3522:     }
1.158     www      3523: }
                   3524: 
                   3525: sub courseacclog {
                   3526:     my $fnsymb=shift;
1.620     albertel 3527:     unless ($env{'request.course.id'}) { return ''; }
                   3528:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3529:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3530:         $what.=':POST';
1.583     matthew  3531:         # FIXME: Probably ought to escape things....
1.800     albertel 3532: 	foreach my $key (keys(%env)) {
                   3533:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3534:                 my $formitem = $1;
                   3535:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3536:                     $what.=':'.$formitem.'='.$env{$key};
                   3537:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3538:                     $what.=':'.$formitem.'='.$env{$key};
                   3539:                 }
1.158     www      3540:             }
1.191     harris41 3541:         }
1.583     matthew  3542:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3543:         # FIXME: We should not be depending on a form parameter that someone
                   3544:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3545:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3546:             $what.= ':POST';
                   3547:             # FIXME: Probably ought to escape things....
                   3548:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3549:                                  'crsdiscuss') {
1.620     albertel 3550:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3551:             }
                   3552:         }
1.158     www      3553:     }
                   3554:     &courselog($what);
1.149     www      3555: }
                   3556: 
1.185     www      3557: sub countacc {
                   3558:     my $url=&declutter(shift);
1.458     matthew  3559:     return if (! defined($url) || $url eq '');
1.620     albertel 3560:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3561: #
                   3562: # Mark that this url was used in this course
                   3563: #
1.620     albertel 3564:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3565: #
                   3566: # Increase the access count for this resource in this child process
                   3567: #
1.281     www      3568:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3569:     $accesshash{$key}++;
1.185     www      3570: }
1.349     www      3571: 
1.361     www      3572: sub linklog {
                   3573:     my ($from,$to)=@_;
                   3574:     $from=&declutter($from);
                   3575:     $to=&declutter($to);
                   3576:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3577:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3578: }
1.1160    www      3579: 
                   3580: sub statslog {
                   3581:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3582:     if ($users<2) { return; }
                   3583:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3584:             'course'       => $env{'request.course.id'},
                   3585:             'sections'     => '"all"',
                   3586:             'num_students' => $users,
                   3587:             'part'         => $part,
                   3588:             'symb'         => $symb,
                   3589:             'mean_tries'   => $av_attempts,
                   3590:             'deg_of_diff'  => $degdiff});
                   3591:     foreach my $key (keys(%dynstore)) {
                   3592:         $accesshash{$key}=$dynstore{$key};
                   3593:     }
                   3594: }
1.361     www      3595:   
1.349     www      3596: sub userrolelog {
                   3597:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3598:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3599:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3600:        $userrolehash
                   3601:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3602:                     =$tend.':'.$tstart;
1.662     raeburn  3603:     }
1.1169    droeschl 3604:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3605:        $userrolehash
                   3606:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3607:                     =$tend.':'.$tstart;
                   3608:     }
1.1169    droeschl 3609:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3610:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3611:        $domainrolehash
                   3612:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3613:                     = $tend.':'.$tstart;
                   3614:     }
1.351     www      3615: }
                   3616: 
1.957     raeburn  3617: sub courserolelog {
                   3618:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3619:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3620:         my $cdom = $1;
                   3621:         my $cnum = $2;
                   3622:         my $sec = $3;
                   3623:         my $namespace = 'rolelog';
                   3624:         my %storehash = (
                   3625:                            role    => $trole,
                   3626:                            start   => $tstart,
                   3627:                            end     => $tend,
                   3628:                            selfenroll => $selfenroll,
                   3629:                            context    => $context,
                   3630:                         );
                   3631:         if ($trole eq 'gr') {
                   3632:             $namespace = 'groupslog';
                   3633:             $storehash{'group'} = $sec;
                   3634:         } else {
                   3635:             $storehash{'section'} = $sec;
                   3636:         }
1.1188    raeburn  3637:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3638:                    $domain,$cnum,$cdom);
1.1184    raeburn  3639:         if (($trole ne 'st') || ($sec ne '')) {
                   3640:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3641:         }
                   3642:     }
                   3643:     return;
                   3644: }
                   3645: 
1.1184    raeburn  3646: sub domainrolelog {
                   3647:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3648:     if ($area =~ m{^/($match_domain)/$}) {
                   3649:         my $cdom = $1;
                   3650:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3651:         my $namespace = 'rolelog';
                   3652:         my %storehash = (
                   3653:                            role    => $trole,
                   3654:                            start   => $tstart,
                   3655:                            end     => $tend,
                   3656:                            context => $context,
                   3657:                         );
1.1188    raeburn  3658:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3659:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3660:     }
                   3661:     return;
                   3662: 
                   3663: }
                   3664: 
                   3665: sub coauthorrolelog {
                   3666:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3667:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3668:         my $audom = $1;
                   3669:         my $auname = $2;
                   3670:         my $namespace = 'rolelog';
                   3671:         my %storehash = (
                   3672:                            role    => $trole,
                   3673:                            start   => $tstart,
                   3674:                            end     => $tend,
                   3675:                            context => $context,
                   3676:                         );
1.1188    raeburn  3677:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3678:                    $domain,$auname,$audom);
1.1184    raeburn  3679:     }
                   3680:     return;
                   3681: }
                   3682: 
1.351     www      3683: sub get_course_adv_roles {
1.948     raeburn  3684:     my ($cid,$codes) = @_;
1.620     albertel 3685:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3686:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3687:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3688:     my %nothide=();
1.800     albertel 3689:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3690:         if ($user !~ /:/) {
                   3691: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3692:         } else {
                   3693:             $nothide{$user}=1;
                   3694:         }
1.470     www      3695:     }
1.351     www      3696:     my %returnhash=();
                   3697:     my %dumphash=
                   3698:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3699:     my $now=time;
1.997     raeburn  3700:     my %privileged;
1.1000    raeburn  3701:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3702: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3703:         if (($tstart) && ($tstart<0)) { next; }
                   3704:         if (($tend) && ($tend<$now)) { next; }
                   3705:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3706:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3707: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3708:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3709:             my %dompersonnel =
1.998     raeburn  3710:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3711:             $privileged{$domain} = {};
                   3712:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3713:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3714:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3715:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3716:                         $privileged{$udom}{$uname} = 1;
                   3717:                     }
                   3718:                 }
                   3719:             }
                   3720:         }
                   3721:         if ((exists($privileged{$domain}{$username})) && 
                   3722:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3723: 	if ($role eq 'cr') { next; }
1.948     raeburn  3724:         if ($codes) {
                   3725:             if ($section) { $role .= ':'.$section; }
                   3726:             if ($returnhash{$role}) {
                   3727:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3728:             } else {
                   3729:                 $returnhash{$role}=$username.':'.$domain;
                   3730:             }
1.351     www      3731:         } else {
1.988     raeburn  3732:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3733:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3734:             if ($returnhash{$key}) {
                   3735: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3736:             } else {
                   3737:                 $returnhash{$key}=$username.':'.$domain;
                   3738:             }
1.351     www      3739:         }
1.948     raeburn  3740:     }
1.400     www      3741:     return %returnhash;
                   3742: }
                   3743: 
                   3744: sub get_my_roles {
1.937     raeburn  3745:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3746:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3747:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3748:     my (%dumphash,%nothide);
1.1086    raeburn  3749:     if ($context eq 'userroles') {
1.1166    raeburn  3750:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3751:     } else {
                   3752:         %dumphash=
1.400     www      3753:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3754:         if ($hidepriv) {
                   3755:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3756:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3757:                 if ($user !~ /:/) {
                   3758:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3759:                 } else {
                   3760:                     $nothide{$user} = 1;
                   3761:                 }
                   3762:             }
                   3763:         }
1.858     raeburn  3764:     }
1.400     www      3765:     my %returnhash=();
                   3766:     my $now=time;
1.999     raeburn  3767:     my %privileged;
1.800     albertel 3768:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3769:         my ($role,$tend,$tstart);
                   3770:         if ($context eq 'userroles') {
1.1149    raeburn  3771:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3772: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3773:         } else {
                   3774:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3775:         }
1.400     www      3776:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3777:         my $status = 'active';
1.939     raeburn  3778:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3779:             $status = 'previous';
                   3780:         } 
                   3781:         if (($tstart) && ($now<$tstart)) {
                   3782:             $status = 'future';
                   3783:         }
                   3784:         if (ref($types) eq 'ARRAY') {
                   3785:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3786:                 next;
                   3787:             } 
                   3788:         } else {
                   3789:             if ($status ne 'active') {
                   3790:                 next;
                   3791:             }
                   3792:         }
1.867     raeburn  3793:         my ($rolecode,$username,$domain,$section,$area);
                   3794:         if ($context eq 'userroles') {
1.1186    raeburn  3795:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3796:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3797:         } else {
                   3798:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3799:         }
1.832     raeburn  3800:         if (ref($roledoms) eq 'ARRAY') {
                   3801:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3802:                 next;
                   3803:             }
                   3804:         }
                   3805:         if (ref($roles) eq 'ARRAY') {
                   3806:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3807:                 if ($role =~ /^cr\//) {
                   3808:                     if (!grep(/^cr$/,@{$roles})) {
                   3809:                         next;
                   3810:                     }
1.1104    raeburn  3811:                 } elsif ($role =~ /^gr\//) {
                   3812:                     if (!grep(/^gr$/,@{$roles})) {
                   3813:                         next;
                   3814:                     }
1.922     raeburn  3815:                 } else {
                   3816:                     next;
                   3817:                 }
1.832     raeburn  3818:             }
1.867     raeburn  3819:         }
1.937     raeburn  3820:         if ($hidepriv) {
1.999     raeburn  3821:             if ($context eq 'userroles') {
                   3822:                 if ((&privileged($username,$domain)) &&
                   3823:                     (!$nothide{$username.':'.$domain})) {
                   3824:                     next;
                   3825:                 }
                   3826:             } else {
                   3827:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3828:                     my %dompersonnel =
                   3829:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3830:                     $privileged{$domain} = {};
                   3831:                     if (keys(%dompersonnel)) {
                   3832:                         foreach my $server (keys(%dompersonnel)) {
                   3833:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3834:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3835:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3836:                                     $privileged{$udom}{$uname} = $trole;
                   3837:                                 }
                   3838:                             }
                   3839:                         }
                   3840:                     }
                   3841:                 }
                   3842:                 if (exists($privileged{$domain}{$username})) {
                   3843:                     if (!$nothide{$username.':'.$domain}) {
                   3844:                         next;
                   3845:                     }
                   3846:                 }
1.937     raeburn  3847:             }
                   3848:         }
1.933     raeburn  3849:         if ($withsec) {
                   3850:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3851:                 $tstart.':'.$tend;
                   3852:         } else {
                   3853:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3854:         }
1.832     raeburn  3855:     }
1.373     www      3856:     return %returnhash;
1.399     www      3857: }
                   3858: 
                   3859: # ----------------------------------------------------- Frontpage Announcements
                   3860: #
                   3861: #
                   3862: 
                   3863: sub postannounce {
                   3864:     my ($server,$text)=@_;
1.844     albertel 3865:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3866:     unless ($text=~/\w/) { $text=''; }
                   3867:     return &reply('setannounce:'.&escape($text),$server);
                   3868: }
                   3869: 
                   3870: sub getannounce {
1.448     albertel 3871: 
                   3872:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3873: 	my $announcement='';
1.800     albertel 3874: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3875: 	close($fh);
1.399     www      3876: 	if ($announcement=~/\w/) { 
                   3877: 	    return 
                   3878:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3879:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3880: 	} else {
                   3881: 	    return '';
                   3882: 	}
                   3883:     } else {
                   3884: 	return '';
                   3885:     }
1.351     www      3886: }
1.353     www      3887: 
                   3888: # ---------------------------------------------------------- Course ID routines
                   3889: # Deal with domain's nohist_courseid.db files
                   3890: #
                   3891: 
                   3892: sub courseidput {
1.921     raeburn  3893:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3894:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3895:     my $outcome;
                   3896:     if ($caller eq 'timeonly') {
                   3897:         my $cids = '';
                   3898:         foreach my $item (keys(%$storehash)) {
                   3899:             $cids.=&escape($item).'&';
                   3900:         }
                   3901:         $cids=~s/\&$//;
                   3902:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3903:                           $coursehome);       
                   3904:     } else {
                   3905:         my $items = '';
                   3906:         foreach my $item (keys(%$storehash)) {
                   3907:             $items.= &escape($item).'='.
                   3908:                      &freeze_escape($$storehash{$item}).'&';
                   3909:         }
                   3910:         $items=~s/\&$//;
                   3911:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3912:                           $coursehome);
1.918     raeburn  3913:     }
                   3914:     if ($outcome eq 'unknown_cmd') {
                   3915:         my $what;
                   3916:         foreach my $cid (keys(%$storehash)) {
                   3917:             $what .= &escape($cid).'=';
1.921     raeburn  3918:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3919:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3920:             }
                   3921:             $what =~ s/\:$/&/;
                   3922:         }
                   3923:         $what =~ s/\&$//;  
                   3924:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3925:     } else {
                   3926:         return $outcome;
                   3927:     }
1.353     www      3928: }
                   3929: 
                   3930: sub courseiddump {
1.921     raeburn  3931:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3932:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3933:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3934:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3935:     my $as_hash = 1;
                   3936:     my %returnhash;
                   3937:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3938:     my %libserv = &all_library();
                   3939:     foreach my $tryserver (keys(%libserv)) {
                   3940:         if ( (  $hostidflag == 1 
                   3941: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3942: 	     || (!defined($hostidflag)) ) {
                   3943: 
1.918     raeburn  3944: 	    if (($domfilter eq '') ||
                   3945: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 3946:                 my $rep;
                   3947:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   3948:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   3949:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   3950:                                 &escape($descfilter), &escape($instcodefilter), 
                   3951:                                 &escape($ownerfilter), &escape($coursefilter),
                   3952:                                 &escape($typefilter), &escape($regexp_ok), 
                   3953:                                 $as_hash, &escape($selfenrollonly), 
                   3954:                                 &escape($catfilter), $showhidden, $caller, 
                   3955:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   3956:                                 &escape($createdbefore), &escape($createdafter), 
                   3957:                                 &escape($creationcontext), $domcloner)));
                   3958:                 } else {
                   3959:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3960:                              $sincefilter.':'.&escape($descfilter).':'.
                   3961:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   3962:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   3963:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   3964:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   3965:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   3966:                              &escape($cc_clone).':'.$cloneonly.':'.
                   3967:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   3968:                              &escape($creationcontext).':'.$domcloner,
                   3969:                              $tryserver);
                   3970:                 }
                   3971:                      
1.918     raeburn  3972:                 my @pairs=split(/\&/,$rep);
                   3973:                 foreach my $item (@pairs) {
                   3974:                     my ($key,$value)=split(/\=/,$item,2);
                   3975:                     $key = &unescape($key);
                   3976:                     next if ($key =~ /^error: 2 /);
                   3977:                     my $result = &thaw_unescape($value);
                   3978:                     if (ref($result) eq 'HASH') {
                   3979:                         $returnhash{$key}=$result;
                   3980:                     } else {
1.921     raeburn  3981:                         my @responses = split(/:/,$value);
                   3982:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3983:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3984:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3985:                         }
1.1008    raeburn  3986:                     }
1.353     www      3987:                 }
                   3988:             }
                   3989:         }
                   3990:     }
                   3991:     return %returnhash;
                   3992: }
                   3993: 
1.1055    raeburn  3994: sub courselastaccess {
                   3995:     my ($cdom,$cnum,$hostidref) = @_;
                   3996:     my %returnhash;
                   3997:     if ($cdom && $cnum) {
                   3998:         my $chome = &homeserver($cnum,$cdom);
                   3999:         if ($chome ne 'no_host') {
                   4000:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4001:             &extract_lastaccess(\%returnhash,$rep);
                   4002:         }
                   4003:     } else {
                   4004:         if (!$cdom) { $cdom=''; }
                   4005:         my %libserv = &all_library();
                   4006:         foreach my $tryserver (keys(%libserv)) {
                   4007:             if (ref($hostidref) eq 'ARRAY') {
                   4008:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4009:             } 
                   4010:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4011:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4012:                 &extract_lastaccess(\%returnhash,$rep);
                   4013:             }
                   4014:         }
                   4015:     }
                   4016:     return %returnhash;
                   4017: }
                   4018: 
                   4019: sub extract_lastaccess {
                   4020:     my ($returnhash,$rep) = @_;
                   4021:     if (ref($returnhash) eq 'HASH') {
                   4022:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4023:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4024:                  $rep eq '') {
                   4025:             my @pairs=split(/\&/,$rep);
                   4026:             foreach my $item (@pairs) {
                   4027:                 my ($key,$value)=split(/\=/,$item,2);
                   4028:                 $key = &unescape($key);
                   4029:                 next if ($key =~ /^error: 2 /);
                   4030:                 $returnhash->{$key} = &thaw_unescape($value);
                   4031:             }
                   4032:         }
                   4033:     }
                   4034:     return;
                   4035: }
                   4036: 
1.658     raeburn  4037: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4038: 
                   4039: sub dcmailput {
1.685     raeburn  4040:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4041:     my $status = &Apache::lonnet::critical(
1.740     www      4042:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4043:        &escape($message),$server);
1.662     raeburn  4044:     return $status;
                   4045: }
                   4046: 
1.658     raeburn  4047: sub dcmaildump {
                   4048:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4049:     my %returnhash=();
1.846     albertel 4050: 
                   4051:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4052:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4053:                                                          &escape($enddate).':';
                   4054: 	my @esc_senders=map { &escape($_)} @$senders;
                   4055: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4056: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4057:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4058:             if (($key) && ($value)) {
                   4059:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4060:             }
                   4061:         }
                   4062:     }
                   4063:     return %returnhash;
                   4064: }
1.662     raeburn  4065: # ---------------------------------------------------------- Domain roles
                   4066: 
                   4067: sub get_domain_roles {
                   4068:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4069:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4070:         $startdate = '.';
                   4071:     }
1.1018    raeburn  4072:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4073:         $enddate = '.';
                   4074:     }
1.922     raeburn  4075:     my $rolelist;
                   4076:     if (ref($roles) eq 'ARRAY') {
                   4077:         $rolelist = join(':',@{$roles});
                   4078:     }
1.662     raeburn  4079:     my %personnel = ();
1.841     albertel 4080: 
                   4081:     my %servers = &get_servers($dom,'library');
                   4082:     foreach my $tryserver (keys(%servers)) {
                   4083: 	%{$personnel{$tryserver}}=();
                   4084: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4085: 					    &escape($startdate).':'.
                   4086: 					    &escape($enddate).':'.
                   4087: 					    &escape($rolelist), $tryserver))) {
                   4088: 	    my ($key,$value) = split(/\=/,$line,2);
                   4089: 	    if (($key) && ($value)) {
                   4090: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4091: 	    }
                   4092: 	}
1.662     raeburn  4093:     }
                   4094:     return %personnel;
                   4095: }
1.658     raeburn  4096: 
1.1057    www      4097: # ----------------------------------------------------------- Interval timing 
1.149     www      4098: 
1.1153    www      4099: {
                   4100: # Caches needed for speedup of navmaps
                   4101: # We don't want to cache this for very long at all (5 seconds at most)
                   4102: # 
                   4103: # The user for whom we cache
                   4104: my $cachedkey='';
                   4105: # The cached times for this user
                   4106: my %cachedtimes=();
                   4107: # When this was last done
                   4108: my $cachedtime=();
                   4109: 
                   4110: sub load_all_first_access {
1.1154    raeburn  4111:     my ($uname,$udom)=@_;
1.1156    www      4112:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4113:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4114:         return;
                   4115:     }
                   4116:     $cachedtime=time;
                   4117:     $cachedkey=$uname.':'.$udom;
                   4118:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4119: }
                   4120: 
1.504     albertel 4121: sub get_first_access {
1.1162    raeburn  4122:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4123:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4124:     if ($argsymb) { $symb=$argsymb; }
                   4125:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4126:     if ($argmap) { $map = $argmap; }
1.926     albertel 4127:     if ($type eq 'course') {
                   4128: 	$res='course';
                   4129:     } elsif ($type eq 'map') {
1.588     albertel 4130: 	$res=&symbread($map);
                   4131:     } else {
                   4132: 	$res=$symb;
                   4133:     }
1.1153    www      4134:     &load_all_first_access($uname,$udom);
                   4135:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4136: }
                   4137: 
                   4138: sub set_first_access {
1.1162    raeburn  4139:     my ($type,$interval)=@_;
1.790     albertel 4140:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4141:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4142:     if ($type eq 'course') {
                   4143: 	$res='course';
                   4144:     } elsif ($type eq 'map') {
1.588     albertel 4145: 	$res=&symbread($map);
                   4146:     } else {
                   4147: 	$res=$symb;
                   4148:     }
1.1153    www      4149:     $cachedkey='';
1.1162    raeburn  4150:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4151:     if (!$firstaccess) {
1.1162    raeburn  4152:         my $start = time;
                   4153: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4154:                           $udom,$uname);
                   4155:         if ($putres eq 'ok') {
                   4156:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4157:                  $udom,$uname); 
                   4158:             &appenv(
                   4159:                      {
                   4160:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4161:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4162:                      }
                   4163:                   );
                   4164:         }
                   4165:         return $putres;
1.505     albertel 4166:     }
                   4167:     return 'already_set';
1.504     albertel 4168: }
1.1153    www      4169: }
1.110     www      4170: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4171: 
                   4172: sub expirespread {
                   4173:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4174:     my $cid=$env{'request.course.id'}; 
1.110     www      4175:     if ($cid) {
                   4176:        my $now=time;
                   4177:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4178:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4179:                             $env{'course.'.$cid.'.num'}.
1.110     www      4180: 	        	    ':nohist_expirationdates:'.
                   4181:                             &escape($key).'='.$now,
1.620     albertel 4182:                             $env{'course.'.$cid.'.home'})
1.110     www      4183:     }
                   4184:     return 'ok';
1.14      www      4185: }
                   4186: 
1.109     www      4187: # ----------------------------------------------------- Devalidate Spreadsheets
                   4188: 
                   4189: sub devalidate {
1.325     www      4190:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4191:     my $cid=$env{'request.course.id'}; 
1.109     www      4192:     if ($cid) {
1.391     matthew  4193:         # delete the stored spreadsheets for
                   4194:         # - the student level sheet of this user in course's homespace
                   4195:         # - the assessment level sheet for this resource 
                   4196:         #   for this user in user's homespace
1.553     albertel 4197: 	# - current conditional state info
1.325     www      4198: 	my $key=$uname.':'.$udom.':';
1.109     www      4199:         my $status=
1.299     matthew  4200: 	    &del('nohist_calculatedsheets',
1.391     matthew  4201: 		 [$key.'studentcalc:'],
1.620     albertel 4202: 		 $env{'course.'.$cid.'.domain'},
                   4203: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4204: 		.' '.
                   4205: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4206: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4207:         unless ($status eq 'ok ok') {
                   4208:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4209:                     $uname.' at '.$udom.' for '.
1.109     www      4210: 		    $symb.': '.$status);
1.133     albertel 4211:         }
1.553     albertel 4212: 	&delenv('user.state.'.$cid);
1.109     www      4213:     }
                   4214: }
                   4215: 
1.265     albertel 4216: sub get_scalar {
                   4217:     my ($string,$end) = @_;
                   4218:     my $value;
                   4219:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4220: 	$value = $1;
                   4221:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4222: 	$value = $1;
                   4223:     }
                   4224:     return &unescape($value);
                   4225: }
                   4226: 
                   4227: sub array2str {
                   4228:   my (@array) = @_;
                   4229:   my $result=&arrayref2str(\@array);
                   4230:   $result=~s/^__ARRAY_REF__//;
                   4231:   $result=~s/__END_ARRAY_REF__$//;
                   4232:   return $result;
                   4233: }
                   4234: 
1.204     albertel 4235: sub arrayref2str {
                   4236:   my ($arrayref) = @_;
1.265     albertel 4237:   my $result='__ARRAY_REF__';
1.204     albertel 4238:   foreach my $elem (@$arrayref) {
1.265     albertel 4239:     if(ref($elem) eq 'ARRAY') {
                   4240:       $result.=&arrayref2str($elem).'&';
                   4241:     } elsif(ref($elem) eq 'HASH') {
                   4242:       $result.=&hashref2str($elem).'&';
                   4243:     } elsif(ref($elem)) {
                   4244:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4245:     } else {
                   4246:       $result.=&escape($elem).'&';
                   4247:     }
                   4248:   }
                   4249:   $result=~s/\&$//;
1.265     albertel 4250:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4251:   return $result;
                   4252: }
                   4253: 
1.168     albertel 4254: sub hash2str {
1.204     albertel 4255:   my (%hash) = @_;
                   4256:   my $result=&hashref2str(\%hash);
1.265     albertel 4257:   $result=~s/^__HASH_REF__//;
                   4258:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4259:   return $result;
                   4260: }
                   4261: 
                   4262: sub hashref2str {
                   4263:   my ($hashref)=@_;
1.265     albertel 4264:   my $result='__HASH_REF__';
1.800     albertel 4265:   foreach my $key (sort(keys(%$hashref))) {
                   4266:     if (ref($key) eq 'ARRAY') {
                   4267:       $result.=&arrayref2str($key).'=';
                   4268:     } elsif (ref($key) eq 'HASH') {
                   4269:       $result.=&hashref2str($key).'=';
                   4270:     } elsif (ref($key)) {
1.265     albertel 4271:       $result.='=';
1.800     albertel 4272:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4273:     } else {
1.1132    raeburn  4274: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4275:     }
                   4276: 
1.800     albertel 4277:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4278:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4279:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4280:       $result.=&hashref2str($hashref->{$key}).'&';
                   4281:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4282:        $result.='&';
1.800     albertel 4283:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4284:     } else {
1.800     albertel 4285:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4286:     }
                   4287:   }
1.168     albertel 4288:   $result=~s/\&$//;
1.265     albertel 4289:   $result .= '__END_HASH_REF__';
1.168     albertel 4290:   return $result;
                   4291: }
                   4292: 
                   4293: sub str2hash {
1.265     albertel 4294:     my ($string)=@_;
                   4295:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4296:     return %$hash;
                   4297: }
                   4298: 
                   4299: sub str2hashref {
1.168     albertel 4300:   my ($string) = @_;
1.265     albertel 4301: 
                   4302:   my %hash;
                   4303: 
                   4304:   if($string !~ /^__HASH_REF__/) {
                   4305:       if (! ($string eq '' || !defined($string))) {
                   4306: 	  $hash{'error'}='Not hash reference';
                   4307:       }
                   4308:       return (\%hash, $string);
                   4309:   }
                   4310: 
                   4311:   $string =~ s/^__HASH_REF__//;
                   4312: 
                   4313:   while($string !~ /^__END_HASH_REF__/) {
                   4314:       #key
                   4315:       my $key='';
                   4316:       if($string =~ /^__HASH_REF__/) {
                   4317:           ($key, $string)=&str2hashref($string);
                   4318:           if(defined($key->{'error'})) {
                   4319:               $hash{'error'}='Bad data';
                   4320:               return (\%hash, $string);
                   4321:           }
                   4322:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4323:           ($key, $string)=&str2arrayref($string);
                   4324:           if($key->[0] eq 'Array reference error') {
                   4325:               $hash{'error'}='Bad data';
                   4326:               return (\%hash, $string);
                   4327:           }
                   4328:       } else {
                   4329:           $string =~ s/^(.*?)=//;
1.267     albertel 4330: 	  $key=&unescape($1);
1.265     albertel 4331:       }
                   4332:       $string =~ s/^=//;
                   4333: 
                   4334:       #value
                   4335:       my $value='';
                   4336:       if($string =~ /^__HASH_REF__/) {
                   4337:           ($value, $string)=&str2hashref($string);
                   4338:           if(defined($value->{'error'})) {
                   4339:               $hash{'error'}='Bad data';
                   4340:               return (\%hash, $string);
                   4341:           }
                   4342:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4343:           ($value, $string)=&str2arrayref($string);
                   4344:           if($value->[0] eq 'Array reference error') {
                   4345:               $hash{'error'}='Bad data';
                   4346:               return (\%hash, $string);
                   4347:           }
                   4348:       } else {
                   4349: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4350:       }
                   4351:       $string =~ s/^&//;
                   4352: 
                   4353:       $hash{$key}=$value;
1.204     albertel 4354:   }
1.265     albertel 4355: 
                   4356:   $string =~ s/^__END_HASH_REF__//;
                   4357: 
                   4358:   return (\%hash, $string);
1.204     albertel 4359: }
                   4360: 
                   4361: sub str2array {
1.265     albertel 4362:     my ($string)=@_;
                   4363:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4364:     return @$array;
                   4365: }
                   4366: 
                   4367: sub str2arrayref {
1.204     albertel 4368:   my ($string) = @_;
1.265     albertel 4369:   my @array;
                   4370: 
                   4371:   if($string !~ /^__ARRAY_REF__/) {
                   4372:       if (! ($string eq '' || !defined($string))) {
                   4373: 	  $array[0]='Array reference error';
                   4374:       }
                   4375:       return (\@array, $string);
                   4376:   }
                   4377: 
                   4378:   $string =~ s/^__ARRAY_REF__//;
                   4379: 
                   4380:   while($string !~ /^__END_ARRAY_REF__/) {
                   4381:       my $value='';
                   4382:       if($string =~ /^__HASH_REF__/) {
                   4383:           ($value, $string)=&str2hashref($string);
                   4384:           if(defined($value->{'error'})) {
                   4385:               $array[0] ='Array reference error';
                   4386:               return (\@array, $string);
                   4387:           }
                   4388:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4389:           ($value, $string)=&str2arrayref($string);
                   4390:           if($value->[0] eq 'Array reference error') {
                   4391:               $array[0] ='Array reference error';
                   4392:               return (\@array, $string);
                   4393:           }
                   4394:       } else {
                   4395: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4396:       }
                   4397:       $string =~ s/^&//;
                   4398: 
                   4399:       push(@array, $value);
1.191     harris41 4400:   }
1.265     albertel 4401: 
                   4402:   $string =~ s/^__END_ARRAY_REF__//;
                   4403: 
                   4404:   return (\@array, $string);
1.168     albertel 4405: }
                   4406: 
1.167     albertel 4407: # -------------------------------------------------------------------Temp Store
                   4408: 
1.168     albertel 4409: sub tmpreset {
                   4410:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4411:   if (!$symb) {
                   4412:     $symb=&symbread();
1.620     albertel 4413:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4414:   }
                   4415:   $symb=escape($symb);
                   4416: 
1.620     albertel 4417:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4418:   $namespace=~s/\//\_/g;
                   4419:   $namespace=~s/\W//g;
                   4420: 
1.620     albertel 4421:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4422:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4423:   if ($domain eq 'public' && $stuname eq 'public') {
                   4424:       $stuname=$ENV{'REMOTE_ADDR'};
                   4425:   }
1.1117    foxr     4426:   my $path=LONCAPA::tempdir();
1.168     albertel 4427:   my %hash;
                   4428:   if (tie(%hash,'GDBM_File',
                   4429: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4430: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4431:     foreach my $key (keys(%hash)) {
1.180     albertel 4432:       if ($key=~ /:$symb/) {
1.168     albertel 4433: 	delete($hash{$key});
                   4434:       }
                   4435:     }
                   4436:   }
                   4437: }
                   4438: 
1.167     albertel 4439: sub tmpstore {
1.168     albertel 4440:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4441: 
                   4442:   if (!$symb) {
                   4443:     $symb=&symbread();
1.620     albertel 4444:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4445:   }
                   4446:   $symb=escape($symb);
                   4447: 
                   4448:   if (!$namespace) {
                   4449:     # I don't think we would ever want to store this for a course.
                   4450:     # it seems this will only be used if we don't have a course.
1.620     albertel 4451:     #$namespace=$env{'request.course.id'};
1.168     albertel 4452:     #if (!$namespace) {
1.620     albertel 4453:       $namespace=$env{'request.state'};
1.168     albertel 4454:     #}
                   4455:   }
                   4456:   $namespace=~s/\//\_/g;
                   4457:   $namespace=~s/\W//g;
1.620     albertel 4458:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4459:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4460:   if ($domain eq 'public' && $stuname eq 'public') {
                   4461:       $stuname=$ENV{'REMOTE_ADDR'};
                   4462:   }
1.168     albertel 4463:   my $now=time;
                   4464:   my %hash;
1.1117    foxr     4465:   my $path=LONCAPA::tempdir();
1.168     albertel 4466:   if (tie(%hash,'GDBM_File',
                   4467: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4468: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4469:     $hash{"version:$symb"}++;
                   4470:     my $version=$hash{"version:$symb"};
                   4471:     my $allkeys=''; 
                   4472:     foreach my $key (keys(%$storehash)) {
                   4473:       $allkeys.=$key.':';
1.591     albertel 4474:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4475:     }
                   4476:     $hash{"$version:$symb:timestamp"}=$now;
                   4477:     $allkeys.='timestamp';
                   4478:     $hash{"$version:keys:$symb"}=$allkeys;
                   4479:     if (untie(%hash)) {
                   4480:       return 'ok';
                   4481:     } else {
                   4482:       return "error:$!";
                   4483:     }
                   4484:   } else {
                   4485:     return "error:$!";
                   4486:   }
                   4487: }
1.167     albertel 4488: 
1.168     albertel 4489: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4490: 
1.168     albertel 4491: sub tmprestore {
                   4492:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4493: 
1.168     albertel 4494:   if (!$symb) {
                   4495:     $symb=&symbread();
1.620     albertel 4496:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4497:   }
                   4498:   $symb=escape($symb);
                   4499: 
1.620     albertel 4500:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4501: 
1.620     albertel 4502:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4503:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4504:   if ($domain eq 'public' && $stuname eq 'public') {
                   4505:       $stuname=$ENV{'REMOTE_ADDR'};
                   4506:   }
1.168     albertel 4507:   my %returnhash;
                   4508:   $namespace=~s/\//\_/g;
                   4509:   $namespace=~s/\W//g;
                   4510:   my %hash;
1.1117    foxr     4511:   my $path=LONCAPA::tempdir();
1.168     albertel 4512:   if (tie(%hash,'GDBM_File',
                   4513: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4514: 	  &GDBM_READER(),0640)) {
1.168     albertel 4515:     my $version=$hash{"version:$symb"};
                   4516:     $returnhash{'version'}=$version;
                   4517:     my $scope;
                   4518:     for ($scope=1;$scope<=$version;$scope++) {
                   4519:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4520:       my @keys=split(/:/,$vkeys);
                   4521:       my $key;
                   4522:       $returnhash{"$scope:keys"}=$vkeys;
                   4523:       foreach $key (@keys) {
1.591     albertel 4524: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4525: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4526:       }
                   4527:     }
1.168     albertel 4528:     if (!(untie(%hash))) {
                   4529:       return "error:$!";
                   4530:     }
                   4531:   } else {
                   4532:     return "error:$!";
                   4533:   }
                   4534:   return %returnhash;
1.167     albertel 4535: }
                   4536: 
1.9       www      4537: # ----------------------------------------------------------------------- Store
                   4538: 
                   4539: sub store {
1.124     www      4540:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4541:     my $home='';
                   4542: 
1.168     albertel 4543:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4544: 
1.213     www      4545:     $symb=&symbclean($symb);
1.122     albertel 4546:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4547: 
1.620     albertel 4548:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4549:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4550: 
                   4551:     &devalidate($symb,$stuname,$domain);
1.109     www      4552: 
                   4553:     $symb=escape($symb);
1.187     www      4554:     if (!$namespace) { 
1.620     albertel 4555:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4556:           return ''; 
                   4557:        } 
                   4558:     }
1.620     albertel 4559:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4560: 
                   4561:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4562:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4563: 
1.12      www      4564:     my $namevalue='';
1.800     albertel 4565:     foreach my $key (keys(%$storehash)) {
                   4566:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4567:     }
1.12      www      4568:     $namevalue=~s/\&$//;
1.187     www      4569:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4570:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4571: }
                   4572: 
1.47      www      4573: # -------------------------------------------------------------- Critical Store
                   4574: 
                   4575: sub cstore {
1.124     www      4576:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4577:     my $home='';
                   4578: 
1.168     albertel 4579:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4580: 
1.213     www      4581:     $symb=&symbclean($symb);
1.122     albertel 4582:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4583: 
1.620     albertel 4584:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4585:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4586: 
                   4587:     &devalidate($symb,$stuname,$domain);
1.109     www      4588: 
                   4589:     $symb=escape($symb);
1.187     www      4590:     if (!$namespace) { 
1.620     albertel 4591:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4592:           return ''; 
                   4593:        } 
                   4594:     }
1.620     albertel 4595:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4596: 
                   4597:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4598:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4599: 
1.47      www      4600:     my $namevalue='';
1.800     albertel 4601:     foreach my $key (keys(%$storehash)) {
                   4602:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4603:     }
1.47      www      4604:     $namevalue=~s/\&$//;
1.187     www      4605:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4606:     return critical
                   4607:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4608: }
                   4609: 
1.9       www      4610: # --------------------------------------------------------------------- Restore
                   4611: 
                   4612: sub restore {
1.124     www      4613:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4614:     my $home='';
                   4615: 
1.168     albertel 4616:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4617: 
1.122     albertel 4618:     if (!$symb) {
                   4619:       unless ($symb=escape(&symbread())) { return ''; }
                   4620:     } else {
1.213     www      4621:       $symb=&escape(&symbclean($symb));
1.122     albertel 4622:     }
1.188     www      4623:     if (!$namespace) { 
1.620     albertel 4624:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4625:           return ''; 
                   4626:        } 
                   4627:     }
1.620     albertel 4628:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4629:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4630:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4631:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4632: 
1.12      www      4633:     my %returnhash=();
1.800     albertel 4634:     foreach my $line (split(/\&/,$answer)) {
                   4635: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4636:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4637:     }
1.75      www      4638:     my $version;
                   4639:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4640:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4641:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4642:        }
1.75      www      4643:     }
1.13      www      4644:     return %returnhash;
1.34      www      4645: }
                   4646: 
                   4647: # ---------------------------------------------------------- Course Description
1.1118    foxr     4648: #
                   4649: #  
1.34      www      4650: 
                   4651: sub coursedescription {
1.731     albertel 4652:     my ($courseid,$args)=@_;
1.34      www      4653:     $courseid=~s/^\///;
1.49      www      4654:     $courseid=~s/\_/\//g;
1.34      www      4655:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4656:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4657:     my $normalid=$cdomain.'_'.$cnum;
                   4658:     # need to always cache even if we get errors otherwise we keep 
                   4659:     # trying and trying and trying to get the course description.
                   4660:     my %envhash=();
                   4661:     my %returnhash=();
1.731     albertel 4662:     
                   4663:     my $expiretime=600;
                   4664:     if ($env{'request.course.id'} eq $normalid) {
                   4665: 	$expiretime=120;
                   4666:     }
                   4667: 
                   4668:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4669:     if (!$args->{'freshen_cache'}
                   4670: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4671: 	foreach my $key (keys(%env)) {
                   4672: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4673: 	    my ($setting) = $1;
                   4674: 	    $returnhash{$setting} = $env{$key};
                   4675: 	}
                   4676: 	return %returnhash;
                   4677:     }
                   4678: 
1.1118    foxr     4679:     # get the data again
                   4680: 
1.731     albertel 4681:     if (!$args->{'one_time'}) {
                   4682: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4683:     }
1.811     albertel 4684: 
1.34      www      4685:     if ($chome ne 'no_host') {
1.302     albertel 4686:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4687:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4688: 	   my $username = $env{'user.name'}; # Defult username
                   4689: 	   if(defined $args->{'user'}) {
                   4690: 	       $username = $args->{'user'};
                   4691: 	   }
1.129     albertel 4692:            $returnhash{'home'}= $chome;
                   4693: 	   $returnhash{'domain'} = $cdomain;
                   4694: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4695:            if (!defined($returnhash{'type'})) {
                   4696:                $returnhash{'type'} = 'Course';
                   4697:            }
1.130     albertel 4698:            while (my ($name,$value) = each %returnhash) {
1.53      www      4699:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4700:            }
1.270     www      4701:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4702:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4703: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4704:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4705:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4706:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4707:        }
                   4708:     }
1.731     albertel 4709:     if (!$args->{'one_time'}) {
1.949     raeburn  4710: 	&appenv(\%envhash);
1.731     albertel 4711:     }
1.302     albertel 4712:     return %returnhash;
1.461     www      4713: }
                   4714: 
1.1080    raeburn  4715: sub update_released_required {
                   4716:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4717:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4718:         $cid = $env{'request.course.id'};
                   4719:         $cdom = $env{'course.'.$cid.'.domain'};
                   4720:         $cnum = $env{'course.'.$cid.'.num'};
                   4721:         $chome = $env{'course.'.$cid.'.home'};
                   4722:     }
                   4723:     if ($needsrelease) {
                   4724:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4725:         my $needsupdate;
                   4726:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4727:             $needsupdate = 1;
                   4728:         } else {
                   4729:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4730:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4731:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4732:                 $needsupdate = 1;
                   4733:             }
                   4734:         }
                   4735:         if ($needsupdate) {
                   4736:             my %needshash = (
                   4737:                              'internal.releaserequired' => $needsrelease,
                   4738:                             );
                   4739:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4740:             if ($putresult eq 'ok') {
                   4741:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4742:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4743:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4744:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4745:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4746:                 }
                   4747:             }
                   4748:         }
                   4749:     }
                   4750:     return;
                   4751: }
                   4752: 
1.461     www      4753: # -------------------------------------------------See if a user is privileged
                   4754: 
                   4755: sub privileged {
                   4756:     my ($username,$domain)=@_;
1.1170    droeschl 4757: 
                   4758:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4759:     my $now = time;
                   4760: 
                   4761:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4762:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4763:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4764:                 return 1 unless ($tend && $tend < $now) 
                   4765:                     or ($tstart && $tstart > $now);
                   4766:             }
1.461     www      4767: 	}
1.1170    droeschl 4768: 
1.461     www      4769:     return 0;
1.9       www      4770: }
1.1       albertel 4771: 
1.103     harris41 4772: # -------------------------------------------------------- Get user privileges
1.11      www      4773: 
                   4774: sub rolesinit {
1.1169    droeschl 4775:     my ($domain, $username) = @_;
                   4776:     my %userroles = ('user.login.time' => time);
                   4777:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4778: 
                   4779:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4780:     # also, blocking can be triggered by an activating timer
                   4781:     # it's saved in the user's %env.
                   4782:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4783:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4784:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4785:         %timerintchk, %timerintenv);
                   4786: 
1.1162    raeburn  4787:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4788:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4789:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4790:     }
1.1169    droeschl 4791: 
1.1162    raeburn  4792:     foreach my $key (keys(%timerinterval)) {
                   4793:         my ($cid,$rest) = split(/\0/,$key);
                   4794:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4795:     }
1.1169    droeschl 4796: 
1.11      www      4797:     my %allroles=();
1.1162    raeburn  4798:     my %allgroups=();
1.11      www      4799: 
1.1169    droeschl 4800:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4801:         my $role = $rolesdump{$area};
                   4802:         $area =~ s/\_\w\w$//;
                   4803: 
                   4804:         my ($trole, $tend, $tstart, $group_privs);
                   4805: 
                   4806:         if ($role =~ /^cr/) {
                   4807:         # Custom role, defined by a user 
                   4808:         # e.g., user.role.cr/msu/smith/mynewrole
                   4809:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4810:                 $trole = $1;
                   4811:                 ($tend, $tstart) = split('_', $2);
                   4812:             } else {
                   4813:                 $trole = $role;
                   4814:             }
                   4815:         } elsif ($role =~ m|^gr/|) {
                   4816:         # Role of member in a group, defined within a course/community
                   4817:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4818:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4819:             next if $tstart eq '-1';
                   4820:             ($trole, $group_privs) = split(/\//, $trole);
                   4821:             $group_privs = &unescape($group_privs);
                   4822:         } else {
                   4823:         # Just a normal role, defined in roles.tab
                   4824:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4825:         }
                   4826: 
                   4827:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4828:                  $username);
                   4829:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4830: 
                   4831:         # role expired or not available yet?
                   4832:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4833:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4834: 
                   4835:         next if $area eq '' or $trole eq '';
                   4836: 
                   4837:         my $spec = "$trole.$area";
                   4838:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4839: 
                   4840:         if ($trole =~ /^cr\//) {
                   4841:         # Custom role, defined by a user
                   4842:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4843:         } elsif ($trole eq 'gr') {
                   4844:         # Role of a member in a group, defined within a course/community
                   4845:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4846:             next;
                   4847:         } else {
                   4848:         # Normal role, defined in roles.tab
                   4849:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4850:         }
                   4851: 
                   4852:         my $cid = $tdomain.'_'.$trest;
                   4853:         unless ($firstaccchk{$cid}) {
                   4854:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4855:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4856:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4857:                         $coursetimerstarts{$cid}{$item}; 
                   4858:                 }
                   4859:             }
                   4860:             $firstaccchk{$cid} = 1;
                   4861:         }
                   4862:         unless ($timerintchk{$cid}) {
                   4863:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4864:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4865:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4866:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4867:                 }
1.12      www      4868:             }
1.1169    droeschl 4869:             $timerintchk{$cid} = 1;
1.191     harris41 4870:         }
1.11      www      4871:     }
1.1169    droeschl 4872: 
                   4873:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4874:         \%allroles, \%allgroups);
                   4875:     $env{'user.adv'} = $userroles{'user.adv'};
                   4876: 
1.1162    raeburn  4877:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4878: }
                   4879: 
1.567     raeburn  4880: sub set_arearole {
                   4881:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4882: # log the associated role with the area
                   4883:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4884:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4885: }
                   4886: 
                   4887: sub custom_roleprivs {
                   4888:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4889:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4890:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4891:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4892:         my ($rdummy,$roledef)=
                   4893:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4894:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4895:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4896:             if (defined($syspriv)) {
1.1043    raeburn  4897:                 if ($trest =~ /^$match_community$/) {
                   4898:                     $syspriv =~ s/bre\&S//; 
                   4899:                 }
1.567     raeburn  4900:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4901:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4902:             }
                   4903:             if ($tdomain ne '') {
                   4904:                 if (defined($dompriv)) {
                   4905:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4906:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4907:                 }
                   4908:                 if (($trest ne '') && (defined($coursepriv))) {
                   4909:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4910:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4911:                 }
                   4912:             }
                   4913:         }
                   4914:     }
                   4915: }
                   4916: 
1.678     raeburn  4917: sub group_roleprivs {
                   4918:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4919:     my $access = 1;
                   4920:     my $now = time;
                   4921:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4922:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4923:     if ($access) {
1.811     albertel 4924:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4925:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4926:     }
                   4927: }
1.567     raeburn  4928: 
                   4929: sub standard_roleprivs {
                   4930:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4931:     if (defined($pr{$trole.':s'})) {
                   4932:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4933:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4934:     }
                   4935:     if ($tdomain ne '') {
                   4936:         if (defined($pr{$trole.':d'})) {
                   4937:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4938:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4939:         }
                   4940:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4941:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4942:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4943:         }
                   4944:     }
                   4945: }
                   4946: 
                   4947: sub set_userprivs {
1.1064    raeburn  4948:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4949:     my $author=0;
                   4950:     my $adv=0;
1.678     raeburn  4951:     my %grouproles = ();
                   4952:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4953:         my @groupkeys; 
1.1000    raeburn  4954:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4955:             push(@groupkeys,$role);
                   4956:         }
                   4957:         if (ref($groups_roles) eq 'HASH') {
                   4958:             foreach my $key (keys(%{$groups_roles})) {
                   4959:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4960:                     push(@groupkeys,$key);
                   4961:                 }
                   4962:             }
                   4963:         }
                   4964:         if (@groupkeys > 0) {
                   4965:             foreach my $role (@groupkeys) {
                   4966:                 my ($trole,$area,$sec,$extendedarea);
                   4967:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4968:                     $trole = $1;
                   4969:                     $area = $2;
                   4970:                     $sec = $3;
                   4971:                     $extendedarea = $area.$sec;
                   4972:                     if (exists($$allgroups{$area})) {
                   4973:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4974:                             my $spec = $trole.'.'.$extendedarea;
                   4975:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4976:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4977:                         }
1.678     raeburn  4978:                     }
                   4979:                 }
                   4980:             }
                   4981:         }
                   4982:     }
1.800     albertel 4983:     foreach my $group (keys(%grouproles)) {
                   4984:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4985:     }
1.800     albertel 4986:     foreach my $role (keys(%{$allroles})) {
                   4987:         my %thesepriv;
1.941     raeburn  4988:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4989:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4990:             if ($item ne '') {
                   4991:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4992:                 if ($restrictions eq '') {
                   4993:                     $thesepriv{$privilege}='F';
                   4994:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4995:                     $thesepriv{$privilege}.=$restrictions;
                   4996:                 }
                   4997:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4998:             }
                   4999:         }
                   5000:         my $thesestr='';
1.1104    raeburn  5001:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5002: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5003: 	}
                   5004:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5005:     }
                   5006:     return ($author,$adv);
                   5007: }
                   5008: 
1.994     raeburn  5009: sub role_status {
1.1104    raeburn  5010:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5011:     my @pwhere = ();
                   5012:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5013:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5014:         unless (!defined($$role) || $$role eq '') {
                   5015:             $$where=join('.',@pwhere);
                   5016:             $$trolecode=$$role.'.'.$$where;
                   5017:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5018:             $$tstatus='is';
1.1104    raeburn  5019:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5020:                 $$tstatus='future';
1.1034    raeburn  5021:                 if ($$tstart<$now) {
                   5022:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5023:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5024:                             my (%allroles,%allgroups,$group_privs,
                   5025:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5026:                             my %userroles = (
                   5027:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5028:                             );
1.1064    raeburn  5029:                             @rolecodes = ('cm'); 
1.1002    raeburn  5030:                             my $spec=$$role.'.'.$$where;
                   5031:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5032:                             if ($$role =~ /^cr\//) {
                   5033:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5034:                                 push(@rolecodes,'cr');
1.1002    raeburn  5035:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5036:                                 push(@rolecodes,$$role);
1.1002    raeburn  5037:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5038:                                                     $env{'user.name'});
1.1064    raeburn  5039:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5040:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5041:                                 $group_privs = &unescape($group_privs);
                   5042:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5043:                                 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  5044:                                 &get_groups_roles($tdomain,$trest,
                   5045:                                                   \%course_roles,\@rolecodes,
                   5046:                                                   \%groups_roles);
1.1002    raeburn  5047:                             } else {
1.1064    raeburn  5048:                                 push(@rolecodes,$$role);
1.1002    raeburn  5049:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5050:                             }
1.1064    raeburn  5051:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5052:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5053:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5054:                         }
                   5055:                     }
1.1034    raeburn  5056:                     $$tstatus = 'is';
1.1002    raeburn  5057:                 }
1.994     raeburn  5058:             }
                   5059:             if ($$tend) {
1.1104    raeburn  5060:                 if ($$tend<$update) {
1.994     raeburn  5061:                     $$tstatus='expired';
                   5062:                 } elsif ($$tend<$now) {
                   5063:                     $$tstatus='will_not';
                   5064:                 }
                   5065:             }
                   5066:         }
                   5067:     }
                   5068: }
                   5069: 
1.1104    raeburn  5070: sub get_groups_roles {
                   5071:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5072:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5073:                   (ref($rolecodes) eq 'ARRAY') && 
                   5074:                   (ref($groups_roles) eq 'HASH')); 
                   5075:     if (keys(%{$cdom_courseroles}) > 0) {
                   5076:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5077:         if ($cdom ne '' && $cnum ne '') {
                   5078:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5079:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5080:                     my $crsrole = $1;
                   5081:                     my $crssec = $2;
                   5082:                     if ($crsrole =~ /^cr/) {
                   5083:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5084:                             push(@{$rolecodes},'cr');
                   5085:                         }
                   5086:                     } else {
                   5087:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5088:                             push(@{$rolecodes},$crsrole);
                   5089:                         }
                   5090:                     }
                   5091:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5092:                     if ($crssec ne '') {
                   5093:                         $rolekey .= "/$crssec";
                   5094:                     }
                   5095:                     $rolekey .= './';
                   5096:                     $groups_roles->{$rolekey} = $rolecodes;
                   5097:                 }
                   5098:             }
                   5099:         }
                   5100:     }
                   5101:     return;
                   5102: }
                   5103: 
                   5104: sub delete_env_groupprivs {
                   5105:     my ($where,$courseroles,$possroles) = @_;
                   5106:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5107:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5108:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5109:         %{$courseroles->{$udom}} =
                   5110:             &get_my_roles('','','userroles',['active'],
                   5111:                           $possroles,[$udom],1);
                   5112:     }
                   5113:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5114:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5115:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5116:             my $area = '/'.$cdom.'/'.$cnum;
                   5117:             my $privkey = "user.priv.$crsrole.$area";
                   5118:             if ($crssec ne '') {
                   5119:                 $privkey .= '/'.$crssec;
                   5120:             }
                   5121:             $privkey .= ".$area/$group";
                   5122:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5123:         }
                   5124:     }
                   5125:     return;
                   5126: }
                   5127: 
1.994     raeburn  5128: sub check_adhoc_privs {
1.1104    raeburn  5129:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5130:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5131:     my $setprivs;
1.994     raeburn  5132:     if ($env{$cckey}) {
                   5133:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5134:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5135:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5136:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5137:             $setprivs = 1;
1.994     raeburn  5138:         }
                   5139:     } else {
1.1088    raeburn  5140:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5141:         $setprivs = 1;
1.994     raeburn  5142:     }
1.1185    raeburn  5143:     return $setprivs;
1.994     raeburn  5144: }
                   5145: 
                   5146: sub set_adhoc_privileges {
                   5147: # role can be cc or ca
1.1088    raeburn  5148:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5149:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5150:     my $spec = $role.'.'.$area;
                   5151:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5152:                                   $env{'user.name'});
                   5153:     my %ccrole = ();
                   5154:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5155:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5156:     &appenv(\%userroles,[$role,'cm']);
                   5157:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5158:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5159:         &appenv( {'request.role'        => $spec,
                   5160:                   'request.role.domain' => $dcdom,
                   5161:                   'request.course.sec'  => ''
                   5162:                  }
                   5163:                );
                   5164:         my $tadv=0;
                   5165:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5166:         &appenv({'request.role.adv'    => $tadv});
                   5167:     }
1.994     raeburn  5168: }
                   5169: 
1.12      www      5170: # --------------------------------------------------------------- get interface
                   5171: 
                   5172: sub get {
1.131     albertel 5173:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5174:    my $items='';
1.800     albertel 5175:    foreach my $item (@$storearr) {
                   5176:        $items.=&escape($item).'&';
1.191     harris41 5177:    }
1.12      www      5178:    $items=~s/\&$//;
1.620     albertel 5179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5180:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5181:    my $uhome=&homeserver($uname,$udomain);
                   5182: 
1.133     albertel 5183:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5184:    my @pairs=split(/\&/,$rep);
1.273     albertel 5185:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5186:      return @pairs;
                   5187:    }
1.15      www      5188:    my %returnhash=();
1.42      www      5189:    my $i=0;
1.800     albertel 5190:    foreach my $item (@$storearr) {
                   5191:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5192:       $i++;
1.191     harris41 5193:    }
1.15      www      5194:    return %returnhash;
1.27      www      5195: }
                   5196: 
                   5197: # --------------------------------------------------------------- del interface
                   5198: 
                   5199: sub del {
1.133     albertel 5200:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5201:    my $items='';
1.800     albertel 5202:    foreach my $item (@$storearr) {
                   5203:        $items.=&escape($item).'&';
1.191     harris41 5204:    }
1.984     neumanie 5205: 
1.27      www      5206:    $items=~s/\&$//;
1.620     albertel 5207:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5208:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5209:    my $uhome=&homeserver($uname,$udomain);
                   5210:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5211: }
                   5212: 
                   5213: # -------------------------------------------------------------- dump interface
                   5214: 
1.1180    droeschl 5215: sub unserialize {
                   5216:     my ($rep, $escapedkeys) = @_;
                   5217: 
                   5218:     return {} if $rep =~ /^error/;
                   5219: 
                   5220:     my %returnhash=();
                   5221: 	foreach my $item (split /\&/, $rep) {
                   5222: 	    my ($key, $value) = split(/=/, $item, 2);
                   5223: 	    $key = unescape($key) unless $escapedkeys;
                   5224: 	    next if $key =~ /^error: 2 /;
                   5225: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5226: 	}
                   5227:     #return %returnhash;
                   5228:     return \%returnhash;
                   5229: }        
                   5230: 
                   5231: # see Lond::dump_with_regexp
                   5232: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5233: sub dump {
1.1180    droeschl 5234:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5235:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5236:     if (!$uname) { $uname=$env{'user.name'}; }
                   5237:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5238: 
1.1180    droeschl 5239:     my $reply;
                   5240:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5241:         # user is hosted on this machine
                   5242:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
                   5243:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5244:         return %{unserialize($reply, $escapedkeys)};
                   5245:     }
1.755     albertel 5246:     if ($regexp) {
                   5247: 	$regexp=&escape($regexp);
                   5248:     } else {
                   5249: 	$regexp='.';
                   5250:     }
1.1166    raeburn  5251:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5252:     my @pairs=split(/\&/,$rep);
                   5253:     my %returnhash=();
1.1098    foxr     5254:     if (!($rep =~ /^error/ )) {
                   5255: 	foreach my $item (@pairs) {
                   5256: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5257:         $key = unescape($key) unless $escapedkeys;
                   5258:         #$key = &unescape($key);
1.1098    foxr     5259: 	    next if ($key =~ /^error: 2 /);
                   5260: 	    $returnhash{$key}=&thaw_unescape($value);
                   5261: 	}
1.755     albertel 5262:     }
                   5263:     return %returnhash;
1.407     www      5264: }
                   5265: 
1.1098    foxr     5266: 
1.717     albertel 5267: # --------------------------------------------------------- dumpstore interface
                   5268: 
                   5269: sub dumpstore {
                   5270:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5271:    # same as dump but keys must be escaped. They may contain colon separated
                   5272:    # lists of values that may themself contain colons (e.g. symbs).
                   5273:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5274: }
                   5275: 
1.407     www      5276: # -------------------------------------------------------------- keys interface
                   5277: 
                   5278: sub getkeys {
                   5279:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5280:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5281:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5282:    my $uhome=&homeserver($uname,$udomain);
                   5283:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5284:    my @keyarray=();
1.800     albertel 5285:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5286:       next if ($key =~ /^error: 2 /);
1.800     albertel 5287:       push(@keyarray,&unescape($key));
1.407     www      5288:    }
                   5289:    return @keyarray;
1.318     matthew  5290: }
                   5291: 
1.319     matthew  5292: # --------------------------------------------------------------- currentdump
                   5293: sub currentdump {
1.328     matthew  5294:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5295:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5296:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5297:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5298:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5299:    my $rep;
                   5300: 
                   5301:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5302:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5303:                    $courseid)));
                   5304:    } else {
                   5305:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5306:    }
                   5307: 
1.318     matthew  5308:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5309:    #
1.318     matthew  5310:    my %returnhash=();
1.319     matthew  5311:    #
                   5312:    if ($rep eq "unknown_cmd") { 
                   5313:        # an old lond will not know currentdump
                   5314:        # Do a dump and make it look like a currentdump
1.822     albertel 5315:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5316:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5317:        my %hash = @tmp;
                   5318:        @tmp=();
1.424     matthew  5319:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5320:    } else {
                   5321:        my @pairs=split(/\&/,$rep);
1.800     albertel 5322:        foreach my $pair (@pairs) {
                   5323:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5324:            my ($symb,$param) = split(/:/,$key);
                   5325:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5326:                                                         &thaw_unescape($value);
1.319     matthew  5327:        }
1.191     harris41 5328:    }
1.12      www      5329:    return %returnhash;
1.424     matthew  5330: }
                   5331: 
                   5332: sub convert_dump_to_currentdump{
                   5333:     my %hash = %{shift()};
                   5334:     my %returnhash;
                   5335:     # Code ripped from lond, essentially.  The only difference
                   5336:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5337:     # we might run in to problems with parameter names =~ /^v\./
                   5338:     while (my ($key,$value) = each(%hash)) {
                   5339:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5340: 	$symb  = &unescape($symb);
                   5341: 	$param = &unescape($param);
1.424     matthew  5342:         next if ($v eq 'version' || $symb eq 'keys');
                   5343:         next if (exists($returnhash{$symb}) &&
                   5344:                  exists($returnhash{$symb}->{$param}) &&
                   5345:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5346:         $returnhash{$symb}->{$param}=$value;
                   5347:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5348:     }
                   5349:     #
                   5350:     # Remove all of the keys in the hashes which keep track of
                   5351:     # the version of the parameter.
                   5352:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5353:         # use a foreach because we are going to delete from the hash.
                   5354:         foreach my $key (keys(%$param_hash)) {
                   5355:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5356:         }
                   5357:     }
                   5358:     return \%returnhash;
1.12      www      5359: }
                   5360: 
1.627     albertel 5361: # ------------------------------------------------------ critical inc interface
                   5362: 
                   5363: sub cinc {
                   5364:     return &inc(@_,'critical');
                   5365: }
                   5366: 
1.449     matthew  5367: # --------------------------------------------------------------- inc interface
                   5368: 
                   5369: sub inc {
1.627     albertel 5370:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5371:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5372:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5373:     my $uhome=&homeserver($uname,$udomain);
                   5374:     my $items='';
                   5375:     if (! ref($store)) {
                   5376:         # got a single value, so use that instead
                   5377:         $items = &escape($store).'=&';
                   5378:     } elsif (ref($store) eq 'SCALAR') {
                   5379:         $items = &escape($$store).'=&';        
                   5380:     } elsif (ref($store) eq 'ARRAY') {
                   5381:         $items = join('=&',map {&escape($_);} @{$store});
                   5382:     } elsif (ref($store) eq 'HASH') {
                   5383:         while (my($key,$value) = each(%{$store})) {
                   5384:             $items.= &escape($key).'='.&escape($value).'&';
                   5385:         }
                   5386:     }
                   5387:     $items=~s/\&$//;
1.627     albertel 5388:     if ($critical) {
                   5389: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5390:     } else {
                   5391: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5392:     }
1.449     matthew  5393: }
                   5394: 
1.12      www      5395: # --------------------------------------------------------------- put interface
                   5396: 
                   5397: sub put {
1.134     albertel 5398:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5399:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5400:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5401:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5402:    my $items='';
1.800     albertel 5403:    foreach my $item (keys(%$storehash)) {
                   5404:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5405:    }
1.12      www      5406:    $items=~s/\&$//;
1.134     albertel 5407:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5408: }
                   5409: 
1.631     albertel 5410: # ------------------------------------------------------------ newput interface
                   5411: 
                   5412: sub newput {
                   5413:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5414:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5415:    if (!$uname) { $uname=$env{'user.name'}; }
                   5416:    my $uhome=&homeserver($uname,$udomain);
                   5417:    my $items='';
                   5418:    foreach my $key (keys(%$storehash)) {
                   5419:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5420:    }
                   5421:    $items=~s/\&$//;
                   5422:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5423: }
                   5424: 
                   5425: # ---------------------------------------------------------  putstore interface
                   5426: 
1.524     raeburn  5427: sub putstore {
1.715     albertel 5428:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5429:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5430:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5431:    my $uhome=&homeserver($uname,$udomain);
                   5432:    my $items='';
1.715     albertel 5433:    foreach my $key (keys(%$storehash)) {
                   5434:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5435:    }
1.715     albertel 5436:    $items=~s/\&$//;
1.716     albertel 5437:    my $esc_symb=&escape($symb);
                   5438:    my $esc_v=&escape($version);
1.715     albertel 5439:    my $reply =
1.716     albertel 5440:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5441: 	      $uhome);
                   5442:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5443:        # gfall back to way things use to be done
1.715     albertel 5444:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5445: 			    $uname);
1.524     raeburn  5446:    }
1.715     albertel 5447:    return $reply;
                   5448: }
                   5449: 
                   5450: sub old_putstore {
1.716     albertel 5451:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5452:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5453:     if (!$uname) { $uname=$env{'user.name'}; }
                   5454:     my $uhome=&homeserver($uname,$udomain);
                   5455:     my %newstorehash;
1.800     albertel 5456:     foreach my $item (keys(%$storehash)) {
                   5457: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5458: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5459:     }
                   5460:     my $items='';
                   5461:     my %allitems = ();
1.800     albertel 5462:     foreach my $item (keys(%newstorehash)) {
                   5463: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5464: 	    my $key = $1.':keys:'.$2;
                   5465: 	    $allitems{$key} .= $3.':';
                   5466: 	}
1.800     albertel 5467: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5468:     }
1.800     albertel 5469:     foreach my $item (keys(%allitems)) {
                   5470: 	$allitems{$item} =~ s/\:$//;
                   5471: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5472:     }
                   5473:     $items=~s/\&$//;
                   5474:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5475: }
                   5476: 
1.47      www      5477: # ------------------------------------------------------ critical put interface
                   5478: 
                   5479: sub cput {
1.134     albertel 5480:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5481:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5482:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5483:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5484:    my $items='';
1.800     albertel 5485:    foreach my $item (keys(%$storehash)) {
                   5486:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5487:    }
1.47      www      5488:    $items=~s/\&$//;
1.134     albertel 5489:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5490: }
                   5491: 
                   5492: # -------------------------------------------------------------- eget interface
                   5493: 
                   5494: sub eget {
1.133     albertel 5495:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5496:    my $items='';
1.800     albertel 5497:    foreach my $item (@$storearr) {
                   5498:        $items.=&escape($item).'&';
1.191     harris41 5499:    }
1.12      www      5500:    $items=~s/\&$//;
1.620     albertel 5501:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5502:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5503:    my $uhome=&homeserver($uname,$udomain);
                   5504:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5505:    my @pairs=split(/\&/,$rep);
                   5506:    my %returnhash=();
1.42      www      5507:    my $i=0;
1.800     albertel 5508:    foreach my $item (@$storearr) {
                   5509:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5510:       $i++;
1.191     harris41 5511:    }
1.12      www      5512:    return %returnhash;
                   5513: }
                   5514: 
1.667     albertel 5515: # ------------------------------------------------------------ tmpput interface
                   5516: sub tmpput {
1.802     raeburn  5517:     my ($storehash,$server,$context)=@_;
1.667     albertel 5518:     my $items='';
1.800     albertel 5519:     foreach my $item (keys(%$storehash)) {
                   5520: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5521:     }
                   5522:     $items=~s/\&$//;
1.802     raeburn  5523:     if (defined($context)) {
                   5524:         $items .= ':'.&escape($context);
                   5525:     }
1.667     albertel 5526:     return &reply("tmpput:$items",$server);
                   5527: }
                   5528: 
                   5529: # ------------------------------------------------------------ tmpget interface
                   5530: sub tmpget {
1.688     albertel 5531:     my ($token,$server)=@_;
                   5532:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5533:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5534:     my %returnhash;
                   5535:     foreach my $item (split(/\&/,$rep)) {
                   5536: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5537:         next if ($key =~ /^error: 2 /);
1.667     albertel 5538: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5539:     }
                   5540:     return %returnhash;
                   5541: }
                   5542: 
1.1113    raeburn  5543: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5544: sub tmpdel {
                   5545:     my ($token,$server)=@_;
                   5546:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5547:     return &reply("tmpdel:$token",$server);
                   5548: }
                   5549: 
1.765     albertel 5550: # -------------------------------------------------- portfolio access checking
                   5551: 
                   5552: sub portfolio_access {
1.766     albertel 5553:     my ($requrl) = @_;
1.765     albertel 5554:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5555:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5556:     if ($result) {
                   5557:         my %setters;
                   5558:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5559:             my ($startblock,$endblock) =
                   5560:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5561:             if ($startblock && $endblock) {
                   5562:                 return 'B';
                   5563:             }
                   5564:         } else {
                   5565:             my ($startblock,$endblock) =
                   5566:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5567:             if ($startblock && $endblock) {
                   5568:                 return 'B';
                   5569:             }
                   5570:         }
                   5571:     }
1.765     albertel 5572:     if ($result eq 'ok') {
1.766     albertel 5573:        return 'F';
1.765     albertel 5574:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5575:        return 'A';
1.765     albertel 5576:     }
1.766     albertel 5577:     return '';
1.765     albertel 5578: }
                   5579: 
                   5580: sub get_portfolio_access {
1.767     albertel 5581:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5582: 
                   5583:     if (!ref($access_hash)) {
                   5584: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5585: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5586: 						   $file_name);
                   5587: 	$access_hash = $access_controls{$file_name};
                   5588:     }
                   5589: 
1.765     albertel 5590:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5591:     my $now = time;
                   5592:     if (ref($access_hash) eq 'HASH') {
                   5593:         foreach my $key (keys(%{$access_hash})) {
                   5594:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5595:             if ($start > $now) {
                   5596:                 next;
                   5597:             }
                   5598:             if ($end && $end<$now) {
                   5599:                 next;
                   5600:             }
                   5601:             if ($scope eq 'public') {
                   5602:                 $public = $key;
                   5603:                 last;
                   5604:             } elsif ($scope eq 'guest') {
                   5605:                 $guest = $key;
                   5606:             } elsif ($scope eq 'domains') {
                   5607:                 push(@domains,$key);
                   5608:             } elsif ($scope eq 'users') {
                   5609:                 push(@users,$key);
                   5610:             } elsif ($scope eq 'course') {
                   5611:                 push(@courses,$key);
                   5612:             } elsif ($scope eq 'group') {
                   5613:                 push(@groups,$key);
                   5614:             }
                   5615:         }
                   5616:         if ($public) {
                   5617:             return 'ok';
                   5618:         }
                   5619:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5620:             if ($guest) {
                   5621:                 return $guest;
                   5622:             }
                   5623:         } else {
                   5624:             if (@domains > 0) {
                   5625:                 foreach my $domkey (@domains) {
                   5626:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5627:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5628:                             return 'ok';
                   5629:                         }
                   5630:                     }
                   5631:                 }
                   5632:             }
                   5633:             if (@users > 0) {
                   5634:                 foreach my $userkey (@users) {
1.865     raeburn  5635:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5636:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5637:                             if (ref($item) eq 'HASH') {
                   5638:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5639:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5640:                                     return 'ok';
                   5641:                                 }
                   5642:                             }
                   5643:                         }
                   5644:                     } 
1.765     albertel 5645:                 }
                   5646:             }
                   5647:             my %roleshash;
                   5648:             my @courses_and_groups = @courses;
                   5649:             push(@courses_and_groups,@groups); 
                   5650:             if (@courses_and_groups > 0) {
                   5651:                 my (%allgroups,%allroles); 
                   5652:                 my ($start,$end,$role,$sec,$group);
                   5653:                 foreach my $envkey (%env) {
1.1060    raeburn  5654:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5655:                         my $cid = $2.'_'.$3; 
                   5656:                         if ($1 eq 'gr') {
                   5657:                             $group = $4;
                   5658:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5659:                         } else {
                   5660:                             if ($4 eq '') {
                   5661:                                 $sec = 'none';
                   5662:                             } else {
                   5663:                                 $sec = $4;
                   5664:                             }
                   5665:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5666:                         }
1.811     albertel 5667:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5668:                         my $cid = $2.'_'.$3;
                   5669:                         if ($4 eq '') {
                   5670:                             $sec = 'none';
                   5671:                         } else {
                   5672:                             $sec = $4;
                   5673:                         }
                   5674:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5675:                     }
                   5676:                 }
                   5677:                 if (keys(%allroles) == 0) {
                   5678:                     return;
                   5679:                 }
                   5680:                 foreach my $key (@courses_and_groups) {
                   5681:                     my %content = %{$$access_hash{$key}};
                   5682:                     my $cnum = $content{'number'};
                   5683:                     my $cdom = $content{'domain'};
                   5684:                     my $cid = $cdom.'_'.$cnum;
                   5685:                     if (!exists($allroles{$cid})) {
                   5686:                         next;
                   5687:                     }    
                   5688:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5689:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5690:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5691:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5692:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5693:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5694:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5695:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5696:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5697:                                         if (grep/^all$/,@sections) {
                   5698:                                             return 'ok';
                   5699:                                         } else {
                   5700:                                             if (grep/^$sec$/,@sections) {
                   5701:                                                 return 'ok';
                   5702:                                             }
                   5703:                                         }
                   5704:                                     }
                   5705:                                 }
                   5706:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5707:                                     if (grep/^none$/,@groups) {
                   5708:                                         return 'ok';
                   5709:                                     }
                   5710:                                 } else {
                   5711:                                     if (grep/^all$/,@groups) {
                   5712:                                         return 'ok';
                   5713:                                     } 
                   5714:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5715:                                         if (grep/^$group$/,@groups) {
                   5716:                                             return 'ok';
                   5717:                                         }
                   5718:                                     }
                   5719:                                 } 
                   5720:                             }
                   5721:                         }
                   5722:                     }
                   5723:                 }
                   5724:             }
                   5725:             if ($guest) {
                   5726:                 return $guest;
                   5727:             }
                   5728:         }
                   5729:     }
                   5730:     return;
                   5731: }
                   5732: 
                   5733: sub course_group_datechecker {
                   5734:     my ($dates,$now,$status) = @_;
                   5735:     my ($start,$end) = split(/\./,$dates);
                   5736:     if (!$start && !$end) {
                   5737:         return 'ok';
                   5738:     }
                   5739:     if (grep/^active$/,@{$status}) {
                   5740:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5741:             return 'ok';
                   5742:         }
                   5743:     }
                   5744:     if (grep/^previous$/,@{$status}) {
                   5745:         if ($end > $now ) {
                   5746:             return 'ok';
                   5747:         }
                   5748:     }
                   5749:     if (grep/^future$/,@{$status}) {
                   5750:         if ($start > $now) {
                   5751:             return 'ok';
                   5752:         }
                   5753:     }
                   5754:     return; 
                   5755: }
                   5756: 
                   5757: sub parse_portfolio_url {
                   5758:     my ($url) = @_;
                   5759: 
                   5760:     my ($type,$udom,$unum,$group,$file_name);
                   5761:     
1.823     albertel 5762:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5763: 	$type = 1;
                   5764:         $udom = $1;
                   5765:         $unum = $2;
                   5766:         $file_name = $3;
1.823     albertel 5767:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5768: 	$type = 2;
                   5769:         $udom = $1;
                   5770:         $unum = $2;
                   5771:         $group = $3;
                   5772:         $file_name = $3.'/'.$4;
                   5773:     }
                   5774:     if (wantarray) {
                   5775: 	return ($type,$udom,$unum,$file_name,$group);
                   5776:     }
                   5777:     return $type;
                   5778: }
                   5779: 
                   5780: sub is_portfolio_url {
                   5781:     my ($url) = @_;
                   5782:     return scalar(&parse_portfolio_url($url));
                   5783: }
                   5784: 
1.798     raeburn  5785: sub is_portfolio_file {
                   5786:     my ($file) = @_;
1.820     raeburn  5787:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5788:         return 1;
                   5789:     }
                   5790:     return;
                   5791: }
                   5792: 
1.976     raeburn  5793: sub usertools_access {
1.1084    raeburn  5794:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5795:     my ($access,%tools);
                   5796:     if ($context eq '') {
                   5797:         $context = 'tools';
                   5798:     }
                   5799:     if ($context eq 'requestcourses') {
                   5800:         %tools = (
                   5801:                       official   => 1,
                   5802:                       unofficial => 1,
1.1006    raeburn  5803:                       community  => 1,
1.985     raeburn  5804:                  );
1.1183    raeburn  5805:     } elsif ($context eq 'requestauthor') {
                   5806:         %tools = (
                   5807:                       requestauthor => 1,
                   5808:                  );
1.985     raeburn  5809:     } else {
                   5810:         %tools = (
                   5811:                       aboutme   => 1,
                   5812:                       blog      => 1,
1.1177    raeburn  5813:                       webdav    => 1,
1.985     raeburn  5814:                       portfolio => 1,
                   5815:                  );
                   5816:     }
1.976     raeburn  5817:     return if (!defined($tools{$tool}));
                   5818: 
                   5819:     if ((!defined($udom)) || (!defined($uname))) {
                   5820:         $udom = $env{'user.domain'};
                   5821:         $uname = $env{'user.name'};
                   5822:     }
                   5823: 
1.978     raeburn  5824:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5825:         if ($action ne 'reload') {
1.985     raeburn  5826:             if ($context eq 'requestcourses') {
                   5827:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  5828:             } elsif ($context eq 'requestauthor') {
                   5829:                 return $env{'environment.canrequest.author'};
1.985     raeburn  5830:             } else {
                   5831:                 return $env{'environment.availabletools.'.$tool};
                   5832:             }
                   5833:         }
1.976     raeburn  5834:     }
                   5835: 
1.1183    raeburn  5836:     my ($toolstatus,$inststatus,$envkey);
                   5837:     if ($context eq 'requestauthor') {
                   5838:         $envkey = $context; 
                   5839:     } else {
                   5840:         $envkey = $context.'.'.$tool;
                   5841:     }
1.976     raeburn  5842: 
1.985     raeburn  5843:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5844:          ($action ne 'reload')) {
1.1183    raeburn  5845:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  5846:         $inststatus = $env{'environment.inststatus'};
                   5847:     } else {
1.1084    raeburn  5848:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  5849:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  5850:             $inststatus = $userenvref->{'inststatus'};
                   5851:         } else {
1.1183    raeburn  5852:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   5853:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  5854:             $inststatus = $userenv{'inststatus'};
                   5855:         }
1.976     raeburn  5856:     }
                   5857: 
                   5858:     if ($toolstatus ne '') {
                   5859:         if ($toolstatus) {
                   5860:             $access = 1;
                   5861:         } else {
                   5862:             $access = 0;
                   5863:         }
                   5864:         return $access;
                   5865:     }
                   5866: 
1.1084    raeburn  5867:     my ($is_adv,%domdef);
                   5868:     if (ref($is_advref) eq 'HASH') {
                   5869:         $is_adv = $is_advref->{'is_adv'};
                   5870:     } else {
                   5871:         $is_adv = &is_advanced_user($udom,$uname);
                   5872:     }
                   5873:     if (ref($domdefref) eq 'HASH') {
                   5874:         %domdef = %{$domdefref};
                   5875:     } else {
                   5876:         %domdef = &get_domain_defaults($udom);
                   5877:     }
1.976     raeburn  5878:     if (ref($domdef{$tool}) eq 'HASH') {
                   5879:         if ($is_adv) {
                   5880:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5881:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5882:                     $access = 1;
                   5883:                 } else {
                   5884:                     $access = 0;
                   5885:                 }
                   5886:                 return $access;
                   5887:             }
                   5888:         }
                   5889:         if ($inststatus ne '') {
                   5890:             my ($hasaccess,$hasnoaccess);
                   5891:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5892:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5893:                     if ($domdef{$tool}{$affiliation}) {
                   5894:                         $hasaccess = 1;
                   5895:                     } else {
                   5896:                         $hasnoaccess = 1;
                   5897:                     }
                   5898:                 }
                   5899:             }
                   5900:             if ($hasaccess || $hasnoaccess) {
                   5901:                 if ($hasaccess) {
                   5902:                     $access = 1;
                   5903:                 } elsif ($hasnoaccess) {
                   5904:                     $access = 0; 
                   5905:                 }
                   5906:                 return $access;
                   5907:             }
                   5908:         } else {
                   5909:             if ($domdef{$tool}{'default'} ne '') {
                   5910:                 if ($domdef{$tool}{'default'}) {
                   5911:                     $access = 1;
                   5912:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5913:                     $access = 0;
                   5914:                 }
                   5915:                 return $access;
                   5916:             }
                   5917:         }
                   5918:     } else {
1.1177    raeburn  5919:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  5920:             $access = 1;
                   5921:         } else {
                   5922:             $access = 0;
                   5923:         }
1.976     raeburn  5924:         return $access;
                   5925:     }
                   5926: }
                   5927: 
1.1050    raeburn  5928: sub is_course_owner {
                   5929:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5930:     if (($udom eq '') || ($uname eq '')) {
                   5931:         $udom = $env{'user.domain'};
                   5932:         $uname = $env{'user.name'};
                   5933:     }
                   5934:     unless (($udom eq '') || ($uname eq '')) {
                   5935:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5936:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5937:                 return 1;
                   5938:             } else {
                   5939:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5940:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5941:                     return 1;
                   5942:                 }
                   5943:             }
                   5944:         }
                   5945:     }
                   5946:     return;
                   5947: }
                   5948: 
1.976     raeburn  5949: sub is_advanced_user {
                   5950:     my ($udom,$uname) = @_;
1.1085    raeburn  5951:     if ($udom ne '' && $uname ne '') {
                   5952:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5953:             if (wantarray) {
                   5954:                 return ($env{'user.adv'},$env{'user.author'});
                   5955:             } else {
                   5956:                 return $env{'user.adv'};
                   5957:             }
1.1085    raeburn  5958:         }
                   5959:     }
1.976     raeburn  5960:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5961:     my %allroles;
1.1128    raeburn  5962:     my ($is_adv,$is_author);
1.976     raeburn  5963:     foreach my $role (keys(%roleshash)) {
                   5964:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5965:         my $area = '/'.$tdomain.'/'.$trest;
                   5966:         if ($sec ne '') {
                   5967:             $area .= '/'.$sec;
                   5968:         }
                   5969:         if (($area ne '') && ($trole ne '')) {
                   5970:             my $spec=$trole.'.'.$area;
                   5971:             if ($trole =~ /^cr\//) {
                   5972:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5973:             } elsif ($trole ne 'gr') {
                   5974:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5975:             }
1.1128    raeburn  5976:             if ($trole eq 'au') {
                   5977:                 $is_author = 1;
                   5978:             }
1.976     raeburn  5979:         }
                   5980:     }
                   5981:     foreach my $role (keys(%allroles)) {
                   5982:         last if ($is_adv);
                   5983:         foreach my $item (split(/:/,$allroles{$role})) {
                   5984:             if ($item ne '') {
                   5985:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5986:                 if ($privilege eq 'adv') {
                   5987:                     $is_adv = 1;
                   5988:                     last;
                   5989:                 }
                   5990:             }
                   5991:         }
                   5992:     }
1.1128    raeburn  5993:     if (wantarray) {
                   5994:         return ($is_adv,$is_author);
                   5995:     }
1.976     raeburn  5996:     return $is_adv;
                   5997: }
1.798     raeburn  5998: 
1.1035    raeburn  5999: sub check_can_request {
1.1036    raeburn  6000:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6001:     my $canreq = 0;
                   6002:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6003:     my @options = ('approval','validate','autolimit');
                   6004:     my $optregex = join('|',@options);
                   6005:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6006:         foreach my $type (@{$types}) {
                   6007:             if (&usertools_access($env{'user.name'},
                   6008:                                   $env{'user.domain'},
                   6009:                                   $type,undef,'requestcourses')) {
                   6010:                 $canreq ++;
1.1036    raeburn  6011:                 if (ref($request_domains) eq 'HASH') {
                   6012:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6013:                 }
1.1035    raeburn  6014:                 if ($dom eq $env{'user.domain'}) {
                   6015:                     $can_request->{$type} = 1;
                   6016:                 }
                   6017:             }
                   6018:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6019:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6020:                 if (@curr > 0) {
1.1036    raeburn  6021:                     foreach my $item (@curr) {
                   6022:                         if (ref($request_domains) eq 'HASH') {
                   6023:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6024:                             if ($otherdom ne '') {
                   6025:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6026:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6027:                                         push(@{$request_domains->{$type}},$otherdom);
                   6028:                                     }
                   6029:                                 } else {
                   6030:                                     push(@{$request_domains->{$type}},$otherdom);
                   6031:                                 }
                   6032:                             }
                   6033:                         }
                   6034:                     }
                   6035:                     unless($dom eq $env{'user.domain'}) {
                   6036:                         $canreq ++;
1.1035    raeburn  6037:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6038:                             $can_request->{$type} = 1;
                   6039:                         }
                   6040:                     }
                   6041:                 }
                   6042:             }
                   6043:         }
                   6044:     }
                   6045:     return $canreq;
                   6046: }
                   6047: 
1.341     www      6048: # ---------------------------------------------- Custom access rule evaluation
                   6049: 
                   6050: sub customaccess {
                   6051:     my ($priv,$uri)=@_;
1.807     albertel 6052:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6053:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6054:     $udom = &LONCAPA::clean_domain($udom);
                   6055:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6056:     my $access=0;
1.800     albertel 6057:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6058: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6059: 	if ($type eq 'user') {
                   6060: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6061: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6062: 		if ($tdom) {
                   6063: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6064: 		}
1.896     albertel 6065: 		if ($tuname) {
                   6066: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6067: 		}
                   6068: 		$access=($effect eq 'allow');
                   6069: 		last;
                   6070: 	    }
                   6071: 	} else {
                   6072: 	    if ($role) {
                   6073: 		if ($role ne $urole) { next; }
                   6074: 	    }
                   6075: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6076: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6077: 		if ($tdom) {
                   6078: 		    if ($tdom ne $udom) { next; }
                   6079: 		}
                   6080: 		if ($tcrs) {
                   6081: 		    if ($tcrs ne $ucrs) { next; }
                   6082: 		}
                   6083: 		if ($tsec) {
                   6084: 		    if ($tsec ne $usec) { next; }
                   6085: 		}
                   6086: 		$access=($effect eq 'allow');
                   6087: 		last;
                   6088: 	    }
                   6089: 	    if ($realm eq '' && $role eq '') {
                   6090: 		$access=($effect eq 'allow');
                   6091: 	    }
1.402     bowersj2 6092: 	}
1.341     www      6093:     }
                   6094:     return $access;
                   6095: }
                   6096: 
1.103     harris41 6097: # ------------------------------------------------- Check for a user privilege
1.12      www      6098: 
                   6099: sub allowed {
1.810     raeburn  6100:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6101:     my $ver_orguri=$uri;
1.439     www      6102:     $uri=&deversion($uri);
1.152     www      6103:     my $orguri=$uri;
1.52      www      6104:     $uri=&declutter($uri);
1.809     raeburn  6105: 
1.810     raeburn  6106:     if ($priv eq 'evb') {
                   6107: # Evade communication block restrictions for specified role in a course
                   6108:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6109:             return $1;
                   6110:         } else {
                   6111:             return;
                   6112:         }
                   6113:     }
                   6114: 
1.620     albertel 6115:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6116: # Free bre access to adm and meta resources
1.775     albertel 6117:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6118: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6119: 	&& ($priv eq 'bre')) {
1.14      www      6120: 	return 'F';
1.159     www      6121:     }
                   6122: 
1.545     banghart 6123: # Free bre access to user's own portfolio contents
1.714     raeburn  6124:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6125:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6126: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6127:         my %setters;
                   6128:         my ($startblock,$endblock) = 
                   6129:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6130:         if ($startblock && $endblock) {
                   6131:             return 'B';
                   6132:         } else {
                   6133:             return 'F';
                   6134:         }
1.545     banghart 6135:     }
                   6136: 
1.762     raeburn  6137: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6138:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6139:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6140:         if (exists($env{'request.course.id'})) {
                   6141:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6142:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6143:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6144:                 my $courseprivid=$env{'request.course.id'};
                   6145:                 $courseprivid=~s/\_/\//;
                   6146:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6147:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6148:                     return $1; 
1.762     raeburn  6149:                 } else {
                   6150:                     if ($env{'request.course.sec'}) {
                   6151:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6152:                     }
                   6153:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6154:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6155:                         return $2;
                   6156:                     }
1.714     raeburn  6157:                 }
                   6158:             }
                   6159:         }
                   6160:     }
                   6161: 
1.159     www      6162: # Free bre to public access
                   6163: 
                   6164:     if ($priv eq 'bre') {
1.238     www      6165:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6166: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6167:            return 'F'; 
                   6168:         }
1.238     www      6169:         if ($copyright eq 'priv') {
                   6170:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6171: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6172: 		return '';
                   6173:             }
                   6174:         }
                   6175:         if ($copyright eq 'domain') {
                   6176:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6177: 	    unless (($env{'user.domain'} eq $1) ||
                   6178:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6179: 		return '';
                   6180:             }
1.262     matthew  6181:         }
1.620     albertel 6182:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6183:             # Library role, so allow browsing of resources in this domain.
                   6184:             return 'F';
1.238     www      6185:         }
1.341     www      6186:         if ($copyright eq 'custom') {
                   6187: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6188:         }
1.14      www      6189:     }
1.264     matthew  6190:     # Domain coordinator is trying to create a course
1.620     albertel 6191:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6192:         # uri is the requested domain in this case.
                   6193:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6194:         # a role of dc for the domain in question.
1.620     albertel 6195:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6196:     }
1.29      www      6197: 
1.52      www      6198:     my $thisallowed='';
                   6199:     my $statecond=0;
                   6200:     my $courseprivid='';
                   6201: 
1.1039    raeburn  6202:     my $ownaccess;
1.1043    raeburn  6203:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6204:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6205:         if ($uri eq '') {
                   6206:             $ownaccess = 1;
                   6207:         } else {
                   6208:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6209:                 my $udom = $env{'user.domain'};
                   6210:                 my $uname = $env{'user.name'};
                   6211:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6212:                     $ownaccess = 1;
1.1040    raeburn  6213:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6214:                     unless ($uri =~ m{\.\./}) {
                   6215:                         $ownaccess = 1;
                   6216:                     }
                   6217:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6218:                     my $now = time;
                   6219:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6220:                         my $adom = $1;
                   6221:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6222:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6223:                                 my ($start,$end) = split('.',$env{$key});
                   6224:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6225:                                     $ownaccess = 1;
                   6226:                                     last;
                   6227:                                 }
                   6228:                             }
                   6229:                         }
                   6230:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6231:                         my $adom = $1;
                   6232:                         my $aname = $2;
1.1042    raeburn  6233:                         foreach my $role ('ca','aa') { 
                   6234:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6235:                                 my ($start,$end) =
                   6236:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6237:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6238:                                     $ownaccess = 1;
                   6239:                                     last;
                   6240:                                 }
1.1039    raeburn  6241:                             }
                   6242:                         }
                   6243:                     }
                   6244:                 }
                   6245:             }
                   6246:         }
                   6247:     }
                   6248: 
1.52      www      6249: # Course
                   6250: 
1.620     albertel 6251:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6252:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6253:             $thisallowed.=$1;
                   6254:         }
1.52      www      6255:     }
1.29      www      6256: 
1.52      www      6257: # Domain
                   6258: 
1.620     albertel 6259:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6260:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6261:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6262:             $thisallowed.=$1;
                   6263:         }
1.12      www      6264:     }
1.52      www      6265: 
1.1141    raeburn  6266: # User who is not author or co-author might still be able to edit
                   6267: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6268:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6269:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6270:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6271:             $thisallowed.=$1;
                   6272:         }
                   6273:     }
                   6274: 
1.52      www      6275: # Course: uri itself is a course
1.66      www      6276:     my $courseuri=$uri;
                   6277:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6278:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6279: 
1.620     albertel 6280:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6281:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6282:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6283:             $thisallowed.=$1;
                   6284:         }
1.12      www      6285:     }
1.29      www      6286: 
1.665     albertel 6287: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6288: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6289:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6290: 	$thisallowed='';
1.671     raeburn  6291:         my ($match)=&is_on_map($uri);
                   6292:         if ($match) {
                   6293:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6294:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6295:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6296:                 if (@blockers > 0) {
                   6297:                     $thisallowed = 'B';
                   6298:                 } else {
                   6299:                     $thisallowed.=$1;
                   6300:                 }
1.671     raeburn  6301:             }
                   6302:         } else {
1.705     albertel 6303:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6304:             if ($refuri) {
                   6305:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6306:                     $thisallowed='F';
1.671     raeburn  6307:                 } else {
                   6308:                     $refuri=&declutter($refuri);
                   6309:                     my ($match) = &is_on_map($refuri);
                   6310:                     if ($match) {
1.1162    raeburn  6311:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6312:                         if (@blockers > 0) {
                   6313:                             $thisallowed = 'B';
                   6314:                         } else {
                   6315:                             $thisallowed='F';
                   6316:                         }
1.671     raeburn  6317:                     }
1.669     raeburn  6318:                 }
1.671     raeburn  6319:             }
                   6320:         }
1.314     www      6321:     }
1.492     albertel 6322: 
1.766     albertel 6323:     if ($priv eq 'bre'
                   6324: 	&& $thisallowed ne 'F' 
                   6325: 	&& $thisallowed ne '2'
                   6326: 	&& &is_portfolio_url($uri)) {
                   6327: 	$thisallowed = &portfolio_access($uri);
                   6328:     }
                   6329:     
1.52      www      6330: # Full access at system, domain or course-wide level? Exit.
1.29      www      6331:     if ($thisallowed=~/F/) {
                   6332: 	return 'F';
                   6333:     }
                   6334: 
1.52      www      6335: # If this is generating or modifying users, exit with special codes
1.29      www      6336: 
1.643     www      6337:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6338: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6339: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6340: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6341: 	    unless ($auname) { return $thisallowed; }
                   6342: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6343: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6344: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6345: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6346: 	}
1.52      www      6347: 	return $thisallowed;
                   6348:     }
                   6349: #
1.103     harris41 6350: # Gathered so far: system, domain and course wide privileges
1.52      www      6351: #
                   6352: # Course: See if uri or referer is an individual resource that is part of 
                   6353: # the course
                   6354: 
1.620     albertel 6355:     if ($env{'request.course.id'}) {
1.232     www      6356: 
1.620     albertel 6357:        $courseprivid=$env{'request.course.id'};
                   6358:        if ($env{'request.course.sec'}) {
                   6359:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6360:        }
                   6361:        $courseprivid=~s/\_/\//;
                   6362:        my $checkreferer=1;
1.232     www      6363:        my ($match,$cond)=&is_on_map($uri);
                   6364:        if ($match) {
                   6365:            $statecond=$cond;
1.620     albertel 6366:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6367:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6368:                my $value = $1;
                   6369:                if ($priv eq 'bre') {
                   6370:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6371:                    if (@blockers > 0) {
                   6372:                        $thisallowed = 'B';
                   6373:                    } else {
                   6374:                        $thisallowed.=$value;
                   6375:                    }
                   6376:                } else {
                   6377:                    $thisallowed.=$value;
                   6378:                }
1.52      www      6379:                $checkreferer=0;
                   6380:            }
1.29      www      6381:        }
1.83      www      6382:        
1.148     www      6383:        if ($checkreferer) {
1.620     albertel 6384: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6385:             unless ($refuri) {
1.800     albertel 6386:                 foreach my $key (keys(%env)) {
                   6387: 		    if ($key=~/^httpref\..*\*/) {
                   6388: 			my $pattern=$key;
1.156     www      6389:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6390:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6391:                         $pattern=~s/\//\\\//g;
1.152     www      6392:                         if ($orguri=~/$pattern/) {
1.800     albertel 6393: 			    $refuri=$env{$key};
1.148     www      6394:                         }
                   6395:                     }
1.191     harris41 6396:                 }
1.148     www      6397:             }
1.232     www      6398: 
1.148     www      6399:          if ($refuri) { 
1.152     www      6400: 	  $refuri=&declutter($refuri);
1.232     www      6401:           my ($match,$cond)=&is_on_map($refuri);
                   6402:             if ($match) {
                   6403:               my $refstatecond=$cond;
1.620     albertel 6404:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6405:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6406:                   my $value = $1;
                   6407:                   if ($priv eq 'bre') {
                   6408:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6409:                       if (@blockers > 0) {
                   6410:                           $thisallowed = 'B';
                   6411:                       } else {
                   6412:                           $thisallowed.=$value;
                   6413:                       }
                   6414:                   } else {
                   6415:                       $thisallowed.=$value;
                   6416:                   }
1.53      www      6417:                   $uri=$refuri;
                   6418:                   $statecond=$refstatecond;
1.52      www      6419:               }
                   6420:           }
1.148     www      6421:         }
1.29      www      6422:        }
1.52      www      6423:    }
1.29      www      6424: 
1.52      www      6425: #
1.103     harris41 6426: # Gathered now: all privileges that could apply, and condition number
1.52      www      6427: # 
                   6428: #
                   6429: # Full or no access?
                   6430: #
1.29      www      6431: 
1.52      www      6432:     if ($thisallowed=~/F/) {
                   6433: 	return 'F';
                   6434:     }
1.29      www      6435: 
1.52      www      6436:     unless ($thisallowed) {
                   6437:         return '';
                   6438:     }
1.29      www      6439: 
1.52      www      6440: # Restrictions exist, deal with them
                   6441: #
                   6442: #   C:according to course preferences
                   6443: #   R:according to resource settings
                   6444: #   L:unless locked
                   6445: #   X:according to user session state
                   6446: #
                   6447: 
                   6448: # Possibly locked functionality, check all courses
1.54      www      6449: # Locks might take effect only after 10 minutes cache expiration for other
                   6450: # courses, and 2 minutes for current course
1.52      www      6451: 
                   6452:     my $envkey;
                   6453:     if ($thisallowed=~/L/) {
1.1000    raeburn  6454:         foreach $envkey (keys(%env)) {
1.54      www      6455:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6456:                my $courseid=$2;
                   6457:                my $roleid=$1.'.'.$2;
1.92      www      6458:                $courseid=~s/^\///;
1.54      www      6459:                my $expiretime=600;
1.620     albertel 6460:                if ($env{'request.role'} eq $roleid) {
1.54      www      6461: 		  $expiretime=120;
                   6462:                }
                   6463: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6464:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6465:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6466: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6467:                }
1.620     albertel 6468:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6469:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6470: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6471:                        &log($env{'user.domain'},$env{'user.name'},
                   6472:                             $env{'user.home'},
1.57      www      6473:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6474:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6475:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6476: 		       return '';
                   6477:                    }
                   6478:                }
1.620     albertel 6479:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6480:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6481: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6482:                        &log($env{'user.domain'},$env{'user.name'},
                   6483:                             $env{'user.home'},
1.57      www      6484:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6485:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6486:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6487: 		       return '';
                   6488:                    }
                   6489:                }
                   6490: 	   }
1.29      www      6491:        }
1.52      www      6492:     }
                   6493:    
                   6494: #
                   6495: # Rest of the restrictions depend on selected course
                   6496: #
                   6497: 
1.620     albertel 6498:     unless ($env{'request.course.id'}) {
1.766     albertel 6499: 	if ($thisallowed eq 'A') {
                   6500: 	    return 'A';
1.814     raeburn  6501:         } elsif ($thisallowed eq 'B') {
                   6502:             return 'B';
1.766     albertel 6503: 	} else {
                   6504: 	    return '1';
                   6505: 	}
1.52      www      6506:     }
1.29      www      6507: 
1.52      www      6508: #
                   6509: # Now user is definitely in a course
                   6510: #
1.53      www      6511: 
                   6512: 
                   6513: # Course preferences
                   6514: 
                   6515:    if ($thisallowed=~/C/) {
1.620     albertel 6516:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6517:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6518:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6519: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6520: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6521: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6522: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6523: 			$env{'request.course.id'});
                   6524: 	   }
1.237     www      6525:            return '';
                   6526:        }
                   6527: 
1.620     albertel 6528:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6529: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6530: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6531: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6532: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6533: 			$env{'request.course.id'});
                   6534: 	   }
1.54      www      6535:            return '';
                   6536:        }
1.53      www      6537:    }
                   6538: 
                   6539: # Resource preferences
                   6540: 
                   6541:    if ($thisallowed=~/R/) {
1.620     albertel 6542:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6543:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6544: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6545: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6546: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6547: 	   }
                   6548: 	   return '';
1.54      www      6549:        }
1.53      www      6550:    }
1.30      www      6551: 
1.246     www      6552: # Restricted by state or randomout?
1.30      www      6553: 
1.52      www      6554:    if ($thisallowed=~/X/) {
1.620     albertel 6555:       if ($env{'acc.randomout'}) {
1.579     albertel 6556: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6557:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6558:             return ''; 
                   6559:          }
1.247     www      6560:       }
                   6561:       if (&condval($statecond)) {
1.52      www      6562: 	 return '2';
                   6563:       } else {
                   6564:          return '';
                   6565:       }
                   6566:    }
1.30      www      6567: 
1.766     albertel 6568:     if ($thisallowed eq 'A') {
                   6569: 	return 'A';
1.814     raeburn  6570:     } elsif ($thisallowed eq 'B') {
                   6571:         return 'B';
1.766     albertel 6572:     }
1.52      www      6573:    return 'F';
1.232     www      6574: }
1.1162    raeburn  6575: 
1.1192    raeburn  6576: # ------------------------------------------- Check construction space access
                   6577: 
                   6578: sub constructaccess {
                   6579:     my ($url,$setpriv)=@_;
                   6580: 
                   6581: # We do not allow editing of previous versions of files
                   6582:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6583: 
                   6584: # Get username and domain from URL
                   6585:     my ($ownername,$ownerdomain,$ownerhome);
                   6586: 
                   6587:     ($ownerdomain,$ownername) =
                   6588:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6589: 
                   6590: # The URL does not really point to any authorspace, forget it
                   6591:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6592: 
                   6593: # Now we need to see if the user has access to the authorspace of
                   6594: # $ownername at $ownerdomain
                   6595: 
                   6596:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6597: # Real author for this?
                   6598:        $ownerhome = $env{'user.home'};
                   6599:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6600:           return ($ownername,$ownerdomain,$ownerhome);
                   6601:        }
                   6602:     } else {
                   6603: # Co-author for this?
                   6604:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6605:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6606:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6607:             return ($ownername,$ownerdomain,$ownerhome);
                   6608:         }
                   6609:     }
                   6610: 
                   6611: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6612: # we might as well leave
                   6613:    unless ($setpriv) { return ''; }
                   6614: 
                   6615: # Backdoor access?
                   6616:     my $allowed=&allowed('eco',$ownerdomain);
                   6617: # Nope
                   6618:     unless ($allowed) { return ''; }
                   6619: # Looks like we may have access, but could be locked by the owner of the construction space
                   6620:     if ($allowed eq 'U') {
                   6621:         my %blocked=&get('environment',['domcoord.author'],
                   6622:                          $ownerdomain,$ownername);
                   6623: # Is blocked by owner
                   6624:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6625:     }
                   6626:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6627: # Grant temporary access
                   6628:         my $then=$env{'user.login.time'};
                   6629:         my $update==$env{'user.update.time'};
                   6630:         if (!$update) { $update = $then; }
                   6631:         my $refresh=$env{'user.refresh.time'};
                   6632:         if (!$refresh) { $refresh = $update; }
                   6633:         my $now = time;
                   6634:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6635:                            $now,'ca','constructaccess');
                   6636:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6637:         return($ownername,$ownerdomain,$ownerhome);
                   6638:     }
                   6639: # No business here
                   6640:     return '';
                   6641: }
                   6642: 
1.1162    raeburn  6643: sub get_comm_blocks {
                   6644:     my ($cdom,$cnum) = @_;
                   6645:     if ($cdom eq '' || $cnum eq '') {
                   6646:         return unless ($env{'request.course.id'});
                   6647:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6648:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6649:     }
                   6650:     my %commblocks;
                   6651:     my $hashid=$cdom.'_'.$cnum;
                   6652:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6653:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6654:         %commblocks = %{$blocksref};
                   6655:     } else {
                   6656:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6657:         my $cachetime = 600;
                   6658:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6659:     }
                   6660:     return %commblocks;
                   6661: }
                   6662: 
                   6663: sub has_comm_blocking {
                   6664:     my ($priv,$symb,$uri,$blocks) = @_;
                   6665:     return unless ($env{'request.course.id'});
                   6666:     return unless ($priv eq 'bre');
                   6667:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6668:     my %commblocks;
                   6669:     if (ref($blocks) eq 'HASH') {
                   6670:         %commblocks = %{$blocks};
                   6671:     } else {
                   6672:         %commblocks = &get_comm_blocks();
                   6673:     }
                   6674:     return unless (keys(%commblocks) > 0);
                   6675:     if (!$symb) { $symb=&symbread($uri,1); }
                   6676:     my ($map,$resid,undef)=&decode_symb($symb);
                   6677:     my %tocheck = (
                   6678:                     maps      => $map,
                   6679:                     resources => $symb,
                   6680:                   );
                   6681:     my @blockers;
                   6682:     my $now = time;
1.1163    raeburn  6683:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6684:     foreach my $block (keys(%commblocks)) {
                   6685:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6686:             my ($start,$end) = ($1,$2);
                   6687:             if ($start <= $now && $end >= $now) {
                   6688:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6689:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6690:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6691:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6692:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6693:                                     push(@blockers,$block);
                   6694:                                 }
                   6695:                             }
                   6696:                         }
                   6697:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6698:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6699:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6700:                                     push(@blockers,$block);
                   6701:                                 }
                   6702:                             }
                   6703:                         }
                   6704:                     }
                   6705:                 }
                   6706:             }
                   6707:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6708:             my $item = $1;
1.1163    raeburn  6709:             my @to_test;
1.1162    raeburn  6710:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6711:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6712:                     my $check_interval;
                   6713:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6714:                         my @interval;
                   6715:                         my $type = 'map';
                   6716:                         if ($item eq 'course') {
                   6717:                             $type = 'course';
                   6718:                             @interval=&EXT("resource.0.interval");
                   6719:                         } else {
                   6720:                             if ($item =~ /___\d+___/) {
                   6721:                                 $type = 'resource';
                   6722:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6723:                                 if (ref($navmap)) {                        
                   6724:                                     my $res = $navmap->getBySymb($item); 
                   6725:                                     push(@to_test,$res);
                   6726:                                 }
1.1162    raeburn  6727:                             } else {
                   6728:                                 my $mapsymb = &symbread($item,1);
                   6729:                                 if ($mapsymb) {
                   6730:                                     if (ref($navmap)) {
                   6731:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6732:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6733:                                         foreach my $res (@to_test) {
1.1162    raeburn  6734:                                             my $symb = $res->symb();
                   6735:                                             next if ($symb eq $mapsymb);
                   6736:                                             if ($symb ne '') {
                   6737:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6738:                                                 last;
                   6739:                                             }
                   6740:                                         }
                   6741:                                     }
                   6742:                                 }
                   6743:                             }
                   6744:                         }
                   6745:                         if ($interval[0] =~ /\d+/) {
                   6746:                             my $first_access;
                   6747:                             if ($type eq 'resource') {
                   6748:                                 $first_access=&get_first_access($interval[1],$item);
                   6749:                             } elsif ($type eq 'map') {
                   6750:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6751:                             } else {
                   6752:                                 $first_access=&get_first_access($interval[1]);
                   6753:                             }
                   6754:                             if ($first_access) {
                   6755:                                 my $timesup = $first_access+$interval[0];
                   6756:                                 if ($timesup > $now) {
1.1163    raeburn  6757:                                     foreach my $res (@to_test) {
                   6758:                                         if ($res->is_problem()) {
                   6759:                                             if ($res->completable()) {
                   6760:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6761:                                                     push(@blockers,$block);
                   6762:                                                 }
                   6763:                                                 last;
                   6764:                                             }
                   6765:                                         }
1.1162    raeburn  6766:                                     }
                   6767:                                 }
                   6768:                             }
                   6769:                         }
                   6770:                     }
                   6771:                 }
                   6772:             }
                   6773:         }
                   6774:     }
                   6775:     return @blockers;
                   6776: }
                   6777: 
                   6778: sub check_docs_block {
                   6779:     my ($docsblock,$tocheck) =@_;
                   6780:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6781:         return;
                   6782:     }
                   6783:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6784:         if ($tocheck->{'maps'}) {
                   6785:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6786:                 return 1;
                   6787:             }
                   6788:         }
                   6789:     }
                   6790:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6791:         if ($tocheck->{'resources'}) {
                   6792:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6793:                 return 1;
                   6794:             }
                   6795:         }
                   6796:     }
                   6797:     return;
                   6798: }
                   6799: 
1.1133    foxr     6800: #
                   6801: #   Removes the versino from a URI and
                   6802: #   splits it in to its filename and path to the filename.
                   6803: #   Seems like File::Basename could have done this more clearly.
                   6804: #   Parameters:
                   6805: #      $uri   - input URI
                   6806: #   Returns:
                   6807: #     Two element list consisting of 
                   6808: #     $pathname  - the URI up to and excluding the trailing /
                   6809: #     $filename  - The part of the URI following the last /
                   6810: #  NOTE:
                   6811: #    Another realization of this is simply:
                   6812: #    use File::Basename;
                   6813: #    ...
                   6814: #    $uri = shift;
                   6815: #    $filename = basename($uri);
                   6816: #    $path     = dirname($uri);
                   6817: #    return ($filename, $path);
                   6818: #
                   6819: #     The implementation below is probably faster however.
                   6820: #
1.710     albertel 6821: sub split_uri_for_cond {
                   6822:     my $uri=&deversion(&declutter(shift));
                   6823:     my @uriparts=split(/\//,$uri);
                   6824:     my $filename=pop(@uriparts);
                   6825:     my $pathname=join('/',@uriparts);
                   6826:     return ($pathname,$filename);
                   6827: }
1.232     www      6828: # --------------------------------------------------- Is a resource on the map?
                   6829: 
                   6830: sub is_on_map {
1.710     albertel 6831:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6832:     #Trying to find the conditional for the file
1.620     albertel 6833:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6834: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6835:     if ($match) {
1.289     bowersj2 6836: 	return (1,$1);
                   6837:     } else {
1.434     www      6838: 	return (0,0);
1.289     bowersj2 6839:     }
1.12      www      6840: }
                   6841: 
1.427     www      6842: # --------------------------------------------------------- Get symb from alias
                   6843: 
                   6844: sub get_symb_from_alias {
                   6845:     my $symb=shift;
                   6846:     my ($map,$resid,$url)=&decode_symb($symb);
                   6847: # Already is a symb
                   6848:     if ($url) { return $symb; }
                   6849: # Must be an alias
                   6850:     my $aliassymb='';
                   6851:     my %bighash;
1.620     albertel 6852:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6853:                             &GDBM_READER(),0640)) {
                   6854:         my $rid=$bighash{'mapalias_'.$symb};
                   6855: 	if ($rid) {
                   6856: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6857: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6858: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6859: 	}
                   6860:         untie %bighash;
                   6861:     }
                   6862:     return $aliassymb;
                   6863: }
                   6864: 
1.12      www      6865: # ----------------------------------------------------------------- Define Role
                   6866: 
                   6867: sub definerole {
                   6868:   if (allowed('mcr','/')) {
                   6869:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6870:     foreach my $role (split(':',$sysrole)) {
                   6871: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6872:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6873:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6874: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6875:                return "refused:s:$crole&$cqual"; 
                   6876:             }
                   6877:         }
1.191     harris41 6878:     }
1.800     albertel 6879:     foreach my $role (split(':',$domrole)) {
                   6880: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6881:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6882:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6883: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6884:                return "refused:d:$crole&$cqual"; 
                   6885:             }
                   6886:         }
1.191     harris41 6887:     }
1.800     albertel 6888:     foreach my $role (split(':',$courole)) {
                   6889: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6890:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6891:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6892: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6893:                return "refused:c:$crole&$cqual"; 
                   6894:             }
                   6895:         }
1.191     harris41 6896:     }
1.620     albertel 6897:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6898:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6899: 	        "rolesdef_$rolename=".
                   6900:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6901:     return reply($command,$env{'user.home'});
1.12      www      6902:   } else {
                   6903:     return 'refused';
                   6904:   }
1.105     harris41 6905: }
                   6906: 
                   6907: # ---------------- Make a metadata query against the network of library servers
                   6908: 
                   6909: sub metadata_query {
1.244     matthew  6910:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6911:     my %rhash;
1.845     albertel 6912:     my %libserv = &all_library();
1.244     matthew  6913:     my @server_list = (defined($server_array) ? @$server_array
                   6914:                                               : keys(%libserv) );
                   6915:     for my $server (@server_list) {
1.118     harris41 6916: 	unless ($custom or $customshow) {
                   6917: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6918: 	    $rhash{$server}=$reply;
                   6919: 	}
                   6920: 	else {
                   6921: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6922: 			     &escape($custom).':'.&escape($customshow),
                   6923: 			     $server);
                   6924: 	    $rhash{$server}=$reply;
                   6925: 	}
1.112     harris41 6926:     }
1.118     harris41 6927:     return \%rhash;
1.240     www      6928: }
                   6929: 
                   6930: # ----------------------------------------- Send log queries and wait for reply
                   6931: 
                   6932: sub log_query {
                   6933:     my ($uname,$udom,$query,%filters)=@_;
                   6934:     my $uhome=&homeserver($uname,$udom);
                   6935:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6936:     my $uhost=&hostname($uhome);
1.800     albertel 6937:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6938:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6939:                        $uhome);
1.479     albertel 6940:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6941:     return get_query_reply($queryid);
                   6942: }
                   6943: 
1.818     raeburn  6944: # -------------------------- Update MySQL table for portfolio file
                   6945: 
                   6946: sub update_portfolio_table {
1.821     raeburn  6947:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6948:     if ($group ne '') {
                   6949:         $file_name =~s /^\Q$group\E//;
                   6950:     }
1.818     raeburn  6951:     my $homeserver = &homeserver($uname,$udom);
                   6952:     my $queryid=
1.821     raeburn  6953:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6954:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6955:     my $reply = &get_query_reply($queryid);
                   6956:     return $reply;
                   6957: }
                   6958: 
1.899     raeburn  6959: # -------------------------- Update MySQL allusers table
                   6960: 
                   6961: sub update_allusers_table {
                   6962:     my ($uname,$udom,$names) = @_;
                   6963:     my $homeserver = &homeserver($uname,$udom);
                   6964:     my $queryid=
                   6965:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6966:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6967:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6968:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6969:                'generation='.&escape($names->{'generation'}).'%%'.
                   6970:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6971:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6972:     return;
1.899     raeburn  6973: }
                   6974: 
1.508     raeburn  6975: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6976: 
                   6977: sub fetch_enrollment_query {
1.511     raeburn  6978:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6979:     my $homeserver;
1.547     raeburn  6980:     my $maxtries = 1;
1.508     raeburn  6981:     if ($context eq 'automated') {
                   6982:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6983:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6984:     } else {
                   6985:         $homeserver = &homeserver($cnum,$dom);
                   6986:     }
1.838     albertel 6987:     my $host=&hostname($homeserver);
1.506     raeburn  6988:     my $cmd = '';
1.1000    raeburn  6989:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6990:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6991:     }
                   6992:     $cmd =~ s/%%$//;
                   6993:     $cmd = &escape($cmd);
                   6994:     my $query = 'fetchenrollment';
1.620     albertel 6995:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6996:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6997:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6998:         return 'error: '.$queryid;
                   6999:     }
1.506     raeburn  7000:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7001:     my $tries = 1;
                   7002:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7003:         $reply = &get_query_reply($queryid);
                   7004:         $tries ++;
                   7005:     }
1.526     raeburn  7006:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7007:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7008:     } else {
1.901     albertel 7009:         my @responses = split(/:/,$reply);
1.515     raeburn  7010:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7011:             foreach my $line (@responses) {
                   7012:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7013:                 $$replyref{$key} = $value;
                   7014:             }
                   7015:         } else {
1.1117    foxr     7016:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7017:             foreach my $line (@responses) {
                   7018:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7019:                 $$replyref{$key} = $value;
                   7020:                 if ($value > 0) {
1.800     albertel 7021:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7022:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7023:                         my $destname = $pathname.'/'.$filename;
                   7024:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7025:                         if ($xml_classlist =~ /^error/) {
                   7026:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7027:                         } else {
1.506     raeburn  7028:                             if ( open(FILE,">$destname") ) {
                   7029:                                 print FILE &unescape($xml_classlist);
                   7030:                                 close(FILE);
1.526     raeburn  7031:                             } else {
                   7032:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7033:                             }
                   7034:                         }
                   7035:                     }
                   7036:                 }
                   7037:             }
                   7038:         }
                   7039:         return 'ok';
                   7040:     }
                   7041:     return 'error';
                   7042: }
                   7043: 
1.242     www      7044: sub get_query_reply {
                   7045:     my $queryid=shift;
1.1117    foxr     7046:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7047:     my $reply='';
                   7048:     for (1..100) {
                   7049: 	sleep 2;
                   7050:         if (-e $replyfile.'.end') {
1.448     albertel 7051: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7052: 		$reply = join('',<$fh>);
                   7053: 		close($fh);
1.240     www      7054: 	   } else { return 'error: reply_file_error'; }
1.242     www      7055:            return &unescape($reply);
                   7056: 	}
1.240     www      7057:     }
1.242     www      7058:     return 'timeout:'.$queryid;
1.240     www      7059: }
                   7060: 
                   7061: sub courselog_query {
1.241     www      7062: #
                   7063: # possible filters:
                   7064: # url: url or symb
                   7065: # username
                   7066: # domain
                   7067: # action: view, submit, grade
                   7068: # start: timestamp
                   7069: # end: timestamp
                   7070: #
1.240     www      7071:     my (%filters)=@_;
1.620     albertel 7072:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7073:     if ($filters{'url'}) {
                   7074: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7075:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7076:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7077:     }
1.620     albertel 7078:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7079:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7080:     return &log_query($cname,$cdom,'courselog',%filters);
                   7081: }
                   7082: 
                   7083: sub userlog_query {
1.858     raeburn  7084: #
                   7085: # possible filters:
                   7086: # action: log check role
                   7087: # start: timestamp
                   7088: # end: timestamp
                   7089: #
1.240     www      7090:     my ($uname,$udom,%filters)=@_;
                   7091:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7092: }
                   7093: 
1.506     raeburn  7094: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7095: 
                   7096: sub auto_run {
1.508     raeburn  7097:     my ($cnum,$cdom) = @_;
1.876     raeburn  7098:     my $response = 0;
                   7099:     my $settings;
                   7100:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7101:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7102:         $settings = $domconfig{'autoenroll'};
                   7103:         if ($settings->{'run'} eq '1') {
                   7104:             $response = 1;
                   7105:         }
                   7106:     } else {
1.934     raeburn  7107:         my $homeserver;
                   7108:         if (&is_course($cdom,$cnum)) {
                   7109:             $homeserver = &homeserver($cnum,$cdom);
                   7110:         } else {
                   7111:             $homeserver = &domain($cdom,'primary');
                   7112:         }
                   7113:         if ($homeserver ne 'no_host') {
                   7114:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7115:         }
1.876     raeburn  7116:     }
1.506     raeburn  7117:     return $response;
                   7118: }
1.776     albertel 7119: 
1.506     raeburn  7120: sub auto_get_sections {
1.508     raeburn  7121:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7122:     my $homeserver;
                   7123:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7124:         $homeserver = &homeserver($cnum,$cdom);
                   7125:     }
                   7126:     if (!defined($homeserver)) { 
                   7127:         if ($cdom =~ /^$match_domain$/) {
                   7128:             $homeserver = &domain($cdom,'primary');
                   7129:         }
                   7130:     }
                   7131:     my @secs;
                   7132:     if (defined($homeserver)) {
                   7133:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7134:         unless ($response eq 'refused') {
                   7135:             @secs = split(/:/,$response);
                   7136:         }
1.506     raeburn  7137:     }
                   7138:     return @secs;
                   7139: }
1.776     albertel 7140: 
1.506     raeburn  7141: sub auto_new_course {
1.1099    raeburn  7142:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7143:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7144:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7145:     return $response;
                   7146: }
1.776     albertel 7147: 
1.506     raeburn  7148: sub auto_validate_courseID {
1.508     raeburn  7149:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7150:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7151:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7152:     return $response;
                   7153: }
1.776     albertel 7154: 
1.1007    raeburn  7155: sub auto_validate_instcode {
1.1020    raeburn  7156:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7157:     my ($homeserver,$response);
                   7158:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7159:         $homeserver = &homeserver($cnum,$cdom);
                   7160:     }
                   7161:     if (!defined($homeserver)) {
                   7162:         if ($cdom =~ /^$match_domain$/) {
                   7163:             $homeserver = &domain($cdom,'primary');
                   7164:         }
                   7165:     }
1.1065    raeburn  7166:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7167:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  7168:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   7169:     return ($outcome,$description);
1.1007    raeburn  7170: }
                   7171: 
1.506     raeburn  7172: sub auto_create_password {
1.873     raeburn  7173:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7174:     my ($homeserver,$response);
1.506     raeburn  7175:     my $create_passwd = 0;
                   7176:     my $authchk = '';
1.873     raeburn  7177:     if ($udom =~ /^$match_domain$/) {
                   7178:         $homeserver = &domain($udom,'primary');
                   7179:     }
                   7180:     if ($homeserver eq '') {
                   7181:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7182:             $homeserver = &homeserver($cnum,$cdom);
                   7183:         }
                   7184:     }
                   7185:     if ($homeserver eq '') {
                   7186:         $authchk = 'nodomain';
1.506     raeburn  7187:     } else {
1.873     raeburn  7188:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7189:         if ($response eq 'refused') {
                   7190:             $authchk = 'refused';
                   7191:         } else {
1.901     albertel 7192:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7193:         }
1.506     raeburn  7194:     }
                   7195:     return ($authparam,$create_passwd,$authchk);
                   7196: }
                   7197: 
1.706     raeburn  7198: sub auto_photo_permission {
                   7199:     my ($cnum,$cdom,$students) = @_;
                   7200:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7201:     my ($outcome,$perm_reqd,$conditions) = 
                   7202: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7203:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7204: 	return (undef,undef);
                   7205:     }
1.706     raeburn  7206:     return ($outcome,$perm_reqd,$conditions);
                   7207: }
                   7208: 
                   7209: sub auto_checkphotos {
                   7210:     my ($uname,$udom,$pid) = @_;
                   7211:     my $homeserver = &homeserver($uname,$udom);
                   7212:     my ($result,$resulttype);
                   7213:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7214: 				   &escape($uname).':'.&escape($pid),
                   7215: 				   $homeserver));
1.709     albertel 7216:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7217: 	return (undef,undef);
                   7218:     }
1.706     raeburn  7219:     if ($outcome) {
                   7220:         ($result,$resulttype) = split(/:/,$outcome);
                   7221:     } 
                   7222:     return ($result,$resulttype);
                   7223: }
                   7224: 
                   7225: sub auto_photochoice {
                   7226:     my ($cnum,$cdom) = @_;
                   7227:     my $homeserver = &homeserver($cnum,$cdom);
                   7228:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7229: 						       &escape($cdom),
                   7230: 						       $homeserver)));
1.709     albertel 7231:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7232: 	return (undef,undef);
                   7233:     }
1.706     raeburn  7234:     return ($update,$comment);
                   7235: }
                   7236: 
                   7237: sub auto_photoupdate {
                   7238:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7239:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7240:     my $host=&hostname($homeserver);
1.706     raeburn  7241:     my $cmd = '';
                   7242:     my $maxtries = 1;
1.800     albertel 7243:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7244:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7245:     }
                   7246:     $cmd =~ s/%%$//;
                   7247:     $cmd = &escape($cmd);
                   7248:     my $query = 'institutionalphotos';
                   7249:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7250:     unless ($queryid=~/^\Q$host\E\_/) {
                   7251:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7252:         return 'error: '.$queryid;
                   7253:     }
                   7254:     my $reply = &get_query_reply($queryid);
                   7255:     my $tries = 1;
                   7256:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7257:         $reply = &get_query_reply($queryid);
                   7258:         $tries ++;
                   7259:     }
                   7260:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7261:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7262:     } else {
                   7263:         my @responses = split(/:/,$reply);
                   7264:         my $outcome = shift(@responses); 
                   7265:         foreach my $item (@responses) {
                   7266:             my ($key,$value) = split(/=/,$item);
                   7267:             $$photo{$key} = $value;
                   7268:         }
                   7269:         return $outcome;
                   7270:     }
                   7271:     return 'error';
                   7272: }
                   7273: 
1.521     raeburn  7274: sub auto_instcode_format {
1.793     albertel 7275:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7276: 	$cat_order) = @_;
1.521     raeburn  7277:     my $courses = '';
1.772     raeburn  7278:     my @homeservers;
1.521     raeburn  7279:     if ($caller eq 'global') {
1.841     albertel 7280: 	my %servers = &get_servers($codedom,'library');
                   7281: 	foreach my $tryserver (keys(%servers)) {
                   7282: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7283: 		push(@homeservers,$tryserver);
                   7284: 	    }
1.584     raeburn  7285:         }
1.1022    raeburn  7286:     } elsif ($caller eq 'requests') {
                   7287:         if ($codedom =~ /^$match_domain$/) {
                   7288:             my $chome = &domain($codedom,'primary');
                   7289:             unless ($chome eq 'no_host') {
                   7290:                 push(@homeservers,$chome);
                   7291:             }
                   7292:         }
1.521     raeburn  7293:     } else {
1.772     raeburn  7294:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7295:     }
1.793     albertel 7296:     foreach my $code (keys(%{$instcodes})) {
                   7297:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7298:     }
                   7299:     chop($courses);
1.772     raeburn  7300:     my $ok_response = 0;
                   7301:     my $response;
                   7302:     while (@homeservers > 0 && $ok_response == 0) {
                   7303:         my $server = shift(@homeservers); 
                   7304:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7305:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7306:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7307: 		split(/:/,$response);
1.772     raeburn  7308:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7309:             push(@{$codetitles},&str2array($codetitles_str));
                   7310:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7311:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7312:             $ok_response = 1;
                   7313:         }
                   7314:     }
                   7315:     if ($ok_response) {
1.521     raeburn  7316:         return 'ok';
1.772     raeburn  7317:     } else {
                   7318:         return $response;
1.521     raeburn  7319:     }
                   7320: }
                   7321: 
1.792     raeburn  7322: sub auto_instcode_defaults {
                   7323:     my ($domain,$returnhash,$code_order) = @_;
                   7324:     my @homeservers;
1.841     albertel 7325: 
                   7326:     my %servers = &get_servers($domain,'library');
                   7327:     foreach my $tryserver (keys(%servers)) {
                   7328: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7329: 	    push(@homeservers,$tryserver);
                   7330: 	}
1.792     raeburn  7331:     }
1.841     albertel 7332: 
1.792     raeburn  7333:     my $response;
1.841     albertel 7334:     foreach my $server (@homeservers) {
1.792     raeburn  7335:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7336:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7337: 	
                   7338: 	foreach my $pair (split(/\&/,$response)) {
                   7339: 	    my ($name,$value)=split(/\=/,$pair);
                   7340: 	    if ($name eq 'code_order') {
                   7341: 		@{$code_order} = split(/\&/,&unescape($value));
                   7342: 	    } else {
                   7343: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7344: 	    }
                   7345: 	}
                   7346: 	return 'ok';
1.792     raeburn  7347:     }
1.841     albertel 7348: 
                   7349:     return $response;
1.1003    raeburn  7350: }
                   7351: 
                   7352: sub auto_possible_instcodes {
1.1007    raeburn  7353:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7354:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7355:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7356:         return;
                   7357:     }
1.1003    raeburn  7358:     my (@homeservers,$uhome);
                   7359:     if (defined(&domain($domain,'primary'))) {
                   7360:         $uhome=&domain($domain,'primary');
                   7361:         push(@homeservers,&domain($domain,'primary'));
                   7362:     } else {
                   7363:         my %servers = &get_servers($domain,'library');
                   7364:         foreach my $tryserver (keys(%servers)) {
                   7365:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7366:                 push(@homeservers,$tryserver);
                   7367:             }
                   7368:         }
                   7369:     }
                   7370:     my $response;
                   7371:     foreach my $server (@homeservers) {
                   7372:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7373:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7374:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7375:             split(':',$response);
                   7376:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7377:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7378:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7379:             my ($name,$value)=split('=',$item);
                   7380:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7381:         }
                   7382:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7383:             my ($name,$value)=split('=',$item);
                   7384:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7385:         }
                   7386:         return 'ok';
                   7387:     }
                   7388:     return $response;
                   7389: }
1.792     raeburn  7390: 
1.1010    raeburn  7391: sub auto_courserequest_checks {
                   7392:     my ($dom) = @_;
1.1020    raeburn  7393:     my ($homeserver,%validations);
                   7394:     if ($dom =~ /^$match_domain$/) {
                   7395:         $homeserver = &domain($dom,'primary');
                   7396:     }
                   7397:     unless ($homeserver eq 'no_host') {
                   7398:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7399:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7400:             my @items = split(/&/,$response);
                   7401:             foreach my $item (@items) {
                   7402:                 my ($key,$value) = split('=',$item);
                   7403:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7404:             }
                   7405:         }
                   7406:     }
1.1010    raeburn  7407:     return %validations; 
                   7408: }
                   7409: 
1.1020    raeburn  7410: sub auto_courserequest_validation {
                   7411:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7412:     my ($homeserver,$response);
                   7413:     if ($dom =~ /^$match_domain$/) {
                   7414:         $homeserver = &domain($dom,'primary');
                   7415:     }
                   7416:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7417:           
1.1020    raeburn  7418:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7419:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7420:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7421:                                     $homeserver));
                   7422:     }
                   7423:     return $response;
                   7424: }
                   7425: 
1.777     albertel 7426: sub auto_validate_class_sec {
1.918     raeburn  7427:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7428:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7429:     my $ownerlist;
                   7430:     if (ref($owners) eq 'ARRAY') {
                   7431:         $ownerlist = join(',',@{$owners});
                   7432:     } else {
                   7433:         $ownerlist = $owners;
                   7434:     }
1.773     raeburn  7435:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7436:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7437:     return $response;
                   7438: }
                   7439: 
1.679     raeburn  7440: # ------------------------------------------------------- Course Group routines
                   7441: 
                   7442: sub get_coursegroups {
1.809     raeburn  7443:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7444:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7445: }
                   7446: 
1.679     raeburn  7447: sub modify_coursegroup {
                   7448:     my ($cdom,$cnum,$groupsettings) = @_;
                   7449:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7450: }
                   7451: 
1.809     raeburn  7452: sub toggle_coursegroup_status {
                   7453:     my ($cdom,$cnum,$group,$action) = @_;
                   7454:     my ($from_namespace,$to_namespace);
                   7455:     if ($action eq 'delete') {
                   7456:         $from_namespace = 'coursegroups';
                   7457:         $to_namespace = 'deleted_groups';
                   7458:     } else {
                   7459:         $from_namespace = 'deleted_groups';
                   7460:         $to_namespace = 'coursegroups';
                   7461:     }
                   7462:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7463:     if (my $tmp = &error(%curr_group)) {
                   7464:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7465:         return ('read error',$tmp);
                   7466:     } else {
                   7467:         my %savedsettings = %curr_group; 
1.809     raeburn  7468:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7469:         my $deloutcome;
                   7470:         if ($result eq 'ok') {
1.809     raeburn  7471:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7472:         } else {
                   7473:             return ('write error',$result);
                   7474:         }
                   7475:         if ($deloutcome eq 'ok') {
                   7476:             return 'ok';
                   7477:         } else {
                   7478:             return ('delete error',$deloutcome);
                   7479:         }
                   7480:     }
                   7481: }
                   7482: 
1.679     raeburn  7483: sub modify_group_roles {
1.957     raeburn  7484:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7485:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7486:     my $role = 'gr/'.&escape($userprivs);
                   7487:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7488:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7489:     if ($result eq 'ok') {
                   7490:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7491:     }
1.679     raeburn  7492:     return $result;
                   7493: }
                   7494: 
                   7495: sub modify_coursegroup_membership {
                   7496:     my ($cdom,$cnum,$membership) = @_;
                   7497:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7498:     return $result;
                   7499: }
                   7500: 
1.682     raeburn  7501: sub get_active_groups {
                   7502:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7503:     my $now = time;
                   7504:     my %groups = ();
                   7505:     foreach my $key (keys(%env)) {
1.811     albertel 7506:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7507:             my ($start,$end) = split(/\./,$env{$key});
                   7508:             if (($end!=0) && ($end<$now)) { next; }
                   7509:             if (($start!=0) && ($start>$now)) { next; }
                   7510:             if ($1 eq $cdom && $2 eq $cnum) {
                   7511:                 $groups{$3} = $env{$key} ;
                   7512:             }
                   7513:         }
                   7514:     }
                   7515:     return %groups;
                   7516: }
                   7517: 
1.683     raeburn  7518: sub get_group_membership {
                   7519:     my ($cdom,$cnum,$group) = @_;
                   7520:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7521: }
                   7522: 
                   7523: sub get_users_groups {
                   7524:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7525:     my @usersgroups;
1.683     raeburn  7526:     my $cachetime=1800;
                   7527: 
                   7528:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7529:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7530:     if (defined($cached)) {
1.734     albertel 7531:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7532:     } else {  
                   7533:         $grouplist = '';
1.816     raeburn  7534:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7535:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7536:         my $access_end = $env{'course.'.$courseid.
                   7537:                               '.default_enrollment_end_date'};
                   7538:         my $now = time;
                   7539:         foreach my $key (keys(%roleshash)) {
                   7540:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7541:                 my $group = $1;
                   7542:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7543:                     my $start = $2;
                   7544:                     my $end = $1;
                   7545:                     if ($start == -1) { next; } # deleted from group
                   7546:                     if (($start!=0) && ($start>$now)) { next; }
                   7547:                     if (($end!=0) && ($end<$now)) {
                   7548:                         if ($access_end && $access_end < $now) {
                   7549:                             if ($access_end - $end < 86400) {
                   7550:                                 push(@usersgroups,$group);
1.733     raeburn  7551:                             }
                   7552:                         }
1.817     raeburn  7553:                         next;
1.733     raeburn  7554:                     }
1.817     raeburn  7555:                     push(@usersgroups,$group);
1.683     raeburn  7556:                 }
                   7557:             }
                   7558:         }
1.817     raeburn  7559:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7560:         $grouplist = join(':',@usersgroups);
                   7561:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7562:     }
1.733     raeburn  7563:     return @usersgroups;
1.683     raeburn  7564: }
                   7565: 
                   7566: sub devalidate_getgroups_cache {
                   7567:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7568:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7569: 
1.683     raeburn  7570:     my $hashid="$udom:$uname:$courseid";
                   7571:     &devalidate_cache_new('getgroups',$hashid);
                   7572: }
                   7573: 
1.12      www      7574: # ------------------------------------------------------------------ Plain Text
                   7575: 
                   7576: sub plaintext {
1.988     raeburn  7577:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7578:     if ($short =~ m{^cr/}) {
1.758     albertel 7579: 	return (split('/',$short))[-1];
                   7580:     }
1.742     raeburn  7581:     if (!defined($cid)) {
                   7582:         $cid = $env{'request.course.id'};
                   7583:     }
                   7584:     my %rolenames = (
1.1008    raeburn  7585:                       Course    => 'std',
                   7586:                       Community => 'alt1',
1.742     raeburn  7587:                     );
1.1037    raeburn  7588:     if ($cid ne '') {
                   7589:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7590:             unless ($forcedefault) {
                   7591:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7592:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7593:                 return &Apache::lonlocal::mt($roletext);
                   7594:             }
                   7595:         }
                   7596:     }
                   7597:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7598:         (defined($rolenames{$type})) && 
                   7599:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7600:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7601:     } elsif ($cid ne '') {
                   7602:         my $crstype = $env{'course.'.$cid.'.type'};
                   7603:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7604:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7605:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7606:         }
1.742     raeburn  7607:     }
1.1037    raeburn  7608:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7609: }
                   7610: 
                   7611: # ----------------------------------------------------------------- Assign Role
                   7612: 
                   7613: sub assignrole {
1.957     raeburn  7614:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7615:         $context)=@_;
1.21      www      7616:     my $mrole;
                   7617:     if ($role =~ /^cr\//) {
1.393     www      7618:         my $cwosec=$url;
1.811     albertel 7619:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7620: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7621:            my $refused = 1;
                   7622:            if ($context eq 'requestcourses') {
                   7623:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7624:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7625:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7626:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7627:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7628:                            if ($crsenv{'internal.courseowner'} eq
                   7629:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7630:                                $refused = '';
                   7631:                            }
                   7632:                        }
                   7633:                    }
                   7634:                }
                   7635:            }
                   7636:            if ($refused) {
                   7637:                &logthis('Refused custom assignrole: '.
                   7638:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7639:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7640:                return 'refused';
                   7641:            }
1.104     www      7642:         }
1.21      www      7643:         $mrole='cr';
1.678     raeburn  7644:     } elsif ($role =~ /^gr\//) {
                   7645:         my $cwogrp=$url;
1.811     albertel 7646:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7647:         unless (&allowed('mdg',$cwogrp)) {
                   7648:             &logthis('Refused group assignrole: '.
                   7649:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7650:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7651:             return 'refused';
                   7652:         }
                   7653:         $mrole='gr';
1.21      www      7654:     } else {
1.82      www      7655:         my $cwosec=$url;
1.811     albertel 7656:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7657:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7658:             my $refused;
                   7659:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7660:                 if (!(&allowed('c'.$role,$url))) {
                   7661:                     $refused = 1;
                   7662:                 }
                   7663:             } else {
                   7664:                 $refused = 1;
                   7665:             }
1.947     raeburn  7666:             if ($refused) {
1.1045    raeburn  7667:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7668:                 if (!$selfenroll && $context eq 'course') {
                   7669:                     my %crsenv;
                   7670:                     if ($role eq 'cc' || $role eq 'co') {
                   7671:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7672:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7673:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7674:                                 if ($crsenv{'internal.courseowner'} eq 
                   7675:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7676:                                     $refused = '';
                   7677:                                 }
                   7678:                             }
                   7679:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7680:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7681:                                 if ($crsenv{'internal.courseowner'} eq 
                   7682:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7683:                                     $refused = '';
                   7684:                                 }
                   7685:                             }
                   7686:                         }
                   7687:                     }
                   7688:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7689:                     $refused = '';
1.1017    raeburn  7690:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7691:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7692:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7693:                         my $wrongcc;
                   7694:                         if ($cnum =~ /^$match_community$/) {
                   7695:                             $wrongcc = 1 if ($role eq 'cc');
                   7696:                         } else {
                   7697:                             $wrongcc = 1 if ($role eq 'co');
                   7698:                         }
                   7699:                         unless ($wrongcc) {
                   7700:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7701:                             if ($crsenv{'internal.courseowner'} eq 
                   7702:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7703:                                 $refused = '';
                   7704:                             }
1.1017    raeburn  7705:                         }
                   7706:                     }
1.1183    raeburn  7707:                 } elsif ($context eq 'requestauthor') {
                   7708:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   7709:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7710:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7711:                             $refused = '';
                   7712:                         } else {
                   7713:                             my %domdefaults = &get_domain_defaults($udom);
                   7714:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7715:                                 my $checkbystatus;
                   7716:                                 if ($env{'user.adv'}) { 
                   7717:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7718:                                     if ($disposition eq 'automatic') {
                   7719:                                         $refused = '';
                   7720:                                     } elsif ($disposition eq '') {
                   7721:                                         $checkbystatus = 1;
                   7722:                                     } 
                   7723:                                 } else {
                   7724:                                     $checkbystatus = 1;
                   7725:                                 }
                   7726:                                 if ($checkbystatus) {
                   7727:                                     if ($env{'environment.inststatus'}) {
                   7728:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7729:                                         foreach my $type (@inststatuses) {
                   7730:                                             if (($type ne '') &&
                   7731:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7732:                                                 $refused = '';
                   7733:                                             }
                   7734:                                         }
                   7735:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   7736:                                         $refused = '';
                   7737:                                     }
                   7738:                                 }
                   7739:                             }
                   7740:                         }
                   7741:                     }
1.1017    raeburn  7742:                 }
                   7743:                 if ($refused) {
1.947     raeburn  7744:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7745:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7746: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7747:                     return 'refused';
                   7748:                 }
1.932     raeburn  7749:             }
1.1131    raeburn  7750:         } elsif ($role eq 'au') {
                   7751:             if ($url ne '/'.$udom.'/') {
                   7752:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7753:                          ' to assign author role for '.$uname.':'.$udom.
                   7754:                          ' in domain: '.$url.' refused (wrong domain).');
                   7755:                 return 'refused';
                   7756:             }
1.104     www      7757:         }
1.21      www      7758:         $mrole=$role;
                   7759:     }
1.620     albertel 7760:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7761:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7762:     if ($end) { $command.='_'.$end; }
1.21      www      7763:     if ($start) {
                   7764: 	if ($end) { 
1.81      www      7765:            $command.='_'.$start; 
1.21      www      7766:         } else {
1.81      www      7767:            $command.='_0_'.$start;
1.21      www      7768:         }
                   7769:     }
1.739     raeburn  7770:     my $origstart = $start;
                   7771:     my $origend = $end;
1.957     raeburn  7772:     my $delflag;
1.357     www      7773: # actually delete
                   7774:     if ($deleteflag) {
1.373     www      7775: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7776: # modify command to delete the role
1.620     albertel 7777:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7778:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7779: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7780: # set start and finish to negative values for userrolelog
                   7781:            $start=-1;
                   7782:            $end=-1;
1.957     raeburn  7783:            $delflag = 1;
1.357     www      7784:         }
                   7785:     }
                   7786: # send command
1.349     www      7787:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7788: # log new user role if status is ok
1.349     www      7789:     if ($answer eq 'ok') {
1.663     raeburn  7790: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7791: # for course roles, perform group memberships changes triggered by role change.
                   7792:         unless ($role =~ /^gr/) {
                   7793:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7794:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7795:         }
1.1184    raeburn  7796:         if (($role eq 'cc') || ($role eq 'in') ||
                   7797:             ($role eq 'ep') || ($role eq 'ad') ||
                   7798:             ($role eq 'ta') || ($role eq 'st') ||
                   7799:             ($role=~/^cr/) || ($role eq 'gr') ||
                   7800:             ($role eq 'co')) {
                   7801:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7802:                            $selfenroll,$context);
                   7803:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   7804:                  ($role eq 'au') || ($role eq 'dc')) {
                   7805:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7806:                            $context);
                   7807:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   7808:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   7809:                              $context); 
                   7810:         }
1.1053    raeburn  7811:         if ($role eq 'cc') {
                   7812:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7813:         }
1.349     www      7814:     }
                   7815:     return $answer;
1.169     harris41 7816: }
                   7817: 
1.1053    raeburn  7818: sub autoupdate_coowners {
                   7819:     my ($url,$end,$start,$uname,$udom) = @_;
                   7820:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7821:     if (($cdom ne '') && ($cnum ne '')) {
                   7822:         my $now = time;
                   7823:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7824:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7825:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7826:             my $instcode = $coursehash{'internal.coursecode'};
                   7827:             if ($instcode ne '') {
1.1056    raeburn  7828:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7829:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7830:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7831:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7832:                         if ($result eq 'valid') {
                   7833:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7834:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7835:                                     push(@newcoowners,$coowner);
                   7836:                                 }
                   7837:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7838:                                     push(@newcoowners,$uname.':'.$udom);
                   7839:                                 }
                   7840:                                 @newcoowners = sort(@newcoowners);
                   7841:                             } else {
                   7842:                                 push(@newcoowners,$uname.':'.$udom);
                   7843:                             }
                   7844:                         } else {
                   7845:                             if ($coursehash{'internal.co-owners'}) {
                   7846:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7847:                                     unless ($coowner eq $uname.':'.$udom) {
                   7848:                                         push(@newcoowners,$coowner);
                   7849:                                     }
                   7850:                                 }
                   7851:                                 unless (@newcoowners > 0) {
                   7852:                                     $delcoowners = 1;
                   7853:                                     $coowners = '';
                   7854:                                 }
                   7855:                             }
                   7856:                         }
                   7857:                         if (@newcoowners || $delcoowners) {
                   7858:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7859:                                             $delcoowners,@newcoowners);
                   7860:                         }
                   7861:                     }
                   7862:                 }
                   7863:             }
                   7864:         }
                   7865:     }
                   7866: }
                   7867: 
                   7868: sub store_coowners {
                   7869:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7870:     my $cid = $cdom.'_'.$cnum;
                   7871:     my ($coowners,$delresult,$putresult);
                   7872:     if (@newcoowners) {
                   7873:         $coowners = join(',',@newcoowners);
                   7874:         my %coownershash = (
                   7875:                             'internal.co-owners' => $coowners,
                   7876:                            );
                   7877:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7878:         if ($putresult eq 'ok') {
                   7879:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7880:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7881:             }
                   7882:         }
                   7883:     }
                   7884:     if ($delcoowners) {
                   7885:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7886:         if ($delresult eq 'ok') {
                   7887:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7888:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7889:             }
                   7890:         }
                   7891:     }
                   7892:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7893:         my %crsinfo =
                   7894:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7895:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7896:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7897:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7898:         }
                   7899:     }
                   7900: }
                   7901: 
1.169     harris41 7902: # -------------------------------------------------- Modify user authentication
1.197     www      7903: # Overrides without validation
                   7904: 
1.169     harris41 7905: sub modifyuserauth {
                   7906:     my ($udom,$uname,$umode,$upass)=@_;
                   7907:     my $uhome=&homeserver($uname,$udom);
1.197     www      7908:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7909:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7910:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7911:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7912:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7913: 		     &escape($upass),$uhome);
1.620     albertel 7914:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7915:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7916:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7917:     &log($udom,,$uname,$uhome,
1.620     albertel 7918:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7919:                                      $env{'user.name'}.', '.$umode.
1.197     www      7920:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7921:     unless ($reply eq 'ok') {
1.197     www      7922:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7923: 	return 'error: '.$reply;
                   7924:     }   
1.170     harris41 7925:     return 'ok';
1.80      www      7926: }
                   7927: 
1.81      www      7928: # --------------------------------------------------------------- Modify a user
1.80      www      7929: 
1.81      www      7930: sub modifyuser {
1.206     matthew  7931:     my ($udom,    $uname, $uid,
                   7932:         $umode,   $upass, $first,
                   7933:         $middle,  $last,  $gene,
1.1058    raeburn  7934:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7935:     $udom= &LONCAPA::clean_domain($udom);
                   7936:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7937:     my $showcandelete = 'none';
                   7938:     if (ref($candelete) eq 'ARRAY') {
                   7939:         if (@{$candelete} > 0) {
                   7940:             $showcandelete = join(', ',@{$candelete});
                   7941:         }
                   7942:     }
1.81      www      7943:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7944:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7945: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7946:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7947:                                      ' desiredhome not specified'). 
1.620     albertel 7948:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7949:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7950:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7951:     my $newuser;
                   7952:     if ($uhome eq 'no_host') {
                   7953:         $newuser = 1;
                   7954:     }
1.80      www      7955: # ----------------------------------------------------------------- Create User
1.406     albertel 7956:     if (($uhome eq 'no_host') && 
                   7957: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7958:         my $unhome='';
1.844     albertel 7959:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7960:             $unhome = $desiredhome;
1.620     albertel 7961: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7962: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7963:         } else { # load balancing routine for determining $unhome
1.81      www      7964:             my $loadm=10000000;
1.841     albertel 7965: 	    my %servers = &get_servers($udom,'library');
                   7966: 	    foreach my $tryserver (keys(%servers)) {
                   7967: 		my $answer=reply('load',$tryserver);
                   7968: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7969: 		    $loadm=$answer;
                   7970: 		    $unhome=$tryserver;
                   7971: 		}
1.80      www      7972: 	    }
                   7973:         }
                   7974:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7975: 	    return 'error: unable to find a home server for '.$uname.
                   7976:                    ' in domain '.$udom;
1.80      www      7977:         }
                   7978:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7979:                          &escape($upass),$unhome);
                   7980: 	unless ($reply eq 'ok') {
                   7981:             return 'error: '.$reply;
                   7982:         }   
1.230     stredwic 7983:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7984:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7985: 	    return 'error: unable verify users home machine.';
1.80      www      7986:         }
1.209     matthew  7987:     }   # End of creation of new user
1.80      www      7988: # ---------------------------------------------------------------------- Add ID
                   7989:     if ($uid) {
                   7990:        $uid=~tr/A-Z/a-z/;
                   7991:        my %uidhash=&idrget($udom,$uname);
1.196     www      7992:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7993:          && (!$forceid)) {
1.80      www      7994: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7995: 	      return 'error: user id "'.$uid.'" does not match '.
                   7996:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7997:           }
                   7998:        } else {
                   7999: 	  &idput($udom,($uname => $uid));
                   8000:        }
                   8001:     }
                   8002: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8003:     my @tmp=&get('environment',
1.899     raeburn  8004: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8005:                     'permanentemail','inststatus'],
1.134     albertel 8006: 		   $udom,$uname);
1.1075    raeburn  8007:     my (%names,%oldnames);
1.313     matthew  8008:     if ($tmp[0] =~ m/^error:.*/) { 
                   8009:         %names=(); 
                   8010:     } else {
                   8011:         %names = @tmp;
1.1075    raeburn  8012:         %oldnames = %names;
1.313     matthew  8013:     }
1.388     www      8014: #
1.1058    raeburn  8015: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8016: # of users did not contain them), do not overwrite existing values
                   8017: # unless field is in $candelete array ref.  
                   8018: #
                   8019: 
                   8020:     my @fields = ('firstname','middlename','lastname','generation',
                   8021:                   'permanentemail','id');
                   8022:     my %newvalues;
                   8023:     if (ref($candelete) eq 'ARRAY') {
                   8024:         foreach my $field (@fields) {
                   8025:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8026:                 if ($field eq 'firstname') {
                   8027:                     $names{$field} = $first;
                   8028:                 } elsif ($field eq 'middlename') {
                   8029:                     $names{$field} = $middle;
                   8030:                 } elsif ($field eq 'lastname') {
                   8031:                     $names{$field} = $last;
                   8032:                 } elsif ($field eq 'generation') { 
                   8033:                     $names{$field} = $gene;
                   8034:                 } elsif ($field eq 'permanentemail') {
                   8035:                     $names{$field} = $email;
                   8036:                 } elsif ($field eq 'id') {
                   8037:                     $names{$field}  = $uid;
                   8038:                 }
                   8039:             }
                   8040:         }
                   8041:     }
1.388     www      8042:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8043:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8044:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8045:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8046:     if ($email) {
                   8047:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8048:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8049:     }
1.899     raeburn  8050:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8051:     if (defined($inststatus)) {
                   8052:         $names{'inststatus'} = '';
                   8053:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8054:         if (ref($usertypes) eq 'HASH') {
                   8055:             my @okstatuses; 
                   8056:             foreach my $item (split(/:/,$inststatus)) {
                   8057:                 if (defined($usertypes->{$item})) {
                   8058:                     push(@okstatuses,$item);  
                   8059:                 }
                   8060:             }
                   8061:             if (@okstatuses) {
                   8062:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8063:             }
                   8064:         }
                   8065:     }
1.1075    raeburn  8066:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8067:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8068:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8069:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8070:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8071:     } else {
                   8072:         $logmsg .= ' during self creation';
                   8073:     }
1.1075    raeburn  8074:     my $changed;
                   8075:     if ($newuser) {
                   8076:         $changed = 1;
                   8077:     } else {
                   8078:         foreach my $field (@fields) {
                   8079:             if ($names{$field} ne $oldnames{$field}) {
                   8080:                 $changed = 1;
                   8081:                 last;
                   8082:             }
                   8083:         }
                   8084:     }
                   8085:     unless ($changed) {
                   8086:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8087:         &logthis($logmsg);
                   8088:         return 'ok';
                   8089:     }
                   8090:     my $reply = &put('environment', \%names, $udom,$uname);
                   8091:     if ($reply ne 'ok') { 
                   8092:         return 'error: '.$reply;
                   8093:     }
1.1087    raeburn  8094:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8095:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8096:     }
1.1075    raeburn  8097:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8098:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8099:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8100:     &logthis($logmsg);
1.134     albertel 8101:     return 'ok';
1.80      www      8102: }
                   8103: 
1.81      www      8104: # -------------------------------------------------------------- Modify student
1.80      www      8105: 
1.81      www      8106: sub modifystudent {
                   8107:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8108:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  8109:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 8110:     if (!$cid) {
1.620     albertel 8111: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8112: 	    return 'not_in_class';
                   8113: 	}
1.80      www      8114:     }
                   8115: # --------------------------------------------------------------- Make the user
1.81      www      8116:     my $reply=&modifyuser
1.209     matthew  8117: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8118:          $desiredhome,$email,$inststatus);
1.80      www      8119:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8120:     # This will cause &modify_student_enrollment to get the uid from the
                   8121:     # students environment
                   8122:     $uid = undef if (!$forceid);
1.455     albertel 8123:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  8124: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  8125:     return $reply;
                   8126: }
                   8127: 
                   8128: sub modify_student_enrollment {
1.957     raeburn  8129:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 8130:     my ($cdom,$cnum,$chome);
                   8131:     if (!$cid) {
1.620     albertel 8132: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8133: 	    return 'not_in_class';
                   8134: 	}
1.620     albertel 8135: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8136: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8137:     } else {
                   8138: 	($cdom,$cnum)=split(/_/,$cid);
                   8139:     }
1.620     albertel 8140:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8141:     if (!$chome) {
1.457     raeburn  8142: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8143:     }
1.455     albertel 8144:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8145:     # Make sure the user exists
1.81      www      8146:     my $uhome=&homeserver($uname,$udom);
                   8147:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8148: 	return 'error: no such user';
                   8149:     }
1.297     matthew  8150:     # Get student data if we were not given enough information
                   8151:     if (!defined($first)  || $first  eq '' || 
                   8152:         !defined($last)   || $last   eq '' || 
                   8153:         !defined($uid)    || $uid    eq '' || 
                   8154:         !defined($middle) || $middle eq '' || 
                   8155:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8156:         # They did not supply us with enough data to enroll the student, so
                   8157:         # we need to pick up more information.
1.297     matthew  8158:         my %tmp = &get('environment',
1.294     matthew  8159:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8160:                        ,$udom,$uname);
                   8161: 
1.800     albertel 8162:         #foreach my $key (keys(%tmp)) {
                   8163:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8164:         #}
1.294     matthew  8165:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8166:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8167:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8168:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8169:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8170:     }
1.556     albertel 8171:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8172:     my $user = "$uname:$udom";
                   8173:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8174:     my $reply=cput('classlist',
1.1148    raeburn  8175: 		   {$user => 
1.515     raeburn  8176: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 8177: 		   $cdom,$cnum);
1.1148    raeburn  8178:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8179:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8180:     } else { 
1.81      www      8181: 	return 'error: '.$reply;
                   8182:     }
1.297     matthew  8183:     # Add student role to user
1.83      www      8184:     my $uurl='/'.$cid;
1.81      www      8185:     $uurl=~s/\_/\//g;
                   8186:     if ($usec) {
                   8187: 	$uurl.='/'.$usec;
                   8188:     }
1.1148    raeburn  8189:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8190:                              $selfenroll,$context);
                   8191:     if ($result ne 'ok') {
                   8192:         if ($old_entry{$user} ne '') {
                   8193:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8194:         } else {
                   8195:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8196:         }
                   8197:     }
                   8198:     return $result; 
1.21      www      8199: }
                   8200: 
1.556     albertel 8201: sub format_name {
                   8202:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8203:     my $name;
                   8204:     if ($first ne 'lastname') {
                   8205: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8206:     } else {
                   8207: 	if ($lastname=~/\S/) {
                   8208: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8209: 	    $name=~s/\s+,/,/;
                   8210: 	} else {
                   8211: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8212: 	}
                   8213:     }
                   8214:     $name=~s/^\s+//;
                   8215:     $name=~s/\s+$//;
                   8216:     $name=~s/\s+/ /g;
                   8217:     return $name;
                   8218: }
                   8219: 
1.84      www      8220: # ------------------------------------------------- Write to course preferences
                   8221: 
                   8222: sub writecoursepref {
                   8223:     my ($courseid,%prefs)=@_;
                   8224:     $courseid=~s/^\///;
                   8225:     $courseid=~s/\_/\//g;
                   8226:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8227:     my $chome=homeserver($cnum,$cdomain);
                   8228:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8229: 	return 'error: no such course';
                   8230:     }
                   8231:     my $cstring='';
1.800     albertel 8232:     foreach my $pref (keys(%prefs)) {
                   8233: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8234:     }
1.84      www      8235:     $cstring=~s/\&$//;
                   8236:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8237: }
                   8238: 
                   8239: # ---------------------------------------------------------- Make/modify course
                   8240: 
                   8241: sub createcourse {
1.741     raeburn  8242:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8243:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8244:     $url=&declutter($url);
                   8245:     my $cid='';
1.1028    raeburn  8246:     if ($context eq 'requestcourses') {
                   8247:         my $can_create = 0;
                   8248:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8249:         if ($udom eq $ownerdom) {
                   8250:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8251:                                   $context)) {
                   8252:                 $can_create = 1;
                   8253:             }
                   8254:         } else {
                   8255:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8256:                                            $category);
                   8257:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8258:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8259:                 if (@curr > 0) {
                   8260:                     my @options = qw(approval validate autolimit);
                   8261:                     my $optregex = join('|',@options);
                   8262:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8263:                         $can_create = 1;
                   8264:                     }
                   8265:                 }
                   8266:             }
                   8267:         }
                   8268:         if ($can_create) {
                   8269:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8270:                 unless (&allowed('ccc',$udom)) {
                   8271:                     return 'refused'; 
                   8272:                 }
1.1017    raeburn  8273:             }
                   8274:         } else {
                   8275:             return 'refused';
                   8276:         }
1.1028    raeburn  8277:     } elsif (!&allowed('ccc',$udom)) {
                   8278:         return 'refused';
1.84      www      8279:     }
1.1011    raeburn  8280: # --------------------------------------------------------------- Get Unique ID
                   8281:     my $uname;
                   8282:     if ($cnum =~ /^$match_courseid$/) {
                   8283:         my $chome=&homeserver($cnum,$udom,'true');
                   8284:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8285:             $uname = $cnum;
                   8286:         } else {
1.1038    raeburn  8287:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8288:         }
                   8289:     } else {
1.1038    raeburn  8290:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8291:     }
                   8292:     return $uname if ($uname =~ /^error/);
                   8293: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8294:     if (!defined($course_server)) {
                   8295:         if (defined(&domain($udom,'primary'))) {
                   8296:             $course_server = &domain($udom,'primary');
                   8297:         } else {
                   8298:             $course_server = $env{'user.home'}; 
                   8299:         }
                   8300:     }
                   8301:     my %host_servers =
                   8302:         &Apache::lonnet::get_servers($udom,'library');
                   8303:     unless ($host_servers{$course_server}) {
                   8304:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8305:     }
1.84      www      8306: # ------------------------------------------------------------- Make the course
                   8307:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8308:                       $course_server);
1.84      www      8309:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8310:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8311:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8312: 	return 'error: no such course';
                   8313:     }
1.271     www      8314: # ----------------------------------------------------------------- Course made
1.516     raeburn  8315: # log existence
1.1029    raeburn  8316:     my $now = time;
1.918     raeburn  8317:     my $newcourse = {
                   8318:                     $udom.'_'.$uname => {
1.921     raeburn  8319:                                      description => $description,
                   8320:                                      inst_code   => $inst_code,
                   8321:                                      owner       => $course_owner,
                   8322:                                      type        => $crstype,
1.1029    raeburn  8323:                                      creator     => $env{'user.name'}.':'.
                   8324:                                                     $env{'user.domain'},
                   8325:                                      created     => $now,
                   8326:                                      context     => $context,
1.918     raeburn  8327:                                                 },
                   8328:                     };
1.921     raeburn  8329:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8330: # set toplevel url
1.271     www      8331:     my $topurl=$url;
                   8332:     unless ($nonstandard) {
                   8333: # ------------------------------------------ For standard courses, make top url
                   8334:         my $mapurl=&clutter($url);
1.278     www      8335:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8336:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8337: <map>
                   8338: <resource id="1" type="start"></resource>
                   8339: <resource id="2" src="$mapurl"></resource>
                   8340: <resource id="3" type="finish"></resource>
                   8341: <link index="1" from="1" to="2"></link>
                   8342: <link index="2" from="2" to="3"></link>
                   8343: </map>
                   8344: ENDINITMAP
                   8345:         $topurl=&declutter(
1.638     albertel 8346:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8347:                           );
                   8348:     }
                   8349: # ----------------------------------------------------------- Write preferences
1.84      www      8350:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8351:                      ('description'              => $description,
                   8352:                       'url'                      => $topurl,
                   8353:                       'internal.creator'         => $env{'user.name'}.':'.
                   8354:                                                     $env{'user.domain'},
                   8355:                       'internal.created'         => $now,
                   8356:                       'internal.creationcontext' => $context)
                   8357:                     );
1.84      www      8358:     return '/'.$udom.'/'.$uname;
                   8359: }
                   8360: 
1.1011    raeburn  8361: # ------------------------------------------------------------------- Create ID
                   8362: sub generate_coursenum {
1.1038    raeburn  8363:     my ($udom,$crstype) = @_;
1.1011    raeburn  8364:     my $domdesc = &domain($udom);
                   8365:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8366:     my $first;
                   8367:     if ($crstype eq 'Community') {
                   8368:         $first = '0';
                   8369:     } else {
                   8370:         $first = int(1+rand(9)); 
                   8371:     } 
                   8372:     my $uname=$first.
1.1011    raeburn  8373:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8374:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8375:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8376: # ----------------------------------------------- Make sure that does not exist
                   8377:     my $uhome=&homeserver($uname,$udom,'true');
                   8378:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8379:         if ($crstype eq 'Community') {
                   8380:             $first = '0';
                   8381:         } else {
                   8382:             $first = int(1+rand(9));
                   8383:         }
                   8384:         $uname=$first.
1.1011    raeburn  8385:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8386:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8387:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8388:         $uhome=&homeserver($uname,$udom,'true');
                   8389:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8390:             return 'error: unable to generate unique course-ID';
                   8391:         }
                   8392:     }
                   8393:     return $uname;
                   8394: }
                   8395: 
1.813     albertel 8396: sub is_course {
1.1167    droeschl 8397:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8398:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8399: 
                   8400:     return unless $cdom and $cnum;
                   8401: 
                   8402:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8403:         '.');
                   8404: 
                   8405:     return unless exists($courses{$cdom.'_'.$cnum});
                   8406:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8407: }
                   8408: 
1.1015    raeburn  8409: sub store_userdata {
                   8410:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8411:     my $result;
1.1016    raeburn  8412:     if ($datakey ne '') {
1.1013    raeburn  8413:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8414:             if ($udom eq '' || $uname eq '') {
                   8415:                 $udom = $env{'user.domain'};
                   8416:                 $uname = $env{'user.name'};
                   8417:             }
                   8418:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8419:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8420:                 $result = 'error: no_host';
                   8421:             } else {
                   8422:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8423:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8424: 
                   8425:                 my $namevalue='';
                   8426:                 foreach my $key (keys(%{$storehash})) {
                   8427:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8428:                 }
                   8429:                 $namevalue=~s/\&$//;
1.1105    raeburn  8430:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8431:                                   $namevalue,$uhome);
1.1013    raeburn  8432:             }
                   8433:         } else {
                   8434:             $result = 'error: data to store was not a hash reference'; 
                   8435:         }
                   8436:     } else {
                   8437:         $result= 'error: invalid requestkey'; 
                   8438:     }
                   8439:     return $result;
                   8440: }
                   8441: 
1.21      www      8442: # ---------------------------------------------------------- Assign Custom Role
                   8443: 
                   8444: sub assigncustomrole {
1.957     raeburn  8445:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8446:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8447:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8448: }
                   8449: 
                   8450: # ----------------------------------------------------------------- Revoke Role
                   8451: 
                   8452: sub revokerole {
1.957     raeburn  8453:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8454:     my $now=time;
1.965     raeburn  8455:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8456: }
                   8457: 
                   8458: # ---------------------------------------------------------- Revoke Custom Role
                   8459: 
                   8460: sub revokecustomrole {
1.957     raeburn  8461:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8462:     my $now=time;
1.357     www      8463:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8464:            $deleteflag,$selfenroll,$context);
1.17      www      8465: }
                   8466: 
1.533     banghart 8467: # ------------------------------------------------------------ Disk usage
1.535     albertel 8468: sub diskusage {
1.955     raeburn  8469:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8470:     $directorypath =~ s/\/$//;
                   8471:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8472:                        .&escape($getpropath).':'.&escape($uname).':'
                   8473:                        .&escape($udom),homeserver($uname,$udom));
                   8474:     if ($listing eq 'unknown_cmd') {
                   8475:         if ($getpropath) {
                   8476:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8477:         }
                   8478:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8479:     }
1.514     albertel 8480:     return $listing;
1.512     banghart 8481: }
                   8482: 
1.566     banghart 8483: sub is_locked {
1.1096    raeburn  8484:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8485:     my @check;
                   8486:     my $is_locked;
1.1093    raeburn  8487:     push (@check,$file_name);
1.613     albertel 8488:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8489: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8490:     my ($tmp)=keys(%locked);
                   8491:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8492:     
1.566     banghart 8493:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8494:         $is_locked = 'false';
                   8495:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8496:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8497:                $is_locked = 'true';
1.1096    raeburn  8498:                if (ref($which) eq 'ARRAY') {
                   8499:                    push(@{$which},$entry);
                   8500:                } else {
                   8501:                    last;
                   8502:                }
1.745     raeburn  8503:            }
                   8504:        }
1.566     banghart 8505:     } else {
                   8506:         $is_locked = 'false';
                   8507:     }
1.1093    raeburn  8508:     return $is_locked;
1.566     banghart 8509: }
                   8510: 
1.759     albertel 8511: sub declutter_portfile {
                   8512:     my ($file) = @_;
1.833     albertel 8513:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8514:     return $file;
                   8515: }
                   8516: 
1.559     banghart 8517: # ------------------------------------------------------------- Mark as Read Only
                   8518: 
                   8519: sub mark_as_readonly {
                   8520:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8521:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8522:     my ($tmp)=keys(%current_permissions);
                   8523:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8524:     foreach my $file (@{$files}) {
1.759     albertel 8525: 	$file = &declutter_portfile($file);
1.561     banghart 8526:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8527:     }
1.613     albertel 8528:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8529:     return;
                   8530: }
                   8531: 
1.572     banghart 8532: # ------------------------------------------------------------Save Selected Files
                   8533: 
                   8534: sub save_selected_files {
                   8535:     my ($user, $path, @files) = @_;
                   8536:     my $filename = $user."savedfiles";
1.573     banghart 8537:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8538:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8539:     foreach my $file (@files) {
1.620     albertel 8540:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8541:     }
                   8542:     foreach my $file (@other_files) {
1.574     banghart 8543:         print (OUT $file."\n");
1.572     banghart 8544:     }
1.574     banghart 8545:     close (OUT);
1.572     banghart 8546:     return 'ok';
                   8547: }
                   8548: 
1.574     banghart 8549: sub clear_selected_files {
                   8550:     my ($user) = @_;
                   8551:     my $filename = $user."savedfiles";
1.1117    foxr     8552:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8553:     print (OUT undef);
                   8554:     close (OUT);
                   8555:     return ("ok");    
                   8556: }
                   8557: 
1.572     banghart 8558: sub files_in_path {
                   8559:     my ($user, $path) = @_;
                   8560:     my $filename = $user."savedfiles";
                   8561:     my %return_files;
1.1117    foxr     8562:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8563:     while (my $line_in = <IN>) {
1.574     banghart 8564:         chomp ($line_in);
                   8565:         my @paths_and_file = split (m!/!, $line_in);
                   8566:         my $file_part = pop (@paths_and_file);
                   8567:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8568:         $path_part.='/';
                   8569:         my $path_and_file = $path_part.$file_part;
                   8570:         if ($path_part eq $path) {
                   8571:             $return_files{$file_part}= 'selected';
                   8572:         }
                   8573:     }
1.574     banghart 8574:     close (IN);
                   8575:     return (\%return_files);
1.572     banghart 8576: }
                   8577: 
                   8578: # called in portfolio select mode, to show files selected NOT in current directory
                   8579: sub files_not_in_path {
                   8580:     my ($user, $path) = @_;
                   8581:     my $filename = $user."savedfiles";
                   8582:     my @return_files;
                   8583:     my $path_part;
1.1117    foxr     8584:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8585:     while (my $line = <IN>) {
1.572     banghart 8586:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8587:         my @paths_and_file = split(m|/|, $line);
                   8588:         my $file_part = pop(@paths_and_file);
                   8589:         chomp($file_part);
                   8590:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8591:         $path_part .= '/';
                   8592:         my $path_and_file = $path_part.$file_part;
                   8593:         if ($path_part ne $path) {
1.800     albertel 8594:             push(@return_files, ($path_and_file));
1.572     banghart 8595:         }
                   8596:     }
1.800     albertel 8597:     close(OUT);
1.574     banghart 8598:     return (@return_files);
1.572     banghart 8599: }
                   8600: 
1.745     raeburn  8601: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8602: 
1.745     raeburn  8603: sub get_portfile_permissions {
                   8604:     my ($domain,$user) = @_;
1.613     albertel 8605:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8606:     my ($tmp)=keys(%current_permissions);
                   8607:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8608:     return \%current_permissions;
                   8609: }
                   8610: 
                   8611: #---------------------------------------------Get portfolio file access controls
                   8612: 
1.749     raeburn  8613: sub get_access_controls {
1.745     raeburn  8614:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8615:     my %access;
                   8616:     my $real_file = $file;
                   8617:     $file =~ s/\.meta$//;
1.745     raeburn  8618:     if (defined($file)) {
1.749     raeburn  8619:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8620:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8621:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8622:             }
                   8623:         }
1.745     raeburn  8624:     } else {
1.749     raeburn  8625:         foreach my $key (keys(%{$current_permissions})) {
                   8626:             if ($key =~ /\0accesscontrol$/) {
                   8627:                 if (defined($group)) {
                   8628:                     if ($key !~ m-^\Q$group\E/-) {
                   8629:                         next;
                   8630:                     }
                   8631:                 }
                   8632:                 my ($fullpath) = split(/\0/,$key);
                   8633:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8634:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8635:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8636:                     }
                   8637:                 }
                   8638:             }
                   8639:         }
                   8640:     }
                   8641:     return %access;
                   8642: }
                   8643: 
                   8644: sub modify_access_controls {
                   8645:     my ($file_name,$changes,$domain,$user)=@_;
                   8646:     my ($outcome,$deloutcome);
                   8647:     my %store_permissions;
                   8648:     my %new_values;
                   8649:     my %new_control;
                   8650:     my %translation;
                   8651:     my @deletions = ();
                   8652:     my $now = time;
                   8653:     if (exists($$changes{'activate'})) {
                   8654:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8655:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8656:             my $numnew = scalar(@newitems);
                   8657:             for (my $i=0; $i<$numnew; $i++) {
                   8658:                 my $newkey = $newitems[$i];
                   8659:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8660:                 if ($newkey =~ /^\d+:/) { 
                   8661:                     $newkey =~ s/^(\d+)/$newid/;
                   8662:                     $translation{$1} = $newid;
                   8663:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8664:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8665:                     $translation{$1} = $newid;
                   8666:                 }
1.749     raeburn  8667:                 $new_values{$file_name."\0".$newkey} = 
                   8668:                                           $$changes{'activate'}{$newitems[$i]};
                   8669:                 $new_control{$newkey} = $now;
                   8670:             }
                   8671:         }
                   8672:     }
                   8673:     my %todelete;
                   8674:     my %changed_items;
                   8675:     foreach my $action ('delete','update') {
                   8676:         if (exists($$changes{$action})) {
                   8677:             if (ref($$changes{$action}) eq 'HASH') {
                   8678:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8679:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8680:                     if ($action eq 'delete') { 
                   8681:                         $todelete{$itemnum} = 1;
                   8682:                     } else {
                   8683:                         $changed_items{$itemnum} = $key;
                   8684:                     }
                   8685:                 }
1.745     raeburn  8686:             }
                   8687:         }
1.749     raeburn  8688:     }
                   8689:     # get lock on access controls for file.
                   8690:     my $lockhash = {
                   8691:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8692:                                                        ':'.$env{'user.domain'},
                   8693:                    }; 
                   8694:     my $tries = 0;
                   8695:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8696:    
                   8697:     while (($gotlock ne 'ok') && $tries <3) {
                   8698:         $tries ++;
                   8699:         sleep 1;
                   8700:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8701:     }
                   8702:     if ($gotlock eq 'ok') {
                   8703:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8704:         my ($tmp)=keys(%curr_permissions);
                   8705:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8706:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8707:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8708:             if (ref($curr_controls) eq 'HASH') {
                   8709:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8710:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8711:                     if (defined($todelete{$itemnum})) {
                   8712:                         push(@deletions,$file_name."\0".$control_item);
                   8713:                     } else {
                   8714:                         if (defined($changed_items{$itemnum})) {
                   8715:                             $new_control{$changed_items{$itemnum}} = $now;
                   8716:                             push(@deletions,$file_name."\0".$control_item);
                   8717:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8718:                         } else {
                   8719:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8720:                         }
                   8721:                     }
1.745     raeburn  8722:                 }
                   8723:             }
                   8724:         }
1.970     raeburn  8725:         my ($group);
                   8726:         if (&is_course($domain,$user)) {
                   8727:             ($group,my $file) = split(/\//,$file_name,2);
                   8728:         }
1.749     raeburn  8729:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8730:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8731:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8732:         #  remove lock
                   8733:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8734:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8735:         my $sqlresult =
1.970     raeburn  8736:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8737:                                     $group);
1.749     raeburn  8738:     } else {
                   8739:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8740:     }
1.749     raeburn  8741:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8742: }
                   8743: 
1.827     raeburn  8744: sub make_public_indefinitely {
                   8745:     my ($requrl) = @_;
                   8746:     my $now = time;
                   8747:     my $action = 'activate';
                   8748:     my $aclnum = 0;
                   8749:     if (&is_portfolio_url($requrl)) {
                   8750:         my (undef,$udom,$unum,$file_name,$group) =
                   8751:             &parse_portfolio_url($requrl);
                   8752:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8753:         my %access_controls = &get_access_controls($current_perms,
                   8754:                                                    $group,$file_name);
                   8755:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8756:             my ($num,$scope,$end,$start) = 
                   8757:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8758:             if ($scope eq 'public') {
                   8759:                 if ($start <= $now && $end == 0) {
                   8760:                     $action = 'none';
                   8761:                 } else {
                   8762:                     $action = 'update';
                   8763:                     $aclnum = $num;
                   8764:                 }
                   8765:                 last;
                   8766:             }
                   8767:         }
                   8768:         if ($action eq 'none') {
                   8769:              return 'ok';
                   8770:         } else {
                   8771:             my %changes;
                   8772:             my $newend = 0;
                   8773:             my $newstart = $now;
                   8774:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8775:             $changes{$action}{$newkey} = {
                   8776:                 type => 'public',
                   8777:                 time => {
                   8778:                     start => $newstart,
                   8779:                     end   => $newend,
                   8780:                 },
                   8781:             };
                   8782:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8783:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8784:             return $outcome;
                   8785:         }
                   8786:     } else {
                   8787:         return 'invalid';
                   8788:     }
                   8789: }
                   8790: 
1.745     raeburn  8791: #------------------------------------------------------Get Marked as Read Only
                   8792: 
                   8793: sub get_marked_as_readonly {
                   8794:     my ($domain,$user,$what,$group) = @_;
                   8795:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8796:     my @readonly_files;
1.629     banghart 8797:     my $cmp1=$what;
                   8798:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8799:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8800:         if (defined($group)) {
                   8801:             if ($file_name !~ m-^\Q$group\E/-) {
                   8802:                 next;
                   8803:             }
                   8804:         }
1.561     banghart 8805:         if (ref($value) eq "ARRAY"){
                   8806:             foreach my $stored_what (@{$value}) {
1.629     banghart 8807:                 my $cmp2=$stored_what;
1.759     albertel 8808:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8809:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8810:                 }
1.629     banghart 8811:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8812:                     push(@readonly_files, $file_name);
1.745     raeburn  8813:                     last;
1.563     banghart 8814:                 } elsif (!defined($what)) {
                   8815:                     push(@readonly_files, $file_name);
1.745     raeburn  8816:                     last;
1.561     banghart 8817:                 }
                   8818:             }
1.745     raeburn  8819:         }
1.561     banghart 8820:     }
                   8821:     return @readonly_files;
                   8822: }
1.577     banghart 8823: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8824: 
1.577     banghart 8825: sub get_marked_as_readonly_hash {
1.745     raeburn  8826:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8827:     my %readonly_files;
1.745     raeburn  8828:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8829:         if (defined($group)) {
                   8830:             if ($file_name !~ m-^\Q$group\E/-) {
                   8831:                 next;
                   8832:             }
                   8833:         }
1.577     banghart 8834:         if (ref($value) eq "ARRAY"){
                   8835:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8836:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8837:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8838:                         if ($lock_descriptor eq 'graded') {
                   8839:                             $readonly_files{$file_name} = 'graded';
                   8840:                         } elsif ($lock_descriptor eq 'handback') {
                   8841:                             $readonly_files{$file_name} = 'handback';
                   8842:                         } else {
                   8843:                             if (!exists($readonly_files{$file_name})) {
                   8844:                                 $readonly_files{$file_name} = 'locked';
                   8845:                             }
                   8846:                         }
1.745     raeburn  8847:                     }
1.750     banghart 8848:                 } 
1.577     banghart 8849:             }
                   8850:         } 
                   8851:     }
                   8852:     return %readonly_files;
                   8853: }
1.559     banghart 8854: # ------------------------------------------------------------ Unmark as Read Only
                   8855: 
                   8856: sub unmark_as_readonly {
1.629     banghart 8857:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8858:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8859:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8860:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8861:     my $symb_crs = $what;
                   8862:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8863:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8864:     my ($tmp)=keys(%current_permissions);
                   8865:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8866:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8867:     foreach my $file (@readonly_files) {
1.759     albertel 8868: 	my $clean_file = &declutter_portfile($file);
                   8869: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8870: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8871:         my @new_locks;
                   8872:         my @del_keys;
                   8873:         if (ref($current_locks) eq "ARRAY"){
                   8874:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8875:                 my $compare=$locker;
1.749     raeburn  8876:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8877:                     $compare=join('',@{$locker});
1.746     raeburn  8878:                     if ($compare ne $symb_crs) {
                   8879:                         push(@new_locks, $locker);
                   8880:                     }
1.563     banghart 8881:                 }
                   8882:             }
1.650     albertel 8883:             if (scalar(@new_locks) > 0) {
1.563     banghart 8884:                 $current_permissions{$file} = \@new_locks;
                   8885:             } else {
                   8886:                 push(@del_keys, $file);
1.613     albertel 8887:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8888:                 delete($current_permissions{$file});
1.563     banghart 8889:             }
                   8890:         }
1.561     banghart 8891:     }
1.613     albertel 8892:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8893:     return;
                   8894: }
1.512     banghart 8895: 
1.17      www      8896: # ------------------------------------------------------------ Directory lister
                   8897: 
                   8898: sub dirlist {
1.955     raeburn  8899:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8900:     $uri=~s/^\///;
                   8901:     $uri=~s/\/$//;
1.253     stredwic 8902:     my ($udom, $uname);
1.955     raeburn  8903:     if ($getuserdir) {
1.253     stredwic 8904:         $udom = $userdomain;
                   8905:         $uname = $username;
1.955     raeburn  8906:     } else {
                   8907:         (undef,$udom,$uname)=split(/\//,$uri);
                   8908:         if(defined($userdomain)) {
                   8909:             $udom = $userdomain;
                   8910:         }
                   8911:         if(defined($username)) {
                   8912:             $uname = $username;
                   8913:         }
1.253     stredwic 8914:     }
1.955     raeburn  8915:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8916: 
1.955     raeburn  8917:     $dirRoot = $perlvar{'lonDocRoot'};
                   8918:     if (defined($getpropath)) {
                   8919:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8920:         $dirRoot =~ s/\/$//;
1.955     raeburn  8921:     } elsif (defined($getuserdir)) {
                   8922:         my $subdir=$uname.'__';
                   8923:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8924:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8925:                    ."/$udom/$subdir/$uname";
                   8926:     } elsif (defined($alternateRoot)) {
                   8927:         $dirRoot = $alternateRoot;
1.751     banghart 8928:     }
1.253     stredwic 8929: 
                   8930:     if($udom) {
                   8931:         if($uname) {
1.1135    raeburn  8932:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8933:             if ($uhome eq 'no_host') {
                   8934:                 return ([],'no_host');
                   8935:             }
1.955     raeburn  8936:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8937:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8938:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8939:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8940:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8941:             } else {
                   8942:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8943:             }
1.605     matthew  8944:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8945:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8946:                 @listing_results = split(/:/,$listing);
                   8947:             } else {
                   8948:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8949:             }
1.1135    raeburn  8950:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8951:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8952:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8953:                 return ([],$listing);
                   8954:             } else {
                   8955:                 return (\@listing_results);
1.1135    raeburn  8956:             }
1.955     raeburn  8957:         } elsif(!$alternateRoot) {
1.1136    raeburn  8958:             my (%allusers,%listerror);
1.841     albertel 8959: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8960:  	    foreach my $tryserver (keys(%servers)) {
                   8961:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8962:                                   &escape($udom),$tryserver);
                   8963:                 if ($listing eq 'unknown_cmd') {
                   8964: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8965: 				      $udom, $tryserver);
                   8966:                 } else {
                   8967:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8968:                 }
1.841     albertel 8969: 		if ($listing eq 'unknown_cmd') {
                   8970: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8971: 				      $udom, $tryserver);
                   8972: 		    @listing_results = split(/:/,$listing);
                   8973: 		} else {
                   8974: 		    @listing_results =
                   8975: 			map { &unescape($_); } split(/:/,$listing);
                   8976: 		}
1.1136    raeburn  8977:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8978:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8979:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8980:                     $listerror{$tryserver} = $listing;
                   8981:                 } else {
1.841     albertel 8982: 		    foreach my $line (@listing_results) {
                   8983: 			my ($entry) = split(/&/,$line,2);
                   8984: 			$allusers{$entry} = 1;
                   8985: 		    }
                   8986: 		}
1.253     stredwic 8987:             }
1.1136    raeburn  8988:             my @alluserslist=();
1.800     albertel 8989:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8990:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8991:             }
1.1136    raeburn  8992:             return (\@alluserslist);
1.253     stredwic 8993:         } else {
1.1136    raeburn  8994:             return ([],'missing username');
1.253     stredwic 8995:         }
1.955     raeburn  8996:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8997:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8998:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8999:         return (\@all_domains);
1.955     raeburn  9000:     } else {
1.1136    raeburn  9001:         return ([],'missing domain');
1.275     stredwic 9002:     }
                   9003: }
                   9004: 
                   9005: # --------------------------------------------- GetFileTimestamp
                   9006: # This function utilizes dirlist and returns the date stamp for
                   9007: # when it was last modified.  It will also return an error of -1
                   9008: # if an error occurs
                   9009: 
                   9010: sub GetFileTimestamp {
1.955     raeburn  9011:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9012:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9013:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9014:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9015:                                     undef,$getuserdir);
                   9016:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9017:         return -1;
                   9018:     }
                   9019:     if (ref($fileref) eq 'ARRAY') {
                   9020:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9021:         # @stats contains first the filename, then the stat output
                   9022:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9023:     } else {
                   9024:         return -1;
1.253     stredwic 9025:     }
1.26      www      9026: }
                   9027: 
1.712     albertel 9028: sub stat_file {
                   9029:     my ($uri) = @_;
1.787     albertel 9030:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9031: 
1.955     raeburn  9032:     my ($udom,$uname,$file);
1.712     albertel 9033:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9034: 	($udom,$uname,$file) =
1.811     albertel 9035: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9036: 	$file = 'userfiles/'.$file;
                   9037:     }
                   9038:     if ($uri =~ m-^/res/-) {
                   9039: 	($udom,$uname) = 
1.807     albertel 9040: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9041: 	$file = $uri;
                   9042:     }
                   9043: 
                   9044:     if (!$udom || !$uname || !$file) {
                   9045: 	# unable to handle the uri
                   9046: 	return ();
                   9047:     }
1.956     raeburn  9048:     my $getpropath;
                   9049:     if ($file =~ /^userfiles\//) {
                   9050:         $getpropath = 1;
                   9051:     }
1.1136    raeburn  9052:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9053:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9054:         return ();
                   9055:     } else {
                   9056:         if (ref($listref) eq 'ARRAY') {
                   9057:             my @stats = split('&',$listref->[0]);
                   9058: 	    shift(@stats); #filename is first
                   9059: 	    return @stats;
                   9060:         }
1.712     albertel 9061:     }
                   9062:     return ();
                   9063: }
                   9064: 
1.26      www      9065: # -------------------------------------------------------- Value of a Condition
                   9066: 
1.713     albertel 9067: # gets the value of a specific preevaluated condition
                   9068: #    stored in the string  $env{user.state.<cid>}
                   9069: # or looks up a condition reference in the bighash and if if hasn't
                   9070: # already been evaluated recurses into docondval to get the value of
                   9071: # the condition, then memoizing it to 
                   9072: #   $env{user.state.<cid>.<condition>}
1.40      www      9073: sub directcondval {
                   9074:     my $number=shift;
1.620     albertel 9075:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9076: 	&Apache::lonuserstate::evalstate();
                   9077:     }
1.713     albertel 9078:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9079: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9080:     } elsif ($number =~ /^_/) {
                   9081: 	my $sub_condition;
                   9082: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9083: 		&GDBM_READER(),0640)) {
                   9084: 	    $sub_condition=$bighash{'conditions'.$number};
                   9085: 	    untie(%bighash);
                   9086: 	}
                   9087: 	my $value = &docondval($sub_condition);
1.949     raeburn  9088: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9089: 	return $value;
                   9090:     }
1.620     albertel 9091:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9092:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9093:     } else {
                   9094:        return 2;
                   9095:     }
                   9096: }
                   9097: 
1.713     albertel 9098: # get the collection of conditions for this resource
1.26      www      9099: sub condval {
                   9100:     my $condidx=shift;
1.54      www      9101:     my $allpathcond='';
1.713     albertel 9102:     foreach my $cond (split(/\|/,$condidx)) {
                   9103: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9104: 	    $allpathcond.=
                   9105: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9106: 	}
1.191     harris41 9107:     }
1.54      www      9108:     $allpathcond=~s/\|$//;
1.713     albertel 9109:     return &docondval($allpathcond);
                   9110: }
                   9111: 
                   9112: #evaluates an expression of conditions
                   9113: sub docondval {
                   9114:     my ($allpathcond) = @_;
                   9115:     my $result=0;
                   9116:     if ($env{'request.course.id'}
                   9117: 	&& defined($allpathcond)) {
                   9118: 	my $operand='|';
                   9119: 	my @stack;
                   9120: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9121: 	    if ($chunk eq '(') {
                   9122: 		push @stack,($operand,$result);
                   9123: 	    } elsif ($chunk eq ')') {
                   9124: 		my $before=pop @stack;
                   9125: 		if (pop @stack eq '&') {
                   9126: 		    $result=$result>$before?$before:$result;
                   9127: 		} else {
                   9128: 		    $result=$result>$before?$result:$before;
                   9129: 		}
                   9130: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9131: 		$operand=$chunk;
                   9132: 	    } else {
                   9133: 		my $new=directcondval($chunk);
                   9134: 		if ($operand eq '&') {
                   9135: 		    $result=$result>$new?$new:$result;
                   9136: 		} else {
                   9137: 		    $result=$result>$new?$result:$new;
                   9138: 		}
                   9139: 	    }
                   9140: 	}
1.26      www      9141:     }
                   9142:     return $result;
1.421     albertel 9143: }
                   9144: 
                   9145: # ---------------------------------------------------- Devalidate courseresdata
                   9146: 
                   9147: sub devalidatecourseresdata {
                   9148:     my ($coursenum,$coursedomain)=@_;
                   9149:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9150:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9151: }
                   9152: 
1.763     www      9153: 
1.200     www      9154: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9155: #
                   9156: #  Parameters:
                   9157: #      $coursenum    - Number of the course.
                   9158: #      $coursedomain - Domain at which the course was created.
                   9159: #  Returns:
                   9160: #     A hash of the course parameters along (I think) with timestamps
                   9161: #     and version info.
1.877     foxr     9162: 
1.624     albertel 9163: sub get_courseresdata {
                   9164:     my ($coursenum,$coursedomain)=@_;
1.200     www      9165:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9166:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9167:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9168:     my %dumpreply;
1.417     albertel 9169:     unless (defined($cached)) {
1.624     albertel 9170: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9171: 	$result=\%dumpreply;
1.251     albertel 9172: 	my ($tmp) = keys(%dumpreply);
                   9173: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9174: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9175: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9176: 	    return $tmp;
1.416     albertel 9177: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9178: 	    $result=undef;
1.599     albertel 9179: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9180: 	}
                   9181:     }
1.624     albertel 9182:     return $result;
                   9183: }
                   9184: 
1.633     albertel 9185: sub devalidateuserresdata {
                   9186:     my ($uname,$udom)=@_;
                   9187:     my $hashid="$udom:$uname";
                   9188:     &devalidate_cache_new('userres',$hashid);
                   9189: }
                   9190: 
1.624     albertel 9191: sub get_userresdata {
                   9192:     my ($uname,$udom)=@_;
                   9193:     #most student don\'t have any data set, check if there is some data
                   9194:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9195: 
                   9196:     my $hashid="$udom:$uname";
                   9197:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9198:     if (!defined($cached)) {
                   9199: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9200: 	$result=\%resourcedata;
                   9201: 	&do_cache_new('userres',$hashid,$result,600);
                   9202:     }
                   9203:     my ($tmp)=keys(%$result);
                   9204:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9205: 	return $result;
                   9206:     }
                   9207:     #error 2 occurs when the .db doesn't exist
                   9208:     if ($tmp!~/error: 2 /) {
1.672     albertel 9209: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9210: 		 " Trying to get resource data for ".
                   9211: 		 $uname." at ".$udom.": ".
                   9212: 		 $tmp."</font>");
                   9213:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9214: 	#&EXT_cache_set($udom,$uname);
                   9215: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9216: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9217:     }
                   9218:     return $tmp;
                   9219: }
1.879     foxr     9220: #----------------------------------------------- resdata - return resource data
                   9221: #  Purpose:
                   9222: #    Return resource data for either users or for a course.
                   9223: #  Parameters:
                   9224: #     $name      - Course/user name.
                   9225: #     $domain    - Name of the domain the user/course is registered on.
                   9226: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9227: #     @which     - Array of names of resources desired.
                   9228: #  Returns:
                   9229: #     The value of the first reasource in @which that is found in the
                   9230: #     resource hash.
                   9231: #  Exceptional Conditions:
                   9232: #     If the $type passed in is not valid (not the string 'course' or 
                   9233: #     'user', an undefined  reference is returned.
                   9234: #     If none of the resources are found, an undef is returned
1.624     albertel 9235: sub resdata {
                   9236:     my ($name,$domain,$type,@which)=@_;
                   9237:     my $result;
                   9238:     if ($type eq 'course') {
                   9239: 	$result=&get_courseresdata($name,$domain);
                   9240:     } elsif ($type eq 'user') {
                   9241: 	$result=&get_userresdata($name,$domain);
                   9242:     }
                   9243:     if (!ref($result)) { return $result; }    
1.251     albertel 9244:     foreach my $item (@which) {
1.927     albertel 9245: 	if (defined($result->{$item->[0]})) {
                   9246: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9247: 	}
1.250     albertel 9248:     }
1.291     albertel 9249:     return undef;
1.200     www      9250: }
                   9251: 
1.379     matthew  9252: #
                   9253: # EXT resource caching routines
                   9254: #
                   9255: 
                   9256: sub clear_EXT_cache_status {
1.383     albertel 9257:     &delenv('cache.EXT.');
1.379     matthew  9258: }
                   9259: 
                   9260: sub EXT_cache_status {
                   9261:     my ($target_domain,$target_user) = @_;
1.383     albertel 9262:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9263:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9264:         # We know already the user has no data
                   9265:         return 1;
                   9266:     } else {
                   9267:         return 0;
                   9268:     }
                   9269: }
                   9270: 
                   9271: sub EXT_cache_set {
                   9272:     my ($target_domain,$target_user) = @_;
1.383     albertel 9273:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9274:     #&appenv({$cachename => time});
1.379     matthew  9275: }
                   9276: 
1.28      www      9277: # --------------------------------------------------------- Value of a Variable
1.58      www      9278: sub EXT {
1.715     albertel 9279: 
1.395     albertel 9280:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9281:     unless ($varname) { return ''; }
1.218     albertel 9282:     #get real user name/domain, courseid and symb
                   9283:     my $courseid;
1.359     albertel 9284:     my $publicuser;
1.427     www      9285:     if ($symbparm) {
                   9286: 	$symbparm=&get_symb_from_alias($symbparm);
                   9287:     }
1.218     albertel 9288:     if (!($uname && $udom)) {
1.790     albertel 9289:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9290:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9291:     } else {
1.620     albertel 9292: 	$courseid=$env{'request.course.id'};
1.218     albertel 9293:     }
1.48      www      9294:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9295:     my $rest;
1.320     albertel 9296:     if (defined($therest[0])) {
1.48      www      9297:        $rest=join('.',@therest);
                   9298:     } else {
                   9299:        $rest='';
                   9300:     }
1.320     albertel 9301: 
1.57      www      9302:     my $qualifierrest=$qualifier;
                   9303:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9304:     my $spacequalifierrest=$space;
                   9305:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9306:     if ($realm eq 'user') {
1.48      www      9307: # --------------------------------------------------------------- user.resource
                   9308: 	if ($space eq 'resource') {
1.651     albertel 9309: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9310: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9311: 		 &&
1.744     albertel 9312: 		 ($symbparm eq &symbread()) ) {	
                   9313: 		# if we are in the middle of processing the resource the
                   9314: 		# get the value we are planning on committing
                   9315:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9316:                     return $Apache::lonhomework::results{$qualifierrest};
                   9317:                 } else {
                   9318:                     return $Apache::lonhomework::history{$qualifierrest};
                   9319:                 }
1.335     albertel 9320: 	    } else {
1.359     albertel 9321: 		my %restored;
1.620     albertel 9322: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9323: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9324: 		} else {
                   9325: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9326: 		}
1.335     albertel 9327: 		return $restored{$qualifierrest};
                   9328: 	    }
1.48      www      9329: # ----------------------------------------------------------------- user.access
                   9330:         } elsif ($space eq 'access') {
1.218     albertel 9331: 	    # FIXME - not supporting calls for a specific user
1.48      www      9332:             return &allowed($qualifier,$rest);
                   9333: # ------------------------------------------ user.preferences, user.environment
                   9334:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9335: 	    if (($uname eq $env{'user.name'}) &&
                   9336: 		($udom eq $env{'user.domain'})) {
                   9337: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9338: 	    } else {
1.359     albertel 9339: 		my %returnhash;
                   9340: 		if (!$publicuser) {
                   9341: 		    %returnhash=&userenvironment($udom,$uname,
                   9342: 						 $qualifierrest);
                   9343: 		}
1.218     albertel 9344: 		return $returnhash{$qualifierrest};
                   9345: 	    }
1.48      www      9346: # ----------------------------------------------------------------- user.course
                   9347:         } elsif ($space eq 'course') {
1.218     albertel 9348: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9349:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9350: # ------------------------------------------------------------------- user.role
                   9351:         } elsif ($space eq 'role') {
1.218     albertel 9352: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9353:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9354:             if ($qualifier eq 'value') {
                   9355: 		return $role;
                   9356:             } elsif ($qualifier eq 'extent') {
                   9357:                 return $where;
                   9358:             }
                   9359: # ----------------------------------------------------------------- user.domain
                   9360:         } elsif ($space eq 'domain') {
1.218     albertel 9361:             return $udom;
1.48      www      9362: # ------------------------------------------------------------------- user.name
                   9363:         } elsif ($space eq 'name') {
1.218     albertel 9364:             return $uname;
1.48      www      9365: # ---------------------------------------------------- Any other user namespace
1.29      www      9366:         } else {
1.359     albertel 9367: 	    my %reply;
                   9368: 	    if (!$publicuser) {
                   9369: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9370: 	    }
                   9371: 	    return $reply{$qualifierrest};
1.48      www      9372:         }
1.236     www      9373:     } elsif ($realm eq 'query') {
                   9374: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9375:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9376: 						[$spacequalifierrest]);
1.620     albertel 9377: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9378:    } elsif ($realm eq 'request') {
1.48      www      9379: # ------------------------------------------------------------- request.browser
                   9380:         if ($space eq 'browser') {
1.1145    bisitz   9381:             return $env{'browser.'.$qualifier};
1.57      www      9382: # ------------------------------------------------------------ request.filename
                   9383:         } else {
1.620     albertel 9384:             return $env{'request.'.$spacequalifierrest};
1.29      www      9385:         }
1.28      www      9386:     } elsif ($realm eq 'course') {
1.48      www      9387: # ---------------------------------------------------------- course.description
1.620     albertel 9388:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9389:     } elsif ($realm eq 'resource') {
1.165     www      9390: 
1.620     albertel 9391: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9392: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9393: 	}
1.693     albertel 9394: 
                   9395: 	if ($space eq 'title') {
                   9396: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9397: 	    return &gettitle($symbparm);
                   9398: 	}
                   9399: 	
                   9400: 	if ($space eq 'map') {
                   9401: 	    my ($map) = &decode_symb($symbparm);
                   9402: 	    return &symbread($map);
                   9403: 	}
1.905     albertel 9404: 	if ($space eq 'filename') {
                   9405: 	    if ($symbparm) {
                   9406: 		return &clutter((&decode_symb($symbparm))[2]);
                   9407: 	    }
                   9408: 	    return &hreflocation('',$env{'request.filename'});
                   9409: 	}
1.693     albertel 9410: 
                   9411: 	my ($section, $group, @groups);
1.593     albertel 9412: 	my ($courselevelm,$courselevel);
1.539     albertel 9413: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9414: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9415: 
1.218     albertel 9416: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9417: 
1.60      www      9418: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9419: 	    my $symbp=$symbparm;
1.735     albertel 9420: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9421: 
                   9422: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9423: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9424: 
1.620     albertel 9425: 	    if (($env{'user.name'} eq $uname) &&
                   9426: 		($env{'user.domain'} eq $udom)) {
                   9427: 		$section=$env{'request.course.sec'};
1.733     raeburn  9428:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9429:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9430: 	    } else {
1.539     albertel 9431: 		if (! defined($usection)) {
1.551     albertel 9432: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9433: 		} else {
                   9434: 		    $section = $usection;
                   9435: 		}
1.733     raeburn  9436:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9437: 	    }
                   9438: 
                   9439: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9440: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9441: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9442: 
1.593     albertel 9443: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9444: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9445: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9446: 
1.60      www      9447: # ----------------------------------------------------------- first, check user
1.624     albertel 9448: 
                   9449: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9450: 				       ([$courselevelr,'resource'],
                   9451: 					[$courselevelm,'map'     ],
                   9452: 					[$courselevel, 'course'  ]));
1.931     albertel 9453: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9454: 
1.594     albertel 9455: # ------------------------------------------------ second, check some of course
1.684     raeburn  9456:             my $coursereply;
1.691     raeburn  9457:             if (@groups > 0) {
                   9458:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9459:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9460:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9461:             }
1.96      www      9462: 
1.684     raeburn  9463: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9464: 				  $env{'course.'.$courseid.'.domain'},
                   9465: 				  'course',
                   9466: 				  ([$seclevelr,   'resource'],
                   9467: 				   [$seclevelm,   'map'     ],
                   9468: 				   [$seclevel,    'course'  ],
                   9469: 				   [$courselevelr,'resource']));
                   9470: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9471: 
1.60      www      9472: # ------------------------------------------------------ third, check map parms
1.218     albertel 9473: 	    my %parmhash=();
                   9474: 	    my $thisparm='';
                   9475: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9476: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9477: 		    &GDBM_READER(),0640)) {
1.218     albertel 9478: 		$thisparm=$parmhash{$symbparm};
                   9479: 		untie(%parmhash);
                   9480: 	    }
1.927     albertel 9481: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9482: 	}
1.594     albertel 9483: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9484: 
1.218     albertel 9485: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9486: 	my $filename;
                   9487: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9488: 	if ($symbparm) {
1.409     www      9489: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9490: 	} else {
1.620     albertel 9491: 	    $filename=$env{'request.filename'};
1.282     albertel 9492: 	}
                   9493: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9494: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9495: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9496: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9497: 
1.927     albertel 9498: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9499: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9500: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9501: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9502: 				     $env{'course.'.$courseid.'.domain'},
                   9503: 				     'course',
1.927     albertel 9504: 				     ([$courselevelm,'map'   ],
                   9505: 				      [$courselevel, 'course']));
                   9506: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9507: 	}
1.145     www      9508: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9509: 	unless ($space eq '0') {
1.336     albertel 9510: 	    my @parts=split(/_/,$space);
                   9511: 	    my $id=pop(@parts);
                   9512: 	    my $part=join('_',@parts);
                   9513: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9514: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9515: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9516: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9517: 	}
1.395     albertel 9518: 	if ($recurse) { return undef; }
                   9519: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9520: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9521: # ---------------------------------------------------- Any other user namespace
                   9522:     } elsif ($realm eq 'environment') {
                   9523: # ----------------------------------------------------------------- environment
1.620     albertel 9524: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9525: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9526: 	} else {
1.770     albertel 9527: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9528: 		return '';
                   9529: 	    }
1.219     albertel 9530: 	    my %returnhash=&userenvironment($udom,$uname,
                   9531: 					    $spacequalifierrest);
                   9532: 	    return $returnhash{$spacequalifierrest};
                   9533: 	}
1.28      www      9534:     } elsif ($realm eq 'system') {
1.48      www      9535: # ----------------------------------------------------------------- system.time
                   9536: 	if ($space eq 'time') {
                   9537: 	    return time;
                   9538:         }
1.696     albertel 9539:     } elsif ($realm eq 'server') {
                   9540: # ----------------------------------------------------------------- system.time
                   9541: 	if ($space eq 'name') {
                   9542: 	    return $ENV{'SERVER_NAME'};
                   9543:         }
1.28      www      9544:     }
1.48      www      9545:     return '';
1.61      www      9546: }
                   9547: 
1.927     albertel 9548: sub get_reply {
                   9549:     my ($reply_value) = @_;
1.940     raeburn  9550:     if (ref($reply_value) eq 'ARRAY') {
                   9551:         if (wantarray) {
                   9552: 	    return @$reply_value;
                   9553:         }
                   9554:         return $reply_value->[0];
                   9555:     } else {
                   9556:         return $reply_value;
1.927     albertel 9557:     }
                   9558: }
                   9559: 
1.691     raeburn  9560: sub check_group_parms {
                   9561:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9562:     my @groupitems = ();
                   9563:     my $resultitem;
1.927     albertel 9564:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9565:     foreach my $group (@{$groups}) {
                   9566:         foreach my $level (@levels) {
1.927     albertel 9567:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9568:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9569:         }
                   9570:     }
                   9571:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9572:                             $env{'course.'.$courseid.'.domain'},
                   9573:                                      'course',@groupitems);
                   9574:     return $coursereply;
                   9575: }
                   9576: 
                   9577: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9578:     my ($courseid,@groups) = @_;
                   9579:     @groups = sort(@groups);
1.691     raeburn  9580:     return @groups;
                   9581: }
                   9582: 
1.395     albertel 9583: sub packages_tab_default {
                   9584:     my ($uri,$varname)=@_;
                   9585:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9586: 
                   9587:     my (@extension,@specifics,$do_default);
                   9588:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9589: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9590: 	if ($pack_type eq 'default') {
                   9591: 	    $do_default=1;
                   9592: 	} elsif ($pack_type eq 'extension') {
                   9593: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9594: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9595: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9596: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9597: 	}
                   9598:     }
                   9599:     # first look for a package that matches the requested part id
                   9600:     foreach my $package (@specifics) {
                   9601: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9602: 	next if ($pack_part ne $part);
                   9603: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9604: 	    return $packagetab{"$pack_type&$name&default"};
                   9605: 	}
                   9606:     }
                   9607:     # look for any possible matching non extension_ package
                   9608:     foreach my $package (@specifics) {
                   9609: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9610: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9611: 	    return $packagetab{"$pack_type&$name&default"};
                   9612: 	}
1.585     albertel 9613: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9614: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9615: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9616: 	}
                   9617:     }
1.738     albertel 9618:     # look for any posible extension_ match
                   9619:     foreach my $package (@extension) {
                   9620: 	my ($package,$pack_type)=@{$package};
                   9621: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9622: 	    return $packagetab{"$pack_type&$name&default"};
                   9623: 	}
                   9624: 	if (defined($packagetab{$package."&$name&default"})) {
                   9625: 	    return $packagetab{$package."&$name&default"};
                   9626: 	}
                   9627:     }
                   9628:     # look for a global default setting
                   9629:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9630: 	return $packagetab{"default&$name&default"};
                   9631:     }
1.395     albertel 9632:     return undef;
                   9633: }
                   9634: 
1.334     albertel 9635: sub add_prefix_and_part {
                   9636:     my ($prefix,$part)=@_;
                   9637:     my $keyroot;
                   9638:     if (defined($prefix) && $prefix !~ /^__/) {
                   9639: 	# prefix that has a part already
                   9640: 	$keyroot=$prefix;
                   9641:     } elsif (defined($prefix)) {
                   9642: 	# prefix that is missing a part
                   9643: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9644:     } else {
                   9645: 	# no prefix at all
                   9646: 	if (defined($part)) { $keyroot='_'.$part; }
                   9647:     }
                   9648:     return $keyroot;
                   9649: }
                   9650: 
1.71      www      9651: # ---------------------------------------------------------------- Get metadata
                   9652: 
1.599     albertel 9653: my %metaentry;
1.1070    www      9654: my %importedpartids;
1.71      www      9655: sub metadata {
1.176     www      9656:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9657:     $uri=&declutter($uri);
1.288     albertel 9658:     # if it is a non metadata possible uri return quickly
1.529     albertel 9659:     if (($uri eq '') || 
                   9660: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9661: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9662:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9663: 	return undef;
                   9664:     }
1.1140    www      9665:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9666: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9667: 	return undef;
1.288     albertel 9668:     }
1.73      www      9669:     my $filename=$uri;
                   9670:     $uri=~s/\.meta$//;
1.172     www      9671: #
                   9672: # Is the metadata already cached?
1.177     www      9673: # Look at timestamp of caching
1.172     www      9674: # Everything is cached by the main uri, libraries are never directly cached
                   9675: #
1.428     albertel 9676:     if (!defined($liburi)) {
1.599     albertel 9677: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9678: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9679:     }
                   9680:     {
1.1069    www      9681: # Imported parts would go here
1.1070    www      9682:         my %importedids=();
                   9683:         my @origfileimportpartids=();
1.1069    www      9684:         my $importedparts=0;
1.172     www      9685: #
                   9686: # Is this a recursive call for a library?
                   9687: #
1.599     albertel 9688: #	if (! exists($metacache{$uri})) {
                   9689: #	    $metacache{$uri}={};
                   9690: #	}
1.924     albertel 9691: 	my $cachetime = 60*60;
1.171     www      9692:         if ($liburi) {
                   9693: 	    $liburi=&declutter($liburi);
                   9694:             $filename=$liburi;
1.401     bowersj2 9695:         } else {
1.599     albertel 9696: 	    &devalidate_cache_new('meta',$uri);
                   9697: 	    undef(%metaentry);
1.401     bowersj2 9698: 	}
1.140     www      9699:         my %metathesekeys=();
1.73      www      9700:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9701: 	my $metastring;
1.1140    www      9702: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9703: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9704: 	    $metastring = 
1.929     albertel 9705: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9706: 					  ('grade_target' => 'meta'));
                   9707: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9708: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9709:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9710: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9711: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9712: 	    $metastring=&getfile($file);
1.489     albertel 9713: 	}
1.208     albertel 9714:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9715:         my $token;
1.140     www      9716:         undef %metathesekeys;
1.71      www      9717:         while ($token=$parser->get_token) {
1.339     albertel 9718: 	    if ($token->[0] eq 'S') {
                   9719: 		if (defined($token->[2]->{'package'})) {
1.172     www      9720: #
                   9721: # This is a package - get package info
                   9722: #
1.339     albertel 9723: 		    my $package=$token->[2]->{'package'};
                   9724: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9725: 		    if (defined($token->[2]->{'id'})) { 
                   9726: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9727: 		    }
1.599     albertel 9728: 		    if ($metaentry{':packages'}) {
                   9729: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9730: 		    } else {
1.599     albertel 9731: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9732: 		    }
1.736     albertel 9733: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9734: 			my $part=$keyroot;
                   9735: 			$part=~s/^\_//;
1.736     albertel 9736: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9737: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9738: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9739: 			    # ignore package.tab specified default values
                   9740:                             # here &package_tab_default() will fetch those
                   9741: 			    if ($subp eq 'default') { next; }
1.736     albertel 9742: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9743: 			    my $unikey;
                   9744: 			    if ($pack =~ /_0$/) {
                   9745: 				$unikey='parameter_0_'.$name;
                   9746: 				$part=0;
                   9747: 			    } else {
                   9748: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9749: 			    }
1.339     albertel 9750: 			    if ($subp eq 'display') {
                   9751: 				$value.=' [Part: '.$part.']';
                   9752: 			    }
1.599     albertel 9753: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9754: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9755: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9756: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9757: 			    }
1.599     albertel 9758: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9759: 				$metaentry{':'.$unikey}=
                   9760: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9761: 			    }
1.339     albertel 9762: 			}
                   9763: 		    }
                   9764: 		} else {
1.172     www      9765: #
                   9766: # This is not a package - some other kind of start tag
1.339     albertel 9767: #
                   9768: 		    my $entry=$token->[1];
1.1068    www      9769: 		    my $unikey='';
1.175     www      9770: 
1.339     albertel 9771: 		    if ($entry eq 'import') {
1.175     www      9772: #
                   9773: # Importing a library here
1.339     albertel 9774: #
1.1067    www      9775:                         my $location=$parser->get_text('/import');
                   9776:                         my $dir=$filename;
                   9777:                         $dir=~s|[^/]*$||;
                   9778:                         $location=&filelocation($dir,$location);
1.1069    www      9779:                        
1.1068    www      9780:                         my $importmode=$token->[2]->{'importmode'};
                   9781:                         if ($importmode eq 'problem') {
1.1069    www      9782: # Import as problem/response
1.1068    www      9783:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9784:                         } elsif ($importmode eq 'part') {
                   9785: # Import as part(s)
1.1069    www      9786:                            $importedparts=1;
                   9787: # We need to get the original file and the imported file to get the part order correct
                   9788: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9789: # Load and inspect original file
1.1070    www      9790:                            if ($#origfileimportpartids<0) {
                   9791:                               undef(%importedpartids);
                   9792:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9793:                               my $origfile=&getfile($origfilelocation);
                   9794:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9795:                            }
                   9796: 
1.1069    www      9797: # Load and inspect imported file
                   9798:                            my $impfile=&getfile($location);
                   9799:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9800:                            if ($#impfilepartids>=0) {
                   9801: # This problem had parts
1.1070    www      9802:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9803:                            } else {
                   9804: # Importing by turning a single problem into a problem part
                   9805: # It gets the import-tags ID as part-ID
                   9806:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9807:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9808:                            }
1.1068    www      9809:                         } else {
                   9810: # Normal import
                   9811:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9812:                            if (defined($token->[2]->{'id'})) {
                   9813:                               $unikey.='_'.$token->[2]->{'id'};
                   9814:                            }
1.1067    www      9815:                         }
                   9816: 
1.339     albertel 9817: 			if ($depthcount<20) {
1.736     albertel 9818: 			    my $metadata = 
                   9819: 				&metadata($uri,'keys', $location,$unikey,
                   9820: 					  $depthcount+1);
                   9821: 			    foreach my $meta (split(',',$metadata)) {
                   9822: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9823: 				$metathesekeys{$meta}=1;
1.339     albertel 9824: 			    }
1.1068    www      9825: 			
                   9826:                         }
1.1067    www      9827: 		    } else {
                   9828: #
                   9829: # Not importing, some other kind of non-package, non-library start tag
                   9830: # 
                   9831:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9832:                         if (defined($token->[2]->{'id'})) {
                   9833:                             $unikey.='_'.$token->[2]->{'id'};
                   9834:                         }
1.339     albertel 9835: 			if (defined($token->[2]->{'name'})) { 
                   9836: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9837: 			}
                   9838: 			$metathesekeys{$unikey}=1;
1.736     albertel 9839: 			foreach my $param (@{$token->[3]}) {
                   9840: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9841: 				$token->[2]->{$param};
1.339     albertel 9842: 			}
                   9843: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9844: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9845: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9846: 		 # only ws inside the tag, and not in default, so use default
                   9847: 		 # as value
1.599     albertel 9848: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9849: 			} elsif ( $internaltext =~ /\S/ ) {
                   9850: 		  # something interesting inside the tag
                   9851: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9852: 			} else {
1.908     albertel 9853: 		  # no interesting values, don't set a default
1.339     albertel 9854: 			}
1.172     www      9855: # end of not-a-package not-a-library import
1.339     albertel 9856: 		    }
1.172     www      9857: # end of not-a-package start tag
1.339     albertel 9858: 		}
1.172     www      9859: # the next is the end of "start tag"
1.339     albertel 9860: 	    }
                   9861: 	}
1.483     albertel 9862: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9863: 	$extension = lc($extension);
                   9864: 	if ($extension eq 'htm') { $extension='html'; }
                   9865: 
1.737     albertel 9866: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9867: 	    #no specific packages #how's our extension
                   9868: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9869: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9870: 					 \%metathesekeys);
                   9871: 	}
1.883     albertel 9872: 
                   9873: 	if (!exists($metaentry{':packages'})
                   9874: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9875: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9876: 		#no specific packages well let's get default then
                   9877: 		if ($key!~/^default&/) { next; }
1.488     albertel 9878: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9879: 					     \%metathesekeys);
                   9880: 	    }
                   9881: 	}
1.338     www      9882: # are there custom rights to evaluate
1.599     albertel 9883: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9884: 
1.338     www      9885:     #
                   9886:     # Importing a rights file here
1.339     albertel 9887:     #
                   9888: 	    unless ($depthcount) {
1.599     albertel 9889: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9890: 		my $dir=$filename;
                   9891: 		$dir=~s|[^/]*$||;
                   9892: 		$location=&filelocation($dir,$location);
1.736     albertel 9893: 		my $rights_metadata =
                   9894: 		    &metadata($uri,'keys',$location,'_rights',
                   9895: 			      $depthcount+1);
                   9896: 		foreach my $rights (split(',',$rights_metadata)) {
                   9897: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9898: 		    $metathesekeys{$rights}=1;
1.339     albertel 9899: 		}
                   9900: 	    }
                   9901: 	}
1.737     albertel 9902: 	# uniqifiy package listing
                   9903: 	my %seen;
                   9904: 	my @uniq_packages =
                   9905: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9906: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9907: 
1.1070    www      9908:         if ($importedparts) {
                   9909: # We had imported parts and need to rebuild partorder
                   9910:            $metaentry{':partorder'}='';
                   9911:            $metathesekeys{'partorder'}=1;
                   9912:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9913:                if ($origfileimportpartids[$index] eq 'part') {
                   9914: # original part, part of the problem
                   9915:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9916:                } else {
                   9917: # we have imported parts at this position
                   9918:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9919:                }
                   9920:            }
                   9921:            $metaentry{':partorder'}=~s/^\,//;
                   9922:         }
                   9923: 
1.737     albertel 9924: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9925: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9926: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9927: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9928: # this is the end of "was not already recently cached
1.71      www      9929:     }
1.599     albertel 9930:     return $metaentry{':'.$what};
1.261     albertel 9931: }
                   9932: 
1.488     albertel 9933: sub metadata_create_package_def {
1.483     albertel 9934:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9935:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9936:     if ($subp eq 'default') { next; }
                   9937:     
1.599     albertel 9938:     if (defined($metaentry{':packages'})) {
                   9939: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9940:     } else {
1.599     albertel 9941: 	$metaentry{':packages'}=$package;
1.483     albertel 9942:     }
                   9943:     my $value=$packagetab{$key};
                   9944:     my $unikey;
                   9945:     $unikey='parameter_0_'.$name;
1.599     albertel 9946:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9947:     $$metathesekeys{$unikey}=1;
1.599     albertel 9948:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9949: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9950:     }
1.599     albertel 9951:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9952: 	$metaentry{':'.$unikey}=
                   9953: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9954:     }
                   9955: }
                   9956: 
1.261     albertel 9957: sub metadata_generate_part0 {
                   9958:     my ($metadata,$metacache,$uri) = @_;
                   9959:     my %allnames;
1.737     albertel 9960:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9961: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9962: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9963: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9964: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9965: 	    $allnames{$name}=$part;
                   9966: 	  }
                   9967: 	}
                   9968:     }
                   9969:     foreach my $name (keys(%allnames)) {
                   9970:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9971:       my $key=":parameter_0_$name";
1.261     albertel 9972:       $$metacache{"$key.part"}='0';
                   9973:       $$metacache{"$key.name"}=$name;
1.428     albertel 9974:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9975: 					   $allnames{$name}.'_'.$name.
                   9976: 					   '.type'};
1.428     albertel 9977:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9978: 			     '.display'};
1.644     www      9979:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9980:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9981:       $$metacache{"$key.display"}=$olddis;
                   9982:     }
1.71      www      9983: }
                   9984: 
1.764     albertel 9985: # ------------------------------------------------------ Devalidate title cache
                   9986: 
                   9987: sub devalidate_title_cache {
                   9988:     my ($url)=@_;
                   9989:     if (!$env{'request.course.id'}) { return; }
                   9990:     my $symb=&symbread($url);
                   9991:     if (!$symb) { return; }
                   9992:     my $key=$env{'request.course.id'}."\0".$symb;
                   9993:     &devalidate_cache_new('title',$key);
                   9994: }
                   9995: 
1.1014    droeschl 9996: # ------------------------------------------------- Get the title of a course
                   9997: 
                   9998: sub current_course_title {
                   9999:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10000: }
1.301     www      10001: # ------------------------------------------------- Get the title of a resource
                   10002: 
                   10003: sub gettitle {
                   10004:     my $urlsymb=shift;
                   10005:     my $symb=&symbread($urlsymb);
1.534     albertel 10006:     if ($symb) {
1.620     albertel 10007: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10008: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10009: 	if (defined($cached)) { 
                   10010: 	    return $result;
                   10011: 	}
1.534     albertel 10012: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10013: 	my $title='';
1.907     albertel 10014: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10015: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10016: 	} else {
                   10017: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10018: 		    &GDBM_READER(),0640)) {
                   10019: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10020: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10021: 		untie(%bighash);
                   10022: 	    }
1.534     albertel 10023: 	}
                   10024: 	$title=~s/\&colon\;/\:/gs;
                   10025: 	if ($title) {
1.1159    www      10026: # Remember both $symb and $title for dynamic metadata
                   10027:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10028:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10029: # Cache this title and then return it
1.599     albertel 10030: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10031: 	}
                   10032: 	$urlsymb=$url;
                   10033:     }
                   10034:     my $title=&metadata($urlsymb,'title');
                   10035:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10036:     return $title;
1.301     www      10037: }
1.613     albertel 10038: 
1.614     albertel 10039: sub get_slot {
                   10040:     my ($which,$cnum,$cdom)=@_;
                   10041:     if (!$cnum || !$cdom) {
1.790     albertel 10042: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10043: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10044: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10045:     }
1.703     albertel 10046:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10047:     my %slotinfo;
                   10048:     if (exists($remembered{$key})) {
                   10049: 	$slotinfo{$which} = $remembered{$key};
                   10050:     } else {
                   10051: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10052: 	&Apache::lonhomework::showhash(%slotinfo);
                   10053: 	my ($tmp)=keys(%slotinfo);
                   10054: 	if ($tmp=~/^error:/) { return (); }
                   10055: 	$remembered{$key} = $slotinfo{$which};
                   10056:     }
1.616     albertel 10057:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10058: 	return %{$slotinfo{$which}};
                   10059:     }
                   10060:     return $slotinfo{$which};
1.614     albertel 10061: }
1.1150    raeburn  10062: 
                   10063: sub get_reservable_slots {
                   10064:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10065:     my $now = time;
                   10066:     my $reservable_info;
                   10067:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10068:     if (exists($remembered{$key})) {
                   10069:         $reservable_info = $remembered{$key};
                   10070:     } else {
                   10071:         my %resv;
                   10072:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10073:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10074:         $reservable_info = \%resv;
                   10075:         $remembered{$key} = $reservable_info;
                   10076:     }
                   10077:     return $reservable_info;
                   10078: }
                   10079: 
                   10080: sub get_course_slots {
                   10081:     my ($cnum,$cdom) = @_;
                   10082:     my $hashid=$cnum.':'.$cdom;
                   10083:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10084:     if (defined($cached)) {
                   10085:         if (ref($result) eq 'HASH') {
                   10086:             return %{$result};
                   10087:         }
                   10088:     } else {
                   10089:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10090:         my ($tmp) = keys(%slots);
                   10091:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10092:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10093:             return %slots;
                   10094:         }
                   10095:     }
                   10096:     return;
                   10097: }
                   10098: 
                   10099: sub devalidate_slots_cache {
                   10100:     my ($cnum,$cdom)=@_;
                   10101:     my $hashid=$cnum.':'.$cdom;
                   10102:     &devalidate_cache_new('allslots',$hashid);
                   10103: }
                   10104: 
1.1181    raeburn  10105: sub get_coursechange {
                   10106:     my ($cdom,$cnum) = @_;
                   10107:     if ($cdom eq '' || $cnum eq '') {
                   10108:         return unless ($env{'request.course.id'});
                   10109:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10110:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10111:     }
                   10112:     my $hashid=$cdom.'_'.$cnum;
                   10113:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10114:     if ((defined($cached)) && ($change ne '')) {
                   10115:         return $change;
                   10116:     } else {
                   10117:         my %crshash;
                   10118:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10119:         if ($crshash{'internal.contentchange'} eq '') {
                   10120:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10121:             if ($change eq '') {
                   10122:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10123:                 $change = $crshash{'internal.created'};
                   10124:             }
                   10125:         } else {
                   10126:             $change = $crshash{'internal.contentchange'};
                   10127:         }
                   10128:         my $cachetime = 600;
                   10129:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10130:     }
                   10131:     return $change;
                   10132: }
                   10133: 
                   10134: sub devalidate_coursechange_cache {
                   10135:     my ($cnum,$cdom)=@_;
                   10136:     my $hashid=$cnum.':'.$cdom;
                   10137:     &devalidate_cache_new('crschange',$hashid);
                   10138: }
                   10139: 
1.31      www      10140: # ------------------------------------------------- Update symbolic store links
                   10141: 
                   10142: sub symblist {
                   10143:     my ($mapname,%newhash)=@_;
1.438     www      10144:     $mapname=&deversion(&declutter($mapname));
1.31      www      10145:     my %hash;
1.620     albertel 10146:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10147:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10148:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10149: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10150: 		next if ($url eq 'last_known'
                   10151: 			 && $env{'form.no_update_last_known'});
                   10152: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10153: 						    $newhash{$url}->[1],
                   10154: 						    $newhash{$url}->[0]);
1.191     harris41 10155:             }
1.31      www      10156:             if (untie(%hash)) {
                   10157: 		return 'ok';
                   10158:             }
                   10159:         }
                   10160:     }
                   10161:     return 'error';
1.212     www      10162: }
                   10163: 
                   10164: # --------------------------------------------------------------- Verify a symb
                   10165: 
                   10166: sub symbverify {
1.1190    raeburn  10167:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10168:     my $thisfn=$thisurl;
1.439     www      10169:     $thisfn=&declutter($thisfn);
1.215     www      10170: # direct jump to resource in page or to a sequence - will construct own symbs
                   10171:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10172: # check URL part
1.409     www      10173:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10174: 
1.431     www      10175:     unless ($url eq $thisfn) { return 0; }
1.213     www      10176: 
1.216     www      10177:     $symb=&symbclean($symb);
1.510     www      10178:     $thisurl=&deversion($thisurl);
1.439     www      10179:     $thisfn=&deversion($thisfn);
1.213     www      10180: 
                   10181:     my %bighash;
                   10182:     my $okay=0;
1.431     www      10183: 
1.620     albertel 10184:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10185:                             &GDBM_READER(),0640)) {
1.1032    raeburn  10186:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10187:             $thisurl =~ s/\?.+$//;
                   10188:         }
1.510     www      10189:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  10190:         unless ($ids) {
                   10191:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10192:             $ids=$bighash{$idkey};
1.216     www      10193:         }
                   10194:         if ($ids) {
                   10195: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 10196: 	    foreach my $id (split(/\,/,$ids)) {
                   10197: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  10198:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10199:                    $symb =~ s/\?.+$//;
                   10200:                }
1.216     www      10201:                if (
                   10202:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10203:    eq $symb) {
                   10204:                    if (ref($encstate)) {
                   10205:                        $$encstate = $bighash{'encrypted_'.$id};
                   10206:                    }
1.620     albertel 10207: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10208: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10209:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10210: 		       $okay=1;
1.582     albertel 10211: 		   }
                   10212: 	       }
1.216     www      10213: 	   }
                   10214:         }
1.213     www      10215: 	untie(%bighash);
                   10216:     }
                   10217:     return $okay;
1.31      www      10218: }
                   10219: 
1.210     www      10220: # --------------------------------------------------------------- Clean-up symb
                   10221: 
                   10222: sub symbclean {
                   10223:     my $symb=shift;
1.568     albertel 10224:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10225: # remove version from map
                   10226:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10227: 
1.210     www      10228: # remove version from URL
                   10229:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10230: 
1.507     www      10231: # remove wrapper
                   10232: 
1.510     www      10233:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10234:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10235:     return $symb;
1.409     www      10236: }
                   10237: 
                   10238: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10239: 
                   10240: sub encode_symb {
                   10241:     my ($map,$resid,$url)=@_;
                   10242:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10243: }
1.409     www      10244: 
                   10245: sub decode_symb {
1.568     albertel 10246:     my $symb=shift;
                   10247:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10248:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10249:     return (&fixversion($map),$resid,&fixversion($url));
                   10250: }
                   10251: 
                   10252: sub fixversion {
                   10253:     my $fn=shift;
1.609     banghart 10254:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10255:     my %bighash;
                   10256:     my $uri=&clutter($fn);
1.620     albertel 10257:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10258: # is this cached?
1.599     albertel 10259:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10260:     if (defined($cached)) { return $result; }
                   10261: # unfortunately not cached, or expired
1.620     albertel 10262:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10263: 	    &GDBM_READER(),0640)) {
                   10264:  	if ($bighash{'version_'.$uri}) {
                   10265:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10266:  	    unless (($version eq 'mostrecent') || 
                   10267: 		    ($version==&getversion($uri))) {
1.440     www      10268:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10269:  	    }
                   10270:  	}
                   10271:  	untie %bighash;
1.413     www      10272:     }
1.599     albertel 10273:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10274: }
                   10275: 
                   10276: sub deversion {
                   10277:     my $url=shift;
                   10278:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10279:     return $url;
1.210     www      10280: }
                   10281: 
1.31      www      10282: # ------------------------------------------------------ Return symb list entry
                   10283: 
                   10284: sub symbread {
1.249     www      10285:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 10286:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1179    raeburn  10287:     if (defined($env{$cache_str})) {
                   10288:         if (($thisfn) || ($env{$cache_str} ne '')) {
                   10289:             return $env{$cache_str};
                   10290:         }
                   10291:     }
1.242     www      10292: # no filename provided? try from environment
1.44      www      10293:     unless ($thisfn) {
1.620     albertel 10294:         if ($env{'request.symb'}) {
                   10295: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10296: 	}
1.620     albertel 10297: 	$thisfn=$env{'request.filename'};
1.44      www      10298:     }
1.569     albertel 10299:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10300: # is that filename actually a symb? Verify, clean, and return
                   10301:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10302: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10303: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10304: 	}
1.242     www      10305:     }
1.44      www      10306:     $thisfn=declutter($thisfn);
1.31      www      10307:     my %hash;
1.37      www      10308:     my %bighash;
                   10309:     my $syval='';
1.620     albertel 10310:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10311:         my $targetfn = $thisfn;
1.609     banghart 10312:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10313:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10314:         }
1.687     albertel 10315: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10316: 	    $targetfn=$1;
                   10317: 	}
1.620     albertel 10318:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10319:                       &GDBM_READER(),0640)) {
1.481     raeburn  10320: 	    $syval=$hash{$targetfn};
1.37      www      10321:             untie(%hash);
                   10322:         }
                   10323: # ---------------------------------------------------------- There was an entry
                   10324:         if ($syval) {
1.601     albertel 10325: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10326: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10327: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10328: 		    #return $env{$cache_str}='';
1.601     albertel 10329: 		#}    
                   10330: 		#$syval.=$1;
                   10331: 	    #}
1.37      www      10332:         } else {
                   10333: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10334:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10335:                             &GDBM_READER(),0640)) {
1.37      www      10336: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10337:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10338:               unless ($ids) { 
                   10339:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10340:               }
                   10341:               unless ($ids) {
                   10342: # alias?
                   10343: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10344:               }
1.37      www      10345:               if ($ids) {
                   10346: # ------------------------------------------------------------------- Has ID(s)
                   10347:                  my @possibilities=split(/\,/,$ids);
1.39      www      10348:                  if ($#possibilities==0) {
                   10349: # ----------------------------------------------- There is only one possibility
1.37      www      10350: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10351: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10352: 						    $resid,$thisfn);
1.249     www      10353:                  } elsif (!$donotrecurse) {
1.39      www      10354: # ------------------------------------------ There is more than one possibility
                   10355:                      my $realpossible=0;
1.800     albertel 10356:                      foreach my $id (@possibilities) {
                   10357: 			 my $file=$bighash{'src_'.$id};
1.39      www      10358:                          if (&allowed('bre',$file)) {
1.800     albertel 10359:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10360:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10361: 				$realpossible++;
1.626     albertel 10362:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10363: 						    $resid,$thisfn);
1.39      www      10364:                             }
                   10365: 			 }
1.191     harris41 10366:                      }
1.39      www      10367: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10368:                  } else {
                   10369:                      $syval='';
1.37      www      10370:                  }
                   10371: 	      }
                   10372:               untie(%bighash)
1.481     raeburn  10373:            }
1.31      www      10374:         }
1.62      www      10375:         if ($syval) {
1.620     albertel 10376: 	    return $env{$cache_str}=$syval;
1.62      www      10377:         }
1.31      www      10378:     }
1.949     raeburn  10379:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10380:     return $env{$cache_str}='';
1.31      www      10381: }
                   10382: 
                   10383: # ---------------------------------------------------------- Return random seed
                   10384: 
1.32      www      10385: sub numval {
                   10386:     my $txt=shift;
                   10387:     $txt=~tr/A-J/0-9/;
                   10388:     $txt=~tr/a-j/0-9/;
                   10389:     $txt=~tr/K-T/0-9/;
                   10390:     $txt=~tr/k-t/0-9/;
                   10391:     $txt=~tr/U-Z/0-5/;
                   10392:     $txt=~tr/u-z/0-5/;
                   10393:     $txt=~s/\D//g;
1.564     albertel 10394:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10395:     return int($txt);
1.368     albertel 10396: }
                   10397: 
1.484     albertel 10398: sub numval2 {
                   10399:     my $txt=shift;
                   10400:     $txt=~tr/A-J/0-9/;
                   10401:     $txt=~tr/a-j/0-9/;
                   10402:     $txt=~tr/K-T/0-9/;
                   10403:     $txt=~tr/k-t/0-9/;
                   10404:     $txt=~tr/U-Z/0-5/;
                   10405:     $txt=~tr/u-z/0-5/;
                   10406:     $txt=~s/\D//g;
                   10407:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10408:     my $total;
                   10409:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10410:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10411:     return int($total);
                   10412: }
                   10413: 
1.575     albertel 10414: sub numval3 {
                   10415:     use integer;
                   10416:     my $txt=shift;
                   10417:     $txt=~tr/A-J/0-9/;
                   10418:     $txt=~tr/a-j/0-9/;
                   10419:     $txt=~tr/K-T/0-9/;
                   10420:     $txt=~tr/k-t/0-9/;
                   10421:     $txt=~tr/U-Z/0-5/;
                   10422:     $txt=~tr/u-z/0-5/;
                   10423:     $txt=~s/\D//g;
                   10424:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10425:     my $total;
                   10426:     foreach my $val (@txts) { $total+=$val; }
                   10427:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10428:     return $total;
                   10429: }
                   10430: 
1.675     albertel 10431: sub digest {
                   10432:     my ($data)=@_;
                   10433:     my $digest=&Digest::MD5::md5($data);
                   10434:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10435:     my ($e,$f);
                   10436:     {
                   10437:         use integer;
                   10438:         $e=($a+$b);
                   10439:         $f=($c+$d);
                   10440:         if ($_64bit) {
                   10441:             $e=(($e<<32)>>32);
                   10442:             $f=(($f<<32)>>32);
                   10443:         }
                   10444:     }
                   10445:     if (wantarray) {
                   10446: 	return ($e,$f);
                   10447:     } else {
                   10448: 	my $g;
                   10449: 	{
                   10450: 	    use integer;
                   10451: 	    $g=($e+$f);
                   10452: 	    if ($_64bit) {
                   10453: 		$g=(($g<<32)>>32);
                   10454: 	    }
                   10455: 	}
                   10456: 	return $g;
                   10457:     }
                   10458: }
                   10459: 
1.368     albertel 10460: sub latest_rnd_algorithm_id {
1.675     albertel 10461:     return '64bit5';
1.366     albertel 10462: }
1.32      www      10463: 
1.503     albertel 10464: sub get_rand_alg {
                   10465:     my ($courseid)=@_;
1.790     albertel 10466:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10467:     if ($courseid) {
1.620     albertel 10468: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10469:     }
                   10470:     return &latest_rnd_algorithm_id();
                   10471: }
                   10472: 
1.562     albertel 10473: sub validCODE {
                   10474:     my ($CODE)=@_;
                   10475:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10476:     return 0;
                   10477: }
                   10478: 
1.491     albertel 10479: sub getCODE {
1.620     albertel 10480:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10481:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10482: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10483: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10484: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10485:     }
                   10486:     return undef;
                   10487: }
1.1133    foxr     10488: #
                   10489: #  Determines the random seed for a specific context:
                   10490: #
                   10491: # parameters:
                   10492: #   symb      - in course context the symb for the seed.
                   10493: #   course_id - The course id of the form domain_coursenum.
                   10494: #   domain    - Domain for the user.
                   10495: #   course    - Course for the user.
                   10496: #   cenv      - environment of the course.
                   10497: #
                   10498: # NOTE:
                   10499: #   All parameters are picked out of the environment if missing
                   10500: #   or not defined.
                   10501: #   If a symb cannot be determined the current time is used instead.
                   10502: #
                   10503: #  For a given well defined symb, courside, domain, username,
                   10504: #  and course environment, the seed is reproducible.
                   10505: #
1.31      www      10506: sub rndseed {
1.1133    foxr     10507:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10508:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10509:     if (!defined($symb)) {
1.366     albertel 10510: 	unless ($symb=$wsymb) { return time; }
                   10511:     }
1.1146    foxr     10512:     if (!defined $courseid) { 
                   10513: 	$courseid=$wcourseid; 
                   10514:     }
                   10515:     if (!defined $domain) { $domain=$wdomain; }
                   10516:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10517: 
                   10518:     my $which;
                   10519:     if (defined($cenv->{'rndseed'})) {
                   10520: 	$which = $cenv->{'rndseed'};
                   10521:     } else {
                   10522: 	$which =&get_rand_alg($courseid);
                   10523:     }
1.491     albertel 10524:     if (defined(&getCODE())) {
1.1133    foxr     10525: 
1.675     albertel 10526: 	if ($which eq '64bit5') {
                   10527: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10528: 	} elsif ($which eq '64bit4') {
1.575     albertel 10529: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10530: 	} else {
                   10531: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10532: 	}
1.675     albertel 10533:     } elsif ($which eq '64bit5') {
                   10534: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10535:     } elsif ($which eq '64bit4') {
                   10536: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10537:     } elsif ($which eq '64bit3') {
                   10538: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10539:     } elsif ($which eq '64bit2') {
                   10540: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10541:     } elsif ($which eq '64bit') {
                   10542: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10543:     }
                   10544:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10545: }
                   10546: 
                   10547: sub rndseed_32bit {
                   10548:     my ($symb,$courseid,$domain,$username)=@_;
                   10549:     {
                   10550: 	use integer;
                   10551: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10552: 	my $symbseed=numval($symb) << 22;
                   10553: 	my $namechck=unpack("%32C*",$username) << 17;
                   10554: 	my $nameseed=numval($username) << 12;
                   10555: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10556: 	my $courseseed=unpack("%32C*",$courseid);
                   10557: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10558: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10559: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10560: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10561: 	return $num;
                   10562:     }
                   10563: }
                   10564: 
                   10565: sub rndseed_64bit {
                   10566:     my ($symb,$courseid,$domain,$username)=@_;
                   10567:     {
                   10568: 	use integer;
                   10569: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10570: 	my $symbseed=numval($symb) << 10;
                   10571: 	my $namechck=unpack("%32S*",$username);
                   10572: 	
                   10573: 	my $nameseed=numval($username) << 21;
                   10574: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10575: 	my $courseseed=unpack("%32S*",$courseid);
                   10576: 	
                   10577: 	my $num1=$symbchck+$symbseed+$namechck;
                   10578: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10579: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10580: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10581: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10582: 	return "$num1,$num2";
1.155     albertel 10583:     }
1.366     albertel 10584: }
                   10585: 
1.443     albertel 10586: sub rndseed_64bit2 {
                   10587:     my ($symb,$courseid,$domain,$username)=@_;
                   10588:     {
                   10589: 	use integer;
                   10590: 	# strings need to be an even # of cahracters long, it it is odd the
                   10591:         # last characters gets thrown away
                   10592: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10593: 	my $symbseed=numval($symb) << 10;
                   10594: 	my $namechck=unpack("%32S*",$username.' ');
                   10595: 	
                   10596: 	my $nameseed=numval($username) << 21;
1.501     albertel 10597: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10598: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10599: 	
                   10600: 	my $num1=$symbchck+$symbseed+$namechck;
                   10601: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10602: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10603: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10604: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10605: 	return "$num1,$num2";
                   10606:     }
                   10607: }
                   10608: 
                   10609: sub rndseed_64bit3 {
                   10610:     my ($symb,$courseid,$domain,$username)=@_;
                   10611:     {
                   10612: 	use integer;
                   10613: 	# strings need to be an even # of cahracters long, it it is odd the
                   10614:         # last characters gets thrown away
                   10615: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10616: 	my $symbseed=numval2($symb) << 10;
                   10617: 	my $namechck=unpack("%32S*",$username.' ');
                   10618: 	
                   10619: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10620: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10621: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10622: 	
                   10623: 	my $num1=$symbchck+$symbseed+$namechck;
                   10624: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10625: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10626: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10627: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10628: 	
1.503     albertel 10629: 	return "$num1:$num2";
1.443     albertel 10630:     }
                   10631: }
                   10632: 
1.575     albertel 10633: sub rndseed_64bit4 {
                   10634:     my ($symb,$courseid,$domain,$username)=@_;
                   10635:     {
                   10636: 	use integer;
                   10637: 	# strings need to be an even # of cahracters long, it it is odd the
                   10638:         # last characters gets thrown away
                   10639: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10640: 	my $symbseed=numval3($symb) << 10;
                   10641: 	my $namechck=unpack("%32S*",$username.' ');
                   10642: 	
                   10643: 	my $nameseed=numval3($username) << 21;
                   10644: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10645: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10646: 	
                   10647: 	my $num1=$symbchck+$symbseed+$namechck;
                   10648: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10649: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10650: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10651: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10652: 	
1.575     albertel 10653: 	return "$num1:$num2";
                   10654:     }
                   10655: }
                   10656: 
1.675     albertel 10657: sub rndseed_64bit5 {
                   10658:     my ($symb,$courseid,$domain,$username)=@_;
                   10659:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10660:     return "$num1:$num2";
                   10661: }
                   10662: 
1.366     albertel 10663: sub rndseed_CODE_64bit {
                   10664:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10665:     {
1.366     albertel 10666: 	use integer;
1.443     albertel 10667: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10668: 	my $symbseed=numval2($symb);
1.491     albertel 10669: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10670: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10671: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10672: 	my $num1=$symbseed+$CODEchck;
                   10673: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10674: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10675: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10676: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10677: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10678: 	return "$num1:$num2";
1.366     albertel 10679:     }
                   10680: }
                   10681: 
1.575     albertel 10682: sub rndseed_CODE_64bit4 {
                   10683:     my ($symb,$courseid,$domain,$username)=@_;
                   10684:     {
                   10685: 	use integer;
                   10686: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10687: 	my $symbseed=numval3($symb);
                   10688: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10689: 	my $CODEseed=numval3(&getCODE());
                   10690: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10691: 	my $num1=$symbseed+$CODEchck;
                   10692: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10693: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10694: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10695: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10696: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10697: 	return "$num1:$num2";
                   10698:     }
                   10699: }
                   10700: 
1.675     albertel 10701: sub rndseed_CODE_64bit5 {
                   10702:     my ($symb,$courseid,$domain,$username)=@_;
                   10703:     my $code = &getCODE();
                   10704:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10705:     return "$num1:$num2";
                   10706: }
                   10707: 
1.366     albertel 10708: sub setup_random_from_rndseed {
                   10709:     my ($rndseed)=@_;
1.503     albertel 10710:     if ($rndseed =~/([,:])/) {
                   10711: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10712: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10713:     } else {
                   10714: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10715:     }
1.36      albertel 10716: }
                   10717: 
1.474     albertel 10718: sub latest_receipt_algorithm_id {
1.835     albertel 10719:     return 'receipt3';
1.474     albertel 10720: }
                   10721: 
1.480     www      10722: sub recunique {
                   10723:     my $fucourseid=shift;
                   10724:     my $unique;
1.835     albertel 10725:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10726: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10727: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10728:     } else {
                   10729: 	$unique=$perlvar{'lonReceipt'};
                   10730:     }
                   10731:     return unpack("%32C*",$unique);
                   10732: }
                   10733: 
                   10734: sub recprefix {
                   10735:     my $fucourseid=shift;
                   10736:     my $prefix;
1.835     albertel 10737:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10738: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10739: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10740:     } else {
                   10741: 	$prefix=$perlvar{'lonHostID'};
                   10742:     }
                   10743:     return unpack("%32C*",$prefix);
                   10744: }
                   10745: 
1.76      www      10746: sub ireceipt {
1.474     albertel 10747:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10748: 
                   10749:     my $return =&recprefix($fucourseid).'-';
                   10750: 
                   10751:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10752: 	$env{'request.state'} eq 'construct') {
                   10753: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10754: 	return $return;
                   10755:     }
                   10756: 
1.76      www      10757:     my $cuname=unpack("%32C*",$funame);
                   10758:     my $cudom=unpack("%32C*",$fudom);
                   10759:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10760:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10761:     my $cunique=&recunique($fucourseid);
1.474     albertel 10762:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10763:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10764: 
1.790     albertel 10765: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10766: 			       
                   10767: 	$return.= ($cunique%$cuname+
                   10768: 		   $cunique%$cudom+
                   10769: 		   $cusymb%$cuname+
                   10770: 		   $cusymb%$cudom+
                   10771: 		   $cucourseid%$cuname+
                   10772: 		   $cucourseid%$cudom+
                   10773: 		   $cpart%$cuname+
                   10774: 		   $cpart%$cudom);
                   10775:     } else {
                   10776: 	$return.= ($cunique%$cuname+
                   10777: 		   $cunique%$cudom+
                   10778: 		   $cusymb%$cuname+
                   10779: 		   $cusymb%$cudom+
                   10780: 		   $cucourseid%$cuname+
                   10781: 		   $cucourseid%$cudom);
                   10782:     }
                   10783:     return $return;
1.76      www      10784: }
                   10785: 
                   10786: sub receipt {
1.474     albertel 10787:     my ($part)=@_;
1.790     albertel 10788:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10789:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10790: }
1.260     ng       10791: 
1.790     albertel 10792: sub whichuser {
                   10793:     my ($passedsymb)=@_;
                   10794:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10795:     if (defined($env{'form.grade_symb'})) {
                   10796: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10797: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10798: 	if (!$allowed &&
                   10799: 	    exists($env{'request.course.sec'}) &&
                   10800: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10801: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10802: 			      '/'.$env{'request.course.sec'});
                   10803: 	}
                   10804: 	if ($allowed) {
                   10805: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10806: 	    $courseid=$tmp_courseid;
                   10807: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10808: 	    ($name)=&get_env_multiple('form.grade_username');
                   10809: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10810: 	}
                   10811:     }
                   10812:     if (!$passedsymb) {
                   10813: 	$symb=&symbread();
                   10814:     } else {
                   10815: 	$symb=$passedsymb;
                   10816:     }
                   10817:     $courseid=$env{'request.course.id'};
                   10818:     $domain=$env{'user.domain'};
                   10819:     $name=$env{'user.name'};
                   10820:     if ($name eq 'public' && $domain eq 'public') {
                   10821: 	if (!defined($env{'form.username'})) {
                   10822: 	    $env{'form.username'}.=time.rand(10000000);
                   10823: 	}
                   10824: 	$name.=$env{'form.username'};
                   10825:     }
                   10826:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10827: 
                   10828: }
                   10829: 
1.36      albertel 10830: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10831: # returns either the contents of the file or 
                   10832: # -1 if the file doesn't exist
1.481     raeburn  10833: #
                   10834: # if the target is a file that was uploaded via DOCS, 
                   10835: # a check will be made to see if a current copy exists on the local server,
                   10836: # if it does this will be served, otherwise a copy will be retrieved from
                   10837: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10838: # the local server.   
1.472     albertel 10839: 
1.36      albertel 10840: sub getfile {
1.538     albertel 10841:     my ($file) = @_;
1.609     banghart 10842:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10843:     &repcopy($file);
                   10844:     return &readfile($file);
                   10845: }
                   10846: 
                   10847: sub repcopy_userfile {
                   10848:     my ($file)=@_;
1.1142    raeburn  10849:     my $londocroot = $perlvar{'lonDocRoot'};
                   10850:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10851:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10852:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10853: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10854:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10855:     if (-e "$file") {
1.828     www      10856: # we already have a local copy, check it out
1.538     albertel 10857: 	my @fileinfo = stat($file);
1.828     www      10858: 	my $rtncode;
                   10859: 	my $info;
1.538     albertel 10860: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10861: 	if ($lwpresp ne 'ok') {
1.828     www      10862: # there is no such file anymore, even though we had a local copy
1.482     albertel 10863: 	    if ($rtncode eq '404') {
1.538     albertel 10864: 		unlink($file);
1.482     albertel 10865: 	    }
                   10866: 	    return -1;
                   10867: 	}
                   10868: 	if ($info < $fileinfo[9]) {
1.828     www      10869: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10870: 	    return 'ok';
1.828     www      10871: 	} else {
                   10872: # the file is outdated, get rid of it
                   10873: 	    unlink($file);
1.482     albertel 10874: 	}
1.828     www      10875:     }
                   10876: # one way or the other, at this point, we don't have the file
                   10877: # construct the correct path for the file
                   10878:     my @parts = ($cdom,$cnum); 
                   10879:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10880: 	push @parts, split(/\//,$1);
                   10881:     }
                   10882:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10883:     foreach my $part (@parts) {
                   10884: 	$path .= '/'.$part;
                   10885: 	if (!-e $path) {
                   10886: 	    mkdir($path,0770);
1.482     albertel 10887: 	}
                   10888:     }
1.828     www      10889: # now the path exists for sure
                   10890: # get a user agent
                   10891:     my $ua=new LWP::UserAgent;
                   10892:     my $transferfile=$file.'.in.transfer';
                   10893: # FIXME: this should flock
                   10894:     if (-e $transferfile) { return 'ok'; }
                   10895:     my $request;
                   10896:     $uri=~s/^\///;
1.980     raeburn  10897:     my $homeserver = &homeserver($cnum,$cdom);
                   10898:     my $protocol = $protocol{$homeserver};
                   10899:     $protocol = 'http' if ($protocol ne 'https');
                   10900:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10901:     my $response=$ua->request($request,$transferfile);
                   10902: # did it work?
                   10903:     if ($response->is_error()) {
                   10904: 	unlink($transferfile);
                   10905: 	&logthis("Userfile repcopy failed for $uri");
                   10906: 	return -1;
                   10907:     }
                   10908: # worked, rename the transfer file
                   10909:     rename($transferfile,$file);
1.607     raeburn  10910:     return 'ok';
1.481     raeburn  10911: }
                   10912: 
1.517     albertel 10913: sub tokenwrapper {
                   10914:     my $uri=shift;
1.980     raeburn  10915:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10916:     $uri=~s|^/||;
1.620     albertel 10917:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10918:     my $token=$1;
1.552     albertel 10919:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10920:     if ($udom && $uname && $file) {
                   10921: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10922:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10923:         my $homeserver = &homeserver($uname,$udom);
                   10924:         my $protocol = $protocol{$homeserver};
                   10925:         $protocol = 'http' if ($protocol ne 'https');
                   10926:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10927:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10928:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10929:     } else {
                   10930:         return '/adm/notfound.html';
                   10931:     }
                   10932: }
                   10933: 
1.828     www      10934: # call with reqtype HEAD: get last modification time
                   10935: # call with reqtype GET: get the file contents
                   10936: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10937: #
1.481     raeburn  10938: sub getuploaded {
                   10939:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10940:     $uri=~s/^\///;
1.980     raeburn  10941:     my $homeserver = &homeserver($cnum,$cdom);
                   10942:     my $protocol = $protocol{$homeserver};
                   10943:     $protocol = 'http' if ($protocol ne 'https');
                   10944:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10945:     my $ua=new LWP::UserAgent;
                   10946:     my $request=new HTTP::Request($reqtype,$uri);
                   10947:     my $response=$ua->request($request);
                   10948:     $$rtncode = $response->code;
1.482     albertel 10949:     if (! $response->is_success()) {
                   10950: 	return 'failed';
                   10951:     }      
                   10952:     if ($reqtype eq 'HEAD') {
1.486     www      10953: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10954:     } elsif ($reqtype eq 'GET') {
                   10955: 	$$info = $response->content;
1.472     albertel 10956:     }
1.482     albertel 10957:     return 'ok';
1.36      albertel 10958: }
                   10959: 
1.481     raeburn  10960: sub readfile {
                   10961:     my $file = shift;
                   10962:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10963:     my $fh;
                   10964:     open($fh,"<$file");
                   10965:     my $a='';
1.800     albertel 10966:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10967:     return $a;
                   10968: }
                   10969: 
1.36      albertel 10970: sub filelocation {
1.590     banghart 10971:     my ($dir,$file) = @_;
                   10972:     my $location;
                   10973:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10974: 
                   10975:     if ($file =~ m-^/adm/-) {
                   10976: 	$file=~s-^/adm/wrapper/-/-;
                   10977: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10978:     }
1.882     albertel 10979: 
1.1139    www      10980:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10981:         $location = $file;
1.609     banghart 10982:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10983:         my ($udom,$uname,$filename)=
1.811     albertel 10984:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10985:         my $home=&homeserver($uname,$udom);
                   10986:         my $is_me=0;
                   10987:         my @ids=&current_machine_ids();
                   10988:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10989:         if ($is_me) {
1.1117    foxr     10990:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10991:         } else {
                   10992:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10993:   	      $udom.'/'.$uname.'/'.$filename;
                   10994:         }
1.882     albertel 10995:     } elsif ($file =~ m-^/adm/-) {
                   10996: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10997:     } else {
                   10998:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10999:         $file=~s:^/(res|priv)/:/:;
                   11000:         my $space=$1;
1.590     banghart 11001:         if ( !( $file =~ m:^/:) ) {
                   11002:             $location = $dir. '/'.$file;
                   11003:         } else {
1.1142    raeburn  11004:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11005:         }
1.59      albertel 11006:     }
1.590     banghart 11007:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11008:     while ($location=~m{/\.\./}) {
                   11009: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11010: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11011: 	} else {
                   11012: 	    $location=~ s{/\.\./}{/}g;
                   11013: 	}
                   11014:     } #remove dir/..
1.590     banghart 11015:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11016:     return $location;
1.46      www      11017: }
1.36      albertel 11018: 
1.46      www      11019: sub hreflocation {
                   11020:     my ($dir,$file)=@_;
1.980     raeburn  11021:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11022: 	$file=filelocation($dir,$file);
1.700     albertel 11023:     } elsif ($file=~m-^/adm/-) {
                   11024: 	$file=~s-^/adm/wrapper/-/-;
                   11025: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11026:     }
                   11027:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11028: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11029:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11030: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11031: 	        {/uploaded/$1/$2/}x;
1.46      www      11032:     }
1.913     albertel 11033:     if ($file=~ m{^/userfiles/}) {
                   11034: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11035:     }
1.462     albertel 11036:     return $file;
1.465     albertel 11037: }
                   11038: 
1.1139    www      11039: 
                   11040: 
                   11041: 
                   11042: 
1.465     albertel 11043: sub current_machine_domains {
1.853     albertel 11044:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11045: }
                   11046: 
                   11047: sub machine_domains {
                   11048:     my ($hostname) = @_;
1.465     albertel 11049:     my @domains;
1.838     albertel 11050:     my %hostname = &all_hostnames();
1.465     albertel 11051:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11052: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11053: 	if ($hostname eq $name) {
1.844     albertel 11054: 	    push(@domains,&host_domain($id));
1.465     albertel 11055: 	}
                   11056:     }
                   11057:     return @domains;
                   11058: }
                   11059: 
                   11060: sub current_machine_ids {
1.853     albertel 11061:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11062: }
                   11063: 
                   11064: sub machine_ids {
                   11065:     my ($hostname) = @_;
                   11066:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11067:     my @ids;
1.888     albertel 11068:     my %name_to_host = &all_names();
1.889     albertel 11069:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11070: 	return @{ $name_to_host{$hostname} };
                   11071:     }
                   11072:     return;
1.31      www      11073: }
                   11074: 
1.824     raeburn  11075: sub additional_machine_domains {
                   11076:     my @domains;
                   11077:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11078:     while( my $line = <$fh>) {
                   11079:         $line =~ s/\s//g;
                   11080:         push(@domains,$line);
                   11081:     }
                   11082:     return @domains;
                   11083: }
                   11084: 
                   11085: sub default_login_domain {
                   11086:     my $domain = $perlvar{'lonDefDomain'};
                   11087:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11088:     foreach my $posdom (&current_machine_domains(),
                   11089:                         &additional_machine_domains()) {
                   11090:         if (lc($posdom) eq lc($testdomain)) {
                   11091:             $domain=$posdom;
                   11092:             last;
                   11093:         }
                   11094:     }
                   11095:     return $domain;
                   11096: }
                   11097: 
1.31      www      11098: # ------------------------------------------------------------- Declutters URLs
                   11099: 
                   11100: sub declutter {
                   11101:     my $thisfn=shift;
1.569     albertel 11102:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11103:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11104:     $thisfn=~s/^\///;
1.697     albertel 11105:     $thisfn=~s|^adm/wrapper/||;
                   11106:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11107:     $thisfn=~s/^res\///;
1.1172    bisitz   11108:     $thisfn=~s/^priv\///;
1.1032    raeburn  11109:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11110:         $thisfn=~s/\?.+$//;
                   11111:     }
1.268     www      11112:     return $thisfn;
                   11113: }
                   11114: 
                   11115: # ------------------------------------------------------------- Clutter up URLs
                   11116: 
                   11117: sub clutter {
                   11118:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11119:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11120: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11121:        $thisfn='/res'.$thisfn; 
                   11122:     }
1.1031    raeburn  11123:     if ($thisfn !~m|^/adm|) {
                   11124: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11125: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11126: 	} else {
                   11127: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11128: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11129: 	    if ($embstyle eq 'ssi'
                   11130: 		|| ($embstyle eq 'hdn')
                   11131: 		|| ($embstyle eq 'rat')
                   11132: 		|| ($embstyle eq 'prv')
                   11133: 		|| ($embstyle eq 'ign')) {
                   11134: 		#do nothing with these
                   11135: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11136: 		|| ($embstyle eq 'emb')
                   11137: 		|| ($embstyle eq 'wrp')) {
                   11138: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11139: 	    } elsif ($embstyle eq 'unk'
                   11140: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11141: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11142: 	    } else {
1.718     www      11143: #		&logthis("Got a blank emb style");
1.695     albertel 11144: 	    }
1.694     albertel 11145: 	}
                   11146:     }
1.31      www      11147:     return $thisfn;
1.12      www      11148: }
                   11149: 
1.787     albertel 11150: sub clutter_with_no_wrapper {
                   11151:     my $uri = &clutter(shift);
                   11152:     if ($uri =~ m-^/adm/-) {
                   11153: 	$uri =~ s-^/adm/wrapper/-/-;
                   11154: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11155:     }
                   11156:     return $uri;
                   11157: }
                   11158: 
1.557     albertel 11159: sub freeze_escape {
                   11160:     my ($value)=@_;
                   11161:     if (ref($value)) {
                   11162: 	$value=&nfreeze($value);
                   11163: 	return '__FROZEN__'.&escape($value);
                   11164:     }
                   11165:     return &escape($value);
                   11166: }
                   11167: 
1.11      www      11168: 
1.557     albertel 11169: sub thaw_unescape {
                   11170:     my ($value)=@_;
                   11171:     if ($value =~ /^__FROZEN__/) {
                   11172: 	substr($value,0,10,undef);
                   11173: 	$value=&unescape($value);
                   11174: 	return &thaw($value);
                   11175:     }
                   11176:     return &unescape($value);
                   11177: }
                   11178: 
1.436     albertel 11179: sub correct_line_ends {
                   11180:     my ($result)=@_;
                   11181:     $$result =~s/\r\n/\n/mg;
                   11182:     $$result =~s/\r/\n/mg;
1.415     albertel 11183: }
1.1       albertel 11184: # ================================================================ Main Program
                   11185: 
1.184     www      11186: sub goodbye {
1.204     albertel 11187:    &logthis("Starting Shut down");
1.443     albertel 11188: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11189:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11190: #converted
1.599     albertel 11191: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11192:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11193: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11194: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11195: #1.1 only
1.870     albertel 11196: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11197: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11198: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11199: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11200:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11201:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11202:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11203:    &flushcourselogs();
                   11204:    &logthis("Shutting down");
                   11205: }
                   11206: 
1.852     albertel 11207: sub get_dns {
1.869     albertel 11208:     my ($url,$func,$ignore_cache) = @_;
                   11209:     if (!$ignore_cache) {
                   11210: 	my ($content,$cached)=
                   11211: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11212: 	if ($cached) {
                   11213: 	    &$func($content);
                   11214: 	    return;
                   11215: 	}
                   11216:     }
                   11217: 
                   11218:     my %alldns;
1.852     albertel 11219:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11220:     foreach my $dns (<$config>) {
                   11221: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11222:         my $line = $1;
                   11223:         my ($host,$protocol) = split(/:/,$line);
                   11224:         if ($protocol ne 'https') {
                   11225:             $protocol = 'http';
                   11226:         }
                   11227: 	$alldns{$host} = $protocol;
1.869     albertel 11228:     }
                   11229:     while (%alldns) {
                   11230: 	my ($dns) = keys(%alldns);
1.852     albertel 11231: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11232:         $ua->timeout(30);
1.979     raeburn  11233: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11234: 	my $response=$ua->request($request);
1.979     raeburn  11235:         delete($alldns{$dns});
1.852     albertel 11236: 	next if ($response->is_error());
                   11237: 	my @content = split("\n",$response->content);
1.869     albertel 11238: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 11239: 	&$func(\@content);
1.869     albertel 11240: 	return;
1.852     albertel 11241:     }
                   11242:     close($config);
1.871     albertel 11243:     my $which = (split('/',$url))[3];
                   11244:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11245:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11246:     my @content = <$config>;
                   11247:     &$func(\@content);
                   11248:     return;
1.852     albertel 11249: }
1.327     albertel 11250: # ------------------------------------------------------------ Read domain file
                   11251: {
1.852     albertel 11252:     my $loaded;
1.846     albertel 11253:     my %domain;
                   11254: 
1.852     albertel 11255:     sub parse_domain_tab {
                   11256: 	my ($lines) = @_;
                   11257: 	foreach my $line (@$lines) {
                   11258: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11259: 
1.846     albertel 11260: 	    chomp($line);
1.852     albertel 11261: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11262: 	    my %this_domain;
                   11263: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11264: 			       'lang_def', 'city', 'longi', 'lati',
                   11265: 			       'primary') {
                   11266: 		$this_domain{$field} = shift(@elements);
                   11267: 	    }
                   11268: 	    $domain{$name} = \%this_domain;
1.852     albertel 11269: 	}
                   11270:     }
1.864     albertel 11271: 
                   11272:     sub reset_domain_info {
                   11273: 	undef($loaded);
                   11274: 	undef(%domain);
                   11275:     }
                   11276: 
1.852     albertel 11277:     sub load_domain_tab {
1.869     albertel 11278: 	my ($ignore_cache) = @_;
                   11279: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11280: 	my $fh;
                   11281: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11282: 	    my @lines = <$fh>;
                   11283: 	    &parse_domain_tab(\@lines);
1.448     albertel 11284: 	}
1.852     albertel 11285: 	close($fh);
                   11286: 	$loaded = 1;
1.327     albertel 11287:     }
1.846     albertel 11288: 
                   11289:     sub domain {
1.852     albertel 11290: 	&load_domain_tab() if (!$loaded);
                   11291: 
1.846     albertel 11292: 	my ($name,$what) = @_;
                   11293: 	return if ( !exists($domain{$name}) );
                   11294: 
                   11295: 	if (!$what) {
                   11296: 	    return $domain{$name}{'description'};
                   11297: 	}
                   11298: 	return $domain{$name}{$what};
                   11299:     }
1.974     raeburn  11300: 
                   11301:     sub domain_info {
                   11302:         &load_domain_tab() if (!$loaded);
                   11303:         return %domain;
                   11304:     }
                   11305: 
1.327     albertel 11306: }
                   11307: 
                   11308: 
1.1       albertel 11309: # ------------------------------------------------------------- Read hosts file
                   11310: {
1.838     albertel 11311:     my %hostname;
1.844     albertel 11312:     my %hostdom;
1.845     albertel 11313:     my %libserv;
1.852     albertel 11314:     my $loaded;
1.888     albertel 11315:     my %name_to_host;
1.1074    raeburn  11316:     my %internetdom;
1.1107    raeburn  11317:     my %LC_dns_serv;
1.852     albertel 11318: 
                   11319:     sub parse_hosts_tab {
                   11320: 	my ($file) = @_;
                   11321: 	foreach my $configline (@$file) {
                   11322: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11323:             chomp($configline);
                   11324: 	    if ($configline =~ /^\^/) {
                   11325:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11326:                     $LC_dns_serv{$1} = 1;
                   11327:                 }
                   11328:                 next;
                   11329:             }
1.1074    raeburn  11330: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11331: 	    $name=~s/\s//g;
                   11332: 	    if ($id && $domain && $role && $name) {
                   11333: 		$hostname{$id}=$name;
1.888     albertel 11334: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11335: 		$hostdom{$id}=$domain;
                   11336: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11337:                 if (defined($protocol)) {
                   11338:                     if ($protocol eq 'https') {
                   11339:                         $protocol{$id} = $protocol;
                   11340:                     } else {
                   11341:                         $protocol{$id} = 'http'; 
                   11342:                     }
1.968     raeburn  11343:                 } else {
1.969     raeburn  11344:                     $protocol{$id} = 'http';
1.968     raeburn  11345:                 }
1.1074    raeburn  11346:                 if (defined($intdom)) {
                   11347:                     $internetdom{$id} = $intdom;
                   11348:                 }
1.852     albertel 11349: 	    }
                   11350: 	}
                   11351:     }
1.864     albertel 11352:     
                   11353:     sub reset_hosts_info {
1.897     albertel 11354: 	&purge_remembered();
1.864     albertel 11355: 	&reset_domain_info();
                   11356: 	&reset_hosts_ip_info();
1.892     albertel 11357: 	undef(%name_to_host);
1.864     albertel 11358: 	undef(%hostname);
                   11359: 	undef(%hostdom);
                   11360: 	undef(%libserv);
                   11361: 	undef($loaded);
                   11362:     }
1.1       albertel 11363: 
1.852     albertel 11364:     sub load_hosts_tab {
1.869     albertel 11365: 	my ($ignore_cache) = @_;
                   11366: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11367: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11368: 	my @config = <$config>;
                   11369: 	&parse_hosts_tab(\@config);
                   11370: 	close($config);
                   11371: 	$loaded=1;
1.1       albertel 11372:     }
1.852     albertel 11373: 
1.838     albertel 11374:     sub hostname {
1.852     albertel 11375: 	&load_hosts_tab() if (!$loaded);
                   11376: 
1.838     albertel 11377: 	my ($lonid) = @_;
                   11378: 	return $hostname{$lonid};
                   11379:     }
1.845     albertel 11380: 
1.838     albertel 11381:     sub all_hostnames {
1.852     albertel 11382: 	&load_hosts_tab() if (!$loaded);
                   11383: 
1.838     albertel 11384: 	return %hostname;
                   11385:     }
1.845     albertel 11386: 
1.888     albertel 11387:     sub all_names {
                   11388: 	&load_hosts_tab() if (!$loaded);
                   11389: 
                   11390: 	return %name_to_host;
                   11391:     }
                   11392: 
1.974     raeburn  11393:     sub all_host_domain {
                   11394:         &load_hosts_tab() if (!$loaded);
                   11395:         return %hostdom;
                   11396:     }
                   11397: 
1.845     albertel 11398:     sub is_library {
1.852     albertel 11399: 	&load_hosts_tab() if (!$loaded);
                   11400: 
1.845     albertel 11401: 	return exists($libserv{$_[0]});
                   11402:     }
                   11403: 
                   11404:     sub all_library {
1.852     albertel 11405: 	&load_hosts_tab() if (!$loaded);
                   11406: 
1.845     albertel 11407: 	return %libserv;
                   11408:     }
                   11409: 
1.1062    droeschl 11410:     sub unique_library {
                   11411: 	#2x reverse removes all hostnames that appear more than once
                   11412:         my %unique = reverse &all_library();
                   11413:         return reverse %unique;
                   11414:     }
                   11415: 
1.841     albertel 11416:     sub get_servers {
1.852     albertel 11417: 	&load_hosts_tab() if (!$loaded);
                   11418: 
1.841     albertel 11419: 	my ($domain,$type) = @_;
                   11420: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11421: 	                                          : %hostname;
                   11422: 	my %result;
1.842     albertel 11423: 	if (ref($domain) eq 'ARRAY') {
                   11424: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11425: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11426: 		    $result{$host} = $hostname;
                   11427: 		}
                   11428: 	    }
                   11429: 	} else {
                   11430: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11431: 		if ($hostdom{$host} eq $domain) {
                   11432: 		    $result{$host} = $hostname;
                   11433: 		}
1.841     albertel 11434: 	    }
                   11435: 	}
                   11436: 	return %result;
                   11437:     }
1.845     albertel 11438: 
1.1062    droeschl 11439:     sub get_unique_servers {
                   11440:         my %unique = reverse &get_servers(@_);
                   11441: 	return reverse %unique;
                   11442:     }
                   11443: 
1.844     albertel 11444:     sub host_domain {
1.852     albertel 11445: 	&load_hosts_tab() if (!$loaded);
                   11446: 
1.844     albertel 11447: 	my ($lonid) = @_;
                   11448: 	return $hostdom{$lonid};
                   11449:     }
                   11450: 
1.841     albertel 11451:     sub all_domains {
1.852     albertel 11452: 	&load_hosts_tab() if (!$loaded);
                   11453: 
1.841     albertel 11454: 	my %seen;
                   11455: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11456: 	return @uniq;
                   11457:     }
1.1074    raeburn  11458: 
                   11459:     sub internet_dom {
                   11460:         &load_hosts_tab() if (!$loaded);
                   11461: 
                   11462:         my ($lonid) = @_;
                   11463:         return $internetdom{$lonid};
                   11464:     }
1.1107    raeburn  11465: 
                   11466:     sub is_LC_dns {
                   11467:         &load_hosts_tab() if (!$loaded);
                   11468: 
                   11469:         my ($hostname) = @_;
                   11470:         return exists($LC_dns_serv{$hostname});
                   11471:     }
                   11472: 
1.1       albertel 11473: }
                   11474: 
1.847     albertel 11475: { 
                   11476:     my %iphost;
1.856     albertel 11477:     my %name_to_ip;
                   11478:     my %lonid_to_ip;
1.869     albertel 11479: 
1.847     albertel 11480:     sub get_hosts_from_ip {
                   11481: 	my ($ip) = @_;
                   11482: 	my %iphosts = &get_iphost();
                   11483: 	if (ref($iphosts{$ip})) {
                   11484: 	    return @{$iphosts{$ip}};
                   11485: 	}
                   11486: 	return;
1.839     albertel 11487:     }
1.864     albertel 11488:     
                   11489:     sub reset_hosts_ip_info {
                   11490: 	undef(%iphost);
                   11491: 	undef(%name_to_ip);
                   11492: 	undef(%lonid_to_ip);
                   11493:     }
1.856     albertel 11494: 
                   11495:     sub get_host_ip {
                   11496: 	my ($lonid) = @_;
                   11497: 	if (exists($lonid_to_ip{$lonid})) {
                   11498: 	    return $lonid_to_ip{$lonid};
                   11499: 	}
                   11500: 	my $name=&hostname($lonid);
                   11501:    	my $ip = gethostbyname($name);
                   11502: 	return if (!$ip || length($ip) ne 4);
                   11503: 	$ip=inet_ntoa($ip);
                   11504: 	$name_to_ip{$name}   = $ip;
                   11505: 	$lonid_to_ip{$lonid} = $ip;
                   11506: 	return $ip;
                   11507:     }
1.847     albertel 11508:     
                   11509:     sub get_iphost {
1.869     albertel 11510: 	my ($ignore_cache) = @_;
1.894     albertel 11511: 
1.869     albertel 11512: 	if (!$ignore_cache) {
                   11513: 	    if (%iphost) {
                   11514: 		return %iphost;
                   11515: 	    }
                   11516: 	    my ($ip_info,$cached)=
                   11517: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11518: 	    if ($cached) {
                   11519: 		%iphost      = %{$ip_info->[0]};
                   11520: 		%name_to_ip  = %{$ip_info->[1]};
                   11521: 		%lonid_to_ip = %{$ip_info->[2]};
                   11522: 		return %iphost;
                   11523: 	    }
                   11524: 	}
1.894     albertel 11525: 
                   11526: 	# get yesterday's info for fallback
                   11527: 	my %old_name_to_ip;
                   11528: 	my ($ip_info,$cached)=
                   11529: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11530: 	if ($cached) {
                   11531: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11532: 	}
                   11533: 
1.888     albertel 11534: 	my %name_to_host = &all_names();
                   11535: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11536: 	    my $ip;
                   11537: 	    if (!exists($name_to_ip{$name})) {
                   11538: 		$ip = gethostbyname($name);
                   11539: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11540: 		    if (defined($old_name_to_ip{$name})) {
                   11541: 			$ip = $old_name_to_ip{$name};
                   11542: 			&logthis("Can't find $name defaulting to old $ip");
                   11543: 		    } else {
                   11544: 			&logthis("Name $name no IP found");
                   11545: 			next;
                   11546: 		    }
                   11547: 		} else {
                   11548: 		    $ip=inet_ntoa($ip);
1.847     albertel 11549: 		}
                   11550: 		$name_to_ip{$name} = $ip;
                   11551: 	    } else {
                   11552: 		$ip = $name_to_ip{$name};
1.653     albertel 11553: 	    }
1.888     albertel 11554: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11555: 		$lonid_to_ip{$id} = $ip;
                   11556: 	    }
                   11557: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11558: 	}
1.869     albertel 11559: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11560: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11561: 				      48*60*60);
1.869     albertel 11562: 
1.847     albertel 11563: 	return %iphost;
1.598     albertel 11564:     }
                   11565: 
1.992     raeburn  11566:     #
                   11567:     #  Given a DNS returns the loncapa host name for that DNS 
                   11568:     # 
                   11569:     sub host_from_dns {
                   11570:         my ($dns) = @_;
                   11571:         my @hosts;
                   11572:         my $ip;
                   11573: 
1.993     raeburn  11574:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11575:             $ip = $name_to_ip{$dns};
                   11576:         }
                   11577:         if (!$ip) {
                   11578:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11579:             if (length($ip) == 4) { 
                   11580: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11581:             }
                   11582:         }
                   11583:         if ($ip) {
                   11584: 	    @hosts = get_hosts_from_ip($ip);
                   11585: 	    return $hosts[0];
                   11586:         }
                   11587:         return undef;
1.986     foxr     11588:     }
1.992     raeburn  11589: 
1.1074    raeburn  11590:     sub get_internet_names {
                   11591:         my ($lonid) = @_;
                   11592:         return if ($lonid eq '');
                   11593:         my ($idnref,$cached)=
                   11594:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11595:         if ($cached) {
                   11596:             return $idnref;
                   11597:         }
                   11598:         my $ip = &get_host_ip($lonid);
                   11599:         my @hosts = &get_hosts_from_ip($ip);
                   11600:         my %iphost = &get_iphost();
                   11601:         my (@idns,%seen);
                   11602:         foreach my $id (@hosts) {
                   11603:             my $dom = &host_domain($id);
                   11604:             my $prim_id = &domain($dom,'primary');
                   11605:             my $prim_ip = &get_host_ip($prim_id);
                   11606:             next if ($seen{$prim_ip});
                   11607:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11608:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11609:                     my $intdom = &internet_dom($id);
                   11610:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11611:                         push(@idns,$intdom);
                   11612:                     }
                   11613:                 }
                   11614:             }
                   11615:             $seen{$prim_ip} = 1;
                   11616:         }
                   11617:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11618:     }
                   11619: 
1.986     foxr     11620: }
                   11621: 
1.1079    raeburn  11622: sub all_loncaparevs {
                   11623:     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);
                   11624: }
                   11625: 
1.862     albertel 11626: BEGIN {
                   11627: 
                   11628: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11629:     unless ($readit) {
                   11630: {
                   11631:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11632:     %perlvar = (%perlvar,%{$configvars});
                   11633: }
                   11634: 
                   11635: 
1.1       albertel 11636: # ------------------------------------------------------ Read spare server file
                   11637: {
1.448     albertel 11638:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11639: 
                   11640:     while (my $configline=<$config>) {
                   11641:        chomp($configline);
1.284     matthew  11642:        if ($configline) {
1.784     albertel 11643: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11644: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11645: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11646:        }
                   11647:     }
1.448     albertel 11648:     close($config);
1.1       albertel 11649: }
1.11      www      11650: # ------------------------------------------------------------ Read permissions
                   11651: {
1.448     albertel 11652:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11653: 
                   11654:     while (my $configline=<$config>) {
1.448     albertel 11655: 	chomp($configline);
                   11656: 	if ($configline) {
                   11657: 	    my ($role,$perm)=split(/ /,$configline);
                   11658: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11659: 	}
1.11      www      11660:     }
1.448     albertel 11661:     close($config);
1.11      www      11662: }
                   11663: 
                   11664: # -------------------------------------------- Read plain texts for permissions
                   11665: {
1.448     albertel 11666:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11667: 
                   11668:     while (my $configline=<$config>) {
1.448     albertel 11669: 	chomp($configline);
                   11670: 	if ($configline) {
1.742     raeburn  11671: 	    my ($short,@plain)=split(/:/,$configline);
                   11672:             %{$prp{$short}} = ();
                   11673: 	    if (@plain > 0) {
                   11674:                 $prp{$short}{'std'} = $plain[0];
                   11675:                 for (my $i=1; $i<@plain; $i++) {
                   11676:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11677:                 }
                   11678:             }
1.448     albertel 11679: 	}
1.135     www      11680:     }
1.448     albertel 11681:     close($config);
1.135     www      11682: }
                   11683: 
                   11684: # ---------------------------------------------------------- Read package table
                   11685: {
1.448     albertel 11686:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11687: 
                   11688:     while (my $configline=<$config>) {
1.483     albertel 11689: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11690: 	chomp($configline);
                   11691: 	my ($short,$plain)=split(/:/,$configline);
                   11692: 	my ($pack,$name)=split(/\&/,$short);
                   11693: 	if ($plain ne '') {
                   11694: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11695: 	    $packagetab{$short}=$plain; 
                   11696: 	}
1.11      www      11697:     }
1.448     albertel 11698:     close($config);
1.329     matthew  11699: }
                   11700: 
1.1073    raeburn  11701: # ---------------------------------------------------------- Read loncaparev table
                   11702: {
                   11703:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11704:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11705:             while (my $configline=<$config>) {
                   11706:                 chomp($configline);
                   11707:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11708:                 $loncaparevs{$hostid}=$loncaparev;
                   11709:             }
                   11710:             close($config);
                   11711:         }
                   11712:     }
                   11713: }
                   11714: 
1.1074    raeburn  11715: # ---------------------------------------------------------- Read serverhostID table
                   11716: {
                   11717:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11718:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11719:             while (my $configline=<$config>) {
                   11720:                 chomp($configline);
                   11721:                 my ($name,$id)=split(/:/,$configline);
                   11722:                 $serverhomeIDs{$name}=$id;
                   11723:             }
                   11724:             close($config);
                   11725:         }
                   11726:     }
                   11727: }
                   11728: 
1.1079    raeburn  11729: {
                   11730:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11731:     if (-e $file) {
                   11732:         my $parser = HTML::LCParser->new($file);
                   11733:         while (my $token = $parser->get_token()) {
                   11734:             if ($token->[0] eq 'S') {
                   11735:                 my $item = $token->[1];
                   11736:                 my $name = $token->[2]{'name'};
                   11737:                 my $value = $token->[2]{'value'};
                   11738:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11739:                     my $release = $parser->get_text();
                   11740:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11741:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11742:                 }
                   11743:             }
                   11744:         }
                   11745:     }
1.1073    raeburn  11746: }
                   11747: 
1.1138    raeburn  11748: # ---------------------------------------------------------- Read managers table
                   11749: {
                   11750:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11751:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11752:             while (my $configline=<$config>) {
                   11753:                 chomp($configline);
                   11754:                 next if ($configline =~ /^\#/);
                   11755:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11756:                     $managerstab{$configline} = 1;
                   11757:                 }
                   11758:             }
                   11759:             close($config);
                   11760:         }
                   11761:     }
                   11762: }
                   11763: 
1.329     matthew  11764: # ------------- set up temporary directory
                   11765: {
1.1117    foxr     11766:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11767: 
1.11      www      11768: }
                   11769: 
1.794     albertel 11770: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11771: 				'compress_threshold'=> 20_000,
                   11772:  			        });
1.185     www      11773: 
1.281     www      11774: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11775: $dumpcount=0;
1.958     www      11776: $locknum=0;
1.22      www      11777: 
1.163     harris41 11778: &logtouch();
1.672     albertel 11779: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11780: $readit=1;
1.564     albertel 11781:     {
                   11782: 	use integer;
                   11783: 	my $test=(2**32)+1;
1.568     albertel 11784: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11785: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11786:     }
1.195     www      11787: }
1.1       albertel 11788: }
1.179     www      11789: 
1.1       albertel 11790: 1;
1.191     harris41 11791: __END__
                   11792: 
1.243     albertel 11793: =pod
                   11794: 
1.191     harris41 11795: =head1 NAME
                   11796: 
1.243     albertel 11797: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11798: 
                   11799: =head1 SYNOPSIS
                   11800: 
1.243     albertel 11801: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11802: 
                   11803:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11804: 
1.243     albertel 11805: Common parameters:
                   11806: 
                   11807: =over 4
                   11808: 
                   11809: =item *
                   11810: 
                   11811: $uname : an internal username (if $cname expecting a course Id specifically)
                   11812: 
                   11813: =item *
                   11814: 
                   11815: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11816: 
                   11817: =item *
                   11818: 
                   11819: $symb : a resource instance identifier
                   11820: 
                   11821: =item *
                   11822: 
                   11823: $namespace : the name of a .db file that contains the data needed or
                   11824: being set.
                   11825: 
                   11826: =back
                   11827: 
1.394     bowersj2 11828: =head1 OVERVIEW
1.191     harris41 11829: 
1.394     bowersj2 11830: lonnet provides subroutines which interact with the
                   11831: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11832: about classes, users, and resources.
1.243     albertel 11833: 
                   11834: For many of these objects you can also use this to store data about
                   11835: them or modify them in various ways.
1.191     harris41 11836: 
1.394     bowersj2 11837: =head2 Symbs
1.191     harris41 11838: 
1.394     bowersj2 11839: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11840: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11841: map, the resource number of the resource in the map, and the URL of
                   11842: the resource itself. The latter is somewhat redundant, but might help
                   11843: if maps change.
                   11844: 
                   11845: An example is
                   11846: 
                   11847:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11848: 
                   11849: The respective map entry is
                   11850: 
                   11851:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11852:   title="Problem 2">
                   11853:  </resource>
                   11854: 
                   11855: Symbs are used by the random number generator, as well as to store and
                   11856: restore data specific to a certain instance of for example a problem.
                   11857: 
                   11858: =head2 Storing And Retrieving Data
                   11859: 
                   11860: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11861: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11862: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11863: is is the non-critical message twin of cstore. These functions are for
                   11864: handlers to store a perl hash to a user's permanent data space in an
                   11865: easy manner, and to retrieve it again on another call. It is expected
                   11866: that a handler would use this once at the beginning to retrieve data,
                   11867: and then again once at the end to send only the new data back.
                   11868: 
                   11869: The data is stored in the user's data directory on the user's
                   11870: homeserver under the ID of the course.
                   11871: 
                   11872: The hash that is returned by restore will have all of the previous
                   11873: value for all of the elements of the hash.
                   11874: 
                   11875: Example:
                   11876: 
                   11877:  #creating a hash
                   11878:  my %hash;
                   11879:  $hash{'foo'}='bar';
                   11880: 
                   11881:  #storing it
                   11882:  &Apache::lonnet::cstore(\%hash);
                   11883: 
                   11884:  #changing a value
                   11885:  $hash{'foo'}='notbar';
                   11886: 
                   11887:  #adding a new value
                   11888:  $hash{'bar'}='foo';
                   11889:  &Apache::lonnet::cstore(\%hash);
                   11890: 
                   11891:  #retrieving the hash
                   11892:  my %history=&Apache::lonnet::restore();
                   11893: 
                   11894:  #print the hash
                   11895:  foreach my $key (sort(keys(%history))) {
                   11896:    print("\%history{$key} = $history{$key}");
                   11897:  }
                   11898: 
                   11899: Will print out:
1.191     harris41 11900: 
1.394     bowersj2 11901:  %history{1:foo} = bar
                   11902:  %history{1:keys} = foo:timestamp
                   11903:  %history{1:timestamp} = 990455579
                   11904:  %history{2:bar} = foo
                   11905:  %history{2:foo} = notbar
                   11906:  %history{2:keys} = foo:bar:timestamp
                   11907:  %history{2:timestamp} = 990455580
                   11908:  %history{bar} = foo
                   11909:  %history{foo} = notbar
                   11910:  %history{timestamp} = 990455580
                   11911:  %history{version} = 2
                   11912: 
                   11913: Note that the special hash entries C<keys>, C<version> and
                   11914: C<timestamp> were added to the hash. C<version> will be equal to the
                   11915: total number of versions of the data that have been stored. The
                   11916: C<timestamp> attribute will be the UNIX time the hash was
                   11917: stored. C<keys> is available in every historical section to list which
                   11918: keys were added or changed at a specific historical revision of a
                   11919: hash.
                   11920: 
                   11921: B<Warning>: do not store the hash that restore returns directly. This
                   11922: will cause a mess since it will restore the historical keys as if the
                   11923: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11924: 
1.394     bowersj2 11925: Calling convention:
1.191     harris41 11926: 
1.394     bowersj2 11927:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11928:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11929: 
1.394     bowersj2 11930: For more detailed information, see lonnet specific documentation.
1.191     harris41 11931: 
1.394     bowersj2 11932: =head1 RETURN MESSAGES
1.191     harris41 11933: 
1.394     bowersj2 11934: =over 4
1.191     harris41 11935: 
1.394     bowersj2 11936: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11937: 
1.394     bowersj2 11938: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11939: when the connection is brought back up
1.191     harris41 11940: 
1.394     bowersj2 11941: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11942: for later delivery
1.191     harris41 11943: 
1.967     bisitz   11944: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11945: 
1.394     bowersj2 11946: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11947: that was requested
1.191     harris41 11948: 
1.243     albertel 11949: =back
1.191     harris41 11950: 
1.243     albertel 11951: =head1 PUBLIC SUBROUTINES
1.191     harris41 11952: 
1.243     albertel 11953: =head2 Session Environment Functions
1.191     harris41 11954: 
1.243     albertel 11955: =over 4
1.191     harris41 11956: 
1.394     bowersj2 11957: =item * 
                   11958: X<appenv()>
1.949     raeburn  11959: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11960: the user envirnoment file, and will be restored for each access this
1.620     albertel 11961: user makes during this session, also modifies the %env for the current
1.949     raeburn  11962: process. Optional rolesarrayref - if defined contains a reference to an array
                   11963: of roles which are exempt from the restriction on modifying user.role entries 
                   11964: in the user's environment.db and in %env.    
1.191     harris41 11965: 
                   11966: =item *
1.394     bowersj2 11967: X<delenv()>
1.987     raeburn  11968: B<delenv($delthis,$regexp)>: removes all items from the session
                   11969: environment file that begin with $delthis. If the 
                   11970: optional second arg - $regexp - is true, $delthis is treated as a 
                   11971: regular expression, otherwise \Q$delthis\E is used. 
                   11972: The values are also deleted from the current processes %env.
1.191     harris41 11973: 
1.795     albertel 11974: =item * get_env_multiple($name) 
                   11975: 
                   11976: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11977: values may be defined and end up as an array ref.
                   11978: 
                   11979: returns an array of values
                   11980: 
1.243     albertel 11981: =back
                   11982: 
                   11983: =head2 User Information
1.191     harris41 11984: 
1.243     albertel 11985: =over 4
1.191     harris41 11986: 
                   11987: =item *
1.394     bowersj2 11988: X<queryauthenticate()>
                   11989: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11990: authentication scheme
                   11991: 
                   11992: =item *
1.394     bowersj2 11993: X<authenticate()>
1.1073    raeburn  11994: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11995: authenticate user from domain's lib servers (first use the current
                   11996: one). C<$upass> should be the users password.
1.1073    raeburn  11997: $checkdefauth is optional (value is 1 if a check should be made to
                   11998:    authenticate user using default authentication method, and allow
                   11999:    account creation if username does not have account in the domain).
                   12000: $clientcancheckhost is optional (value is 1 if checking whether the
                   12001:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12002: 
                   12003: =item *
1.394     bowersj2 12004: X<homeserver()>
                   12005: B<homeserver($uname,$udom)>: find the server which has
                   12006: the user's directory and files (there must be only one), this caches
                   12007: the answer, and also caches if there is a borken connection.
1.191     harris41 12008: 
                   12009: =item *
1.394     bowersj2 12010: X<idget()>
                   12011: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12012: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12013: username, and only 1 username per ID in a specific domain) (returns
                   12014: hash: id=>name,id=>name)
1.191     harris41 12015: 
                   12016: =item *
1.394     bowersj2 12017: X<idrget()>
                   12018: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12019: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12020: 
                   12021: =item *
1.394     bowersj2 12022: X<idput()>
                   12023: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12024: 
                   12025: =item *
1.394     bowersj2 12026: X<rolesinit()>
1.1169    droeschl 12027: B<rolesinit($udom,$username)>: get user privileges.
                   12028: returns user role, first access and timer interval hashes
1.243     albertel 12029: 
                   12030: =item *
1.1171    droeschl 12031: X<privileged()>
                   12032: B<privileged($username,$domain)>: returns a true if user has a
                   12033: privileged and active role (i.e. su or dc), false otherwise.
                   12034: 
                   12035: =item *
1.551     albertel 12036: X<getsection()>
                   12037: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12038: course $cname, return section name/number or '' for "not in course"
                   12039: and '-1' for "no section"
                   12040: 
                   12041: =item *
1.394     bowersj2 12042: X<userenvironment()>
                   12043: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12044: passed in @what from the requested user's environment, returns a hash
                   12045: 
1.858     raeburn  12046: =item * 
                   12047: X<userlog_query()>
1.859     albertel 12048: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12049: activity.log file. %filters defines filters applied when parsing the
                   12050: log file. These can be start or end timestamps, or the type of action
                   12051: - log to look for Login or Logout events, check for Checkin or
                   12052: Checkout, role for role selection. The response is in the form
                   12053: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12054: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12055: 
1.243     albertel 12056: =back
                   12057: 
                   12058: =head2 User Roles
                   12059: 
                   12060: =over 4
                   12061: 
                   12062: =item *
                   12063: 
1.810     raeburn  12064: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12065:  F: full access
                   12066:  U,I,K: authentication modes (cxx only)
                   12067:  '': forbidden
                   12068:  1: user needs to choose course
                   12069:  2: browse allowed
1.766     albertel 12070:  A: passphrase authentication needed
1.243     albertel 12071: 
                   12072: =item *
                   12073: 
1.1192    raeburn  12074: constructaccess($url,$setpriv) : check for access to construction space URL
                   12075: 
                   12076: See if the owner domain and name in the URL match those in the
                   12077: expected environment.  If so, return three element list
                   12078: ($ownername,$ownerdomain,$ownerhome).
                   12079: 
                   12080: Otherwise return the null string.
                   12081: 
                   12082: If second argument 'setpriv' is true, it assigns the privileges,
                   12083: and returns the same three element list, unless the owner has
                   12084: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12085: in which case the null string is returned.
                   12086: 
                   12087: =item *
                   12088: 
1.243     albertel 12089: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12090: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12091: and course level
                   12092: 
                   12093: =item *
                   12094: 
1.988     raeburn  12095: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12096: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12097: $type is Course (default) or Community.
1.988     raeburn  12098: If $forcedefault evaluates to true, text returned will be default 
                   12099: text for $type. Otherwise, if this is a course, the text returned 
                   12100: will be a custom name for the role (if defined in the course's 
                   12101: environment).  If no custom name is defined the default is returned.
                   12102:    
1.832     raeburn  12103: =item *
                   12104: 
1.935     raeburn  12105: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12106: All arguments are optional. Returns a hash of a roles, either for
                   12107: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12108: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12109: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12110: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12111: For each key, value is set to colon-separated start and end times for
                   12112: the role.  If no username and domain are specified, will default to
1.934     raeburn  12113: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12114: of role statuses (active, future or previous), roles 
                   12115: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12116: to restrict the list of roles reported. If no array ref is 
                   12117: provided for types, will default to return only active roles.
1.834     albertel 12118: 
1.243     albertel 12119: =back
                   12120: 
                   12121: =head2 User Modification
                   12122: 
                   12123: =over 4
                   12124: 
                   12125: =item *
                   12126: 
1.957     raeburn  12127: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12128: user for the level given by URL.  Optional start and end dates (leave empty
                   12129: string or zero for "no date")
1.191     harris41 12130: 
                   12131: =item *
                   12132: 
1.243     albertel 12133: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12134: change a users, password, possible return values are: ok,
                   12135: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12136: refused
1.191     harris41 12137: 
                   12138: =item *
                   12139: 
1.243     albertel 12140: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12141: 
                   12142: =item *
                   12143: 
1.1058    raeburn  12144: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12145:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12146: 
                   12147: will update user information (firstname,middlename,lastname,generation,
                   12148: permanentemail), and if forceid is true, student/employee ID also.
                   12149: A user's institutional affiliation(s) can also be updated.
                   12150: User information fields will not be overwritten with empty entries 
                   12151: unless the field is included in the $candelete array reference.
                   12152: This array is included when a single user is modified via "Manage Users",
                   12153: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12154: 
                   12155: =item *
                   12156: 
1.286     matthew  12157: modifystudent
                   12158: 
1.957     raeburn  12159: modify a student's enrollment and identification information.
1.286     matthew  12160: The course id is resolved based on the current users environment.  
                   12161: This means the envoking user must be a course coordinator or otherwise
                   12162: associated with a course.
                   12163: 
1.297     matthew  12164: This call is essentially a wrapper for lonnet::modifyuser and
                   12165: lonnet::modify_student_enrollment
1.286     matthew  12166: 
                   12167: Inputs: 
                   12168: 
                   12169: =over 4
                   12170: 
1.957     raeburn  12171: =item B<$udom> Student's loncapa domain
1.286     matthew  12172: 
1.957     raeburn  12173: =item B<$uname> Student's loncapa login name
1.286     matthew  12174: 
1.964     bisitz   12175: =item B<$uid> Student/Employee ID
1.286     matthew  12176: 
1.957     raeburn  12177: =item B<$umode> Student's authentication mode
1.286     matthew  12178: 
1.957     raeburn  12179: =item B<$upass> Student's password
1.286     matthew  12180: 
1.957     raeburn  12181: =item B<$first> Student's first name
1.286     matthew  12182: 
1.957     raeburn  12183: =item B<$middle> Student's middle name
1.286     matthew  12184: 
1.957     raeburn  12185: =item B<$last> Student's last name
1.286     matthew  12186: 
1.957     raeburn  12187: =item B<$gene> Student's generation
1.286     matthew  12188: 
1.957     raeburn  12189: =item B<$usec> Student's section in course
1.286     matthew  12190: 
                   12191: =item B<$end> Unix time of the roles expiration
                   12192: 
                   12193: =item B<$start> Unix time of the roles start date
                   12194: 
                   12195: =item B<$forceid> If defined, allow $uid to be changed
                   12196: 
                   12197: =item B<$desiredhome> server to use as home server for student
                   12198: 
1.957     raeburn  12199: =item B<$email> Student's permanent e-mail address
                   12200: 
                   12201: =item B<$type> Type of enrollment (auto or manual)
                   12202: 
1.963     raeburn  12203: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12204: 
                   12205: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12206: 
1.963     raeburn  12207: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12208: 
1.963     raeburn  12209: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12210: 
1.963     raeburn  12211: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  12212: 
1.286     matthew  12213: =back
1.297     matthew  12214: 
                   12215: =item *
                   12216: 
                   12217: modify_student_enrollment
                   12218: 
                   12219: Change a students enrollment status in a class.  The environment variable
                   12220: 'role.request.course' must be defined for this function to proceed.
                   12221: 
                   12222: Inputs:
                   12223: 
                   12224: =over 4
                   12225: 
                   12226: =item $udom, students domain
                   12227: 
                   12228: =item $uname, students name
                   12229: 
                   12230: =item $uid, students user id
                   12231: 
                   12232: =item $first, students first name
                   12233: 
                   12234: =item $middle
                   12235: 
                   12236: =item $last
                   12237: 
                   12238: =item $gene
                   12239: 
                   12240: =item $usec
                   12241: 
                   12242: =item $end
                   12243: 
                   12244: =item $start
                   12245: 
1.957     raeburn  12246: =item $type
                   12247: 
                   12248: =item $locktype
                   12249: 
                   12250: =item $cid
                   12251: 
                   12252: =item $selfenroll
                   12253: 
                   12254: =item $context
                   12255: 
1.297     matthew  12256: =back
                   12257: 
1.191     harris41 12258: 
                   12259: =item *
                   12260: 
1.243     albertel 12261: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12262: custom role; give a custom role to a user for the level given by URL.  Specify
                   12263: name and domain of role author, and role name
1.191     harris41 12264: 
                   12265: =item *
                   12266: 
1.243     albertel 12267: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12268: 
                   12269: =item *
                   12270: 
1.243     albertel 12271: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12272: 
                   12273: =back
                   12274: 
                   12275: =head2 Course Infomation
                   12276: 
                   12277: =over 4
1.191     harris41 12278: 
                   12279: =item *
                   12280: 
1.1118    foxr     12281: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12282: specified course id, including all environment settings for the
                   12283: course, the description of the course will be in the hash under the
                   12284: key 'description'
1.191     harris41 12285: 
1.1118    foxr     12286: $options is an optional parameter that if supplied is a hash reference that controls
                   12287: what how this function works.  It has the following key/values:
                   12288: 
                   12289: =over 4
                   12290: 
                   12291: =item freshen_cache
                   12292: 
                   12293: If defined, and the environment cache for the course is valid, it is 
                   12294: returned in the returned hash.
                   12295: 
                   12296: =item one_time
                   12297: 
                   12298: If defined, the last cache time is set to _now_
                   12299: 
                   12300: =item user
                   12301: 
                   12302: If defined, the supplied username is used instead of the current user.
                   12303: 
                   12304: 
                   12305: =back
                   12306: 
1.191     harris41 12307: =item *
                   12308: 
1.624     albertel 12309: resdata($name,$domain,$type,@which) : request for current parameter
                   12310: setting for a specific $type, where $type is either 'course' or 'user',
                   12311: @what should be a list of parameters to ask about. This routine caches
                   12312: answers for 5 minutes.
1.243     albertel 12313: 
1.877     foxr     12314: =item *
                   12315: 
                   12316: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12317: data base, returning a hash that is keyed by the resource name and has
                   12318: values that are the resource value.  I believe that the timestamps and
                   12319: versions are also returned.
                   12320: 
                   12321: 
1.243     albertel 12322: =back
                   12323: 
                   12324: =head2 Course Modification
                   12325: 
                   12326: =over 4
1.191     harris41 12327: 
                   12328: =item *
                   12329: 
1.243     albertel 12330: writecoursepref($courseid,%prefs) : write preferences (environment
                   12331: database) for a course
1.191     harris41 12332: 
                   12333: =item *
                   12334: 
1.1011    raeburn  12335: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12336: 
                   12337: =item *
                   12338: 
1.1038    raeburn  12339: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12340: 
1.1167    droeschl 12341: =item *
                   12342: 
                   12343: is_course($courseid), is_course($cdom, $cnum)
                   12344: 
                   12345: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12346: two component version $cdom, $cnum. It checks if the specified course exists.
                   12347: 
                   12348: Returns:
                   12349:     undef if the course doesn't exist, otherwise
                   12350:     in scalar context the combined courseid.
                   12351:     in list context the two components of the course identifier, domain and 
                   12352:     courseid.    
                   12353: 
1.243     albertel 12354: =back
                   12355: 
                   12356: =head2 Resource Subroutines
                   12357: 
                   12358: =over 4
1.191     harris41 12359: 
                   12360: =item *
                   12361: 
1.243     albertel 12362: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12363: 
                   12364: =item *
                   12365: 
1.243     albertel 12366: repcopy($filename) : subscribes to the requested file, and attempts to
                   12367: replicate from the owning library server, Might return
1.607     raeburn  12368: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12369: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12370: resource. Expects the local filesystem pathname
                   12371: (/home/httpd/html/res/....)
                   12372: 
                   12373: =back
                   12374: 
                   12375: =head2 Resource Information
                   12376: 
                   12377: =over 4
1.191     harris41 12378: 
                   12379: =item *
                   12380: 
1.243     albertel 12381: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12382: a vairety of different possible values, $varname should be a request
                   12383: string, and the other parameters can be used to specify who and what
                   12384: one is asking about.
                   12385: 
                   12386: Possible values for $varname are environment.lastname (or other item
                   12387: from the envirnment hash), user.name (or someother aspect about the
                   12388: user), resource.0.maxtries (or some other part and parameter of a
                   12389: resource)
1.204     albertel 12390: 
                   12391: =item *
                   12392: 
1.243     albertel 12393: directcondval($number) : get current value of a condition; reads from a state
                   12394: string
1.204     albertel 12395: 
                   12396: =item *
                   12397: 
1.243     albertel 12398: condval($condidx) : value of condition index based on state
1.204     albertel 12399: 
                   12400: =item *
                   12401: 
1.243     albertel 12402: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12403: resource's metadata, $what should be either a specific key, or either
                   12404: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12405: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12406: 
                   12407: this function automatically caches all requests
1.191     harris41 12408: 
                   12409: =item *
                   12410: 
1.243     albertel 12411: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12412: network of library servers; returns file handle of where SQL and regex results
                   12413: will be stored for query
1.191     harris41 12414: 
                   12415: =item *
                   12416: 
1.243     albertel 12417: symbread($filename) : return symbolic list entry (filename argument optional);
                   12418: returns the data handle
1.191     harris41 12419: 
                   12420: =item *
                   12421: 
1.1190    raeburn  12422: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12423: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12424: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12425: on failure, user must be in a course, as it assumes the existence of
                   12426: the course initial hash, and uses $env('request.course.id'}.  The third
                   12427: arg is an optional reference to a scalar.  If this arg is passed in the 
                   12428: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12429: encrypted; otherwise it will be null.  
1.191     harris41 12430: 
                   12431: =item *
                   12432: 
1.243     albertel 12433: symbclean($symb) : removes versions numbers from a symb, returns the
                   12434: cleaned symb
1.191     harris41 12435: 
                   12436: =item *
                   12437: 
1.243     albertel 12438: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12439: course map, user must be in a course for it to work.
1.191     harris41 12440: 
                   12441: =item *
                   12442: 
1.243     albertel 12443: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12444: 
                   12445: =item *
                   12446: 
1.243     albertel 12447: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12448: a random seed, all arguments are optional, if they aren't sent it uses the
                   12449: environment to derive them. Note: if symb isn't sent and it can't get one
                   12450: from &symbread it will use the current time as its return value
1.191     harris41 12451: 
                   12452: =item *
                   12453: 
1.243     albertel 12454: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12455: unfakeable, receipt
1.191     harris41 12456: 
                   12457: =item *
                   12458: 
1.620     albertel 12459: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12460: 
                   12461: =item *
                   12462: 
1.243     albertel 12463: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12464: 
                   12465: =item *
                   12466: 
1.243     albertel 12467: 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 12468: 
                   12469: =item *
                   12470: 
1.243     albertel 12471: 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 12472: 
                   12473: =item *
                   12474: 
1.243     albertel 12475: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12476: 
                   12477: =item *
                   12478: 
1.243     albertel 12479: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12480: forcing spreadsheet to reevaluate the resource scores next time.
                   12481: 
                   12482: =back
                   12483: 
                   12484: =head2 Storing/Retreiving Data
                   12485: 
                   12486: =over 4
1.191     harris41 12487: 
                   12488: =item *
                   12489: 
1.243     albertel 12490: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12491: for this url; hashref needs to be given and should be a \%hashname; the
                   12492: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12493: be derived from the env
1.191     harris41 12494: 
                   12495: =item *
                   12496: 
1.243     albertel 12497: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12498: uses critical subroutine
1.191     harris41 12499: 
                   12500: =item *
                   12501: 
1.243     albertel 12502: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12503: all args are optional
1.191     harris41 12504: 
                   12505: =item *
                   12506: 
1.717     albertel 12507: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12508: dumps the complete (or key matching regexp) namespace into a hash
                   12509: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12510: normally &store()ed into
                   12511: 
                   12512: $range should be either an integer '100' (give me the first 100
                   12513:                                            matching records)
                   12514:               or be  two integers sperated by a - with no spaces
                   12515:                  '30-50' (give me the 30th through the 50th matching
                   12516:                           records)
                   12517: 
                   12518: 
                   12519: =item *
                   12520: 
                   12521: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12522: replaces a &store() version of data with a replacement set of data
                   12523: for a particular resource in a namespace passed in the $storehash hash 
                   12524: reference
                   12525: 
                   12526: =item *
                   12527: 
1.243     albertel 12528: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12529: works very similar to store/cstore, but all data is stored in a
                   12530: temporary location and can be reset using tmpreset, $storehash should
                   12531: be a hash reference, returns nothing on success
1.191     harris41 12532: 
                   12533: =item *
                   12534: 
1.243     albertel 12535: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12536: similar to restore, but all data is stored in a temporary location and
                   12537: can be reset using tmpreset. Returns a hash of values on success,
                   12538: error string otherwise.
1.191     harris41 12539: 
                   12540: =item *
                   12541: 
1.243     albertel 12542: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12543: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12544: 
                   12545: =item *
                   12546: 
1.243     albertel 12547: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12548: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12549: 
                   12550: =item *
                   12551: 
1.243     albertel 12552: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12553: namesp ($udom and $uname are optional)
1.191     harris41 12554: 
                   12555: =item *
                   12556: 
1.702     albertel 12557: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12558: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12559: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12560: 
1.702     albertel 12561: $range should be either an integer '100' (give me the first 100
                   12562:                                            matching records)
                   12563:               or be  two integers sperated by a - with no spaces
                   12564:                  '30-50' (give me the 30th through the 50th matching
                   12565:                           records)
1.449     matthew  12566: =item *
                   12567: 
                   12568: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12569: $store can be a scalar, an array reference, or if the amount to be 
                   12570: incremented is > 1, a hash reference.
                   12571: 
                   12572: ($udom and $uname are optional)
1.191     harris41 12573: 
                   12574: =item *
                   12575: 
1.243     albertel 12576: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12577: ($udom and $uname are optional)
1.191     harris41 12578: 
                   12579: =item *
                   12580: 
1.243     albertel 12581: cput($namespace,$storehash,$udom,$uname) : critical put
                   12582: ($udom and $uname are optional)
1.191     harris41 12583: 
                   12584: =item *
                   12585: 
1.748     albertel 12586: newput($namespace,$storehash,$udom,$uname) :
                   12587: 
                   12588: Attempts to store the items in the $storehash, but only if they don't
                   12589: currently exist, if this succeeds you can be certain that you have 
                   12590: successfully created a new key value pair in the $namespace db.
                   12591: 
                   12592: 
                   12593: Args:
                   12594:  $namespace: name of database to store values to
                   12595:  $storehash: hashref to store to the db
                   12596:  $udom: (optional) domain of user containing the db
                   12597:  $uname: (optional) name of user caontaining the db
                   12598: 
                   12599: Returns:
                   12600:  'ok' -> succeeded in storing all keys of $storehash
                   12601:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12602:                         least <key> already existed in the db (other
                   12603:                         requested keys may also already exist)
1.967     bisitz   12604:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12605:  'con_lost' -> unable to contact request server
                   12606:  'refused' -> action was not allowed by remote machine
                   12607: 
                   12608: 
                   12609: =item *
                   12610: 
1.243     albertel 12611: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12612: reference filled in from namesp (encrypts the return communication)
                   12613: ($udom and $uname are optional)
1.191     harris41 12614: 
                   12615: =item *
                   12616: 
1.243     albertel 12617: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12618: critical subroutine
                   12619: 
1.806     raeburn  12620: =item *
                   12621: 
1.860     raeburn  12622: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12623: array reference filled in from namespace found in domain level on either
                   12624: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12625: 
                   12626: =item *
                   12627: 
1.860     raeburn  12628: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12629: domain level either on specified domain server ($uhome) or primary domain 
                   12630: server ($udom and $uhome are optional)
1.806     raeburn  12631: 
1.943     raeburn  12632: =item * 
                   12633: 
                   12634: get_domain_defaults($target_domain) : returns hash with defaults for
                   12635: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12636: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12637: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12638: Values are retrieved from cache (if current), or from domain's configuration.db
                   12639: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12640: or lonTabs/domain.tab. 
                   12641: 
                   12642: %domdefaults = &get_auth_defaults($target_domain);
                   12643: 
1.243     albertel 12644: =back
                   12645: 
                   12646: =head2 Network Status Functions
                   12647: 
                   12648: =over 4
1.191     harris41 12649: 
                   12650: =item *
                   12651: 
1.1137    raeburn  12652: dirlist() : return directory list based on URI (first arg).
                   12653: 
                   12654: Inputs: 1 required, 5 optional.
                   12655: 
                   12656: =over
                   12657: 
                   12658: =item 
                   12659: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12660: 
                   12661: =item
                   12662: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12663: 
                   12664: =item
                   12665: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12666: 
                   12667: =item
                   12668: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12669: 
                   12670: =item
                   12671: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12672: 
                   12673: =item 
                   12674: $alternateRoot - path to prepend in place of path from $uri.
                   12675: 
                   12676: =back
                   12677: 
                   12678: Returns: Array of up to two items.
                   12679: 
                   12680: =over
                   12681: 
                   12682: a reference to an array of files/subdirectories
                   12683: 
                   12684: =over
                   12685: 
                   12686: Each element in the array of files/subdirectories is a & separated list of
                   12687: item name and the result of running stat on the item.  If dirlist was requested
                   12688: for a file instead of a directory, the item name will be ''. For a directory 
                   12689: listing, if the item is a metadata file, the element will end &N&M 
                   12690: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12691: default copyright set (1).  
                   12692: 
                   12693: =back
                   12694: 
                   12695: a scalar containing error condition (if encountered).
                   12696: 
                   12697: =over
                   12698: 
                   12699: =item 
                   12700: no_host (no homeserver identified for $username:$domain).
                   12701: 
                   12702: =item 
                   12703: no_such_host (server contacted for listing not identified as valid host).
                   12704: 
                   12705: =item 
                   12706: con_lost (connection to remote server failed).
                   12707: 
                   12708: =item 
                   12709: refused (invalid $username:$domain received on lond side).
                   12710: 
                   12711: =item 
                   12712: no_such_dir (directory at specified path on lond side does not exist). 
                   12713: 
                   12714: =item 
                   12715: empty (directory at specified path on lond side is empty).
                   12716: 
                   12717: =over
                   12718: 
                   12719: This is currently not encountered because the &ls3, &ls2, 
                   12720: &ls (_handler) routines on the lond side do not filter out
                   12721: . and .. from a directory listing. 
                   12722: 
                   12723: =back
                   12724: 
                   12725: =back
                   12726: 
                   12727: =back
1.191     harris41 12728: 
                   12729: =item *
                   12730: 
1.243     albertel 12731: spareserver() : find server with least workload from spare.tab
                   12732: 
1.986     foxr     12733: 
                   12734: =item *
                   12735: 
                   12736: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12737: if there is no corresponding loncapa host.
                   12738: 
1.243     albertel 12739: =back
                   12740: 
1.986     foxr     12741: 
1.243     albertel 12742: =head2 Apache Request
                   12743: 
                   12744: =over 4
1.191     harris41 12745: 
                   12746: =item *
                   12747: 
1.243     albertel 12748: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12749: localhost, posts hash
                   12750: 
                   12751: =back
                   12752: 
                   12753: =head2 Data to String to Data
                   12754: 
                   12755: =over 4
1.191     harris41 12756: 
                   12757: =item *
                   12758: 
1.243     albertel 12759: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12760: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12761: 
                   12762: =item *
                   12763: 
1.243     albertel 12764: hashref2str($hashref) : convert a hashref into a string complete with
                   12765: escaping and '=' and '&' separators, supports elements that are
                   12766: arrayrefs and hashrefs
1.191     harris41 12767: 
                   12768: =item *
                   12769: 
1.243     albertel 12770: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12771: with escaping and '&' separators, supports elements that are arrayrefs
                   12772: and hashrefs
1.191     harris41 12773: 
                   12774: =item *
                   12775: 
1.243     albertel 12776: str2hash($string) : convert string to hash using unescaping and
                   12777: splitting on '=' and '&', supports elements that are arrayrefs and
                   12778: hashrefs
1.191     harris41 12779: 
                   12780: =item *
                   12781: 
1.243     albertel 12782: str2array($string) : convert string to hash using unescaping and
                   12783: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12784: 
                   12785: =back
                   12786: 
                   12787: =head2 Logging Routines
                   12788: 
                   12789: 
                   12790: These routines allow one to make log messages in the lonnet.log and
                   12791: lonnet.perm logfiles.
1.191     harris41 12792: 
1.1119    foxr     12793: =over 4
                   12794: 
1.191     harris41 12795: =item *
                   12796: 
1.243     albertel 12797: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12798: 
                   12799: =item *
                   12800: 
1.243     albertel 12801: logthis() : append message to the normal lonnet.log file, it gets
                   12802: preiodically rolled over and deleted.
1.191     harris41 12803: 
                   12804: =item *
                   12805: 
1.243     albertel 12806: logperm() : append a permanent message to lonnet.perm.log, this log
                   12807: file never gets deleted by any automated portion of the system, only
                   12808: messages of critical importance should go in here.
                   12809: 
1.1119    foxr     12810: 
1.243     albertel 12811: =back
                   12812: 
                   12813: =head2 General File Helper Routines
                   12814: 
                   12815: =over 4
1.191     harris41 12816: 
                   12817: =item *
                   12818: 
1.481     raeburn  12819: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12820: (a) files in /uploaded
                   12821:   (i) If a local copy of the file exists - 
                   12822:       compares modification date of local copy with last-modified date for 
                   12823:       definitive version stored on home server for course. If local copy is 
                   12824:       stale, requests a new version from the home server and stores it. 
                   12825:       If the original has been removed from the home server, then local copy 
                   12826:       is unlinked.
                   12827:   (ii) If local copy does not exist -
                   12828:       requests the file from the home server and stores it. 
                   12829:   
                   12830:   If $caller is 'uploadrep':  
                   12831:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12832:     for request for files originally uploaded via DOCS. 
                   12833:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12834:   
                   12835:   Otherwise:
                   12836:      This indicates a call from the content generation phase of the request.
                   12837:      -  returns the entire contents of the file or -1.
                   12838:      
                   12839: (b) files in /res
                   12840:    - returns the entire contents of a file or -1; 
                   12841:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12842: 
1.712     albertel 12843: 
                   12844: =item *
                   12845: 
                   12846: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12847:                   reference
                   12848: 
                   12849: returns either a stat() list of data about the file or an empty list
                   12850: if the file doesn't exist or couldn't find out about it (connection
                   12851: problems or user unknown)
                   12852: 
1.191     harris41 12853: =item *
                   12854: 
1.243     albertel 12855: filelocation($dir,$file) : returns file system location of a file
                   12856: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12857: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12858: and a file of ../bob will become /a/bob)
1.191     harris41 12859: 
                   12860: =item *
                   12861: 
                   12862: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12863: filelocation except for hrefs
                   12864: 
                   12865: =item *
                   12866: 
                   12867: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12868: 
1.243     albertel 12869: =back
                   12870: 
1.608     albertel 12871: =head2 Usererfile file routines (/uploaded*)
                   12872: 
                   12873: =over 4
                   12874: 
                   12875: =item *
                   12876: 
                   12877: userfileupload(): main rotine for putting a file in a user or course's
                   12878:                   filespace, arguments are,
                   12879: 
1.620     albertel 12880:  formname - required - this is the name of the element in $env where the
1.608     albertel 12881:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12882:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12883:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12884:  context - if coursedoc, store the file in the course of the active role
                   12885:              of the current user; 
                   12886:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12887:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12888:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12889:          if undefined, it will be placed in "unknown"
                   12890: 
                   12891:  (This routine calls clean_filename() to remove any dangerous
                   12892:  characters from the filename, and then calls finuserfileupload() to
                   12893:  complete the transaction)
                   12894: 
                   12895:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12896:  and /adm/notfound.html if unsuccessful
                   12897: 
                   12898: =item *
                   12899: 
                   12900: clean_filename(): routine for cleaing a filename up for storage in
                   12901:                  userfile space, argument is:
                   12902: 
                   12903:  filename - proposed filename
                   12904: 
                   12905: returns: the new clean filename
                   12906: 
                   12907: =item *
                   12908: 
1.1090    raeburn  12909: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12910: userspace, probably shouldn't be called directly
                   12911: 
                   12912:   docuname: username or courseid of destination for the file
                   12913:   docudom: domain of user/course of destination for the file
                   12914:   formname: same as for userfileupload()
1.1090    raeburn  12915:   fname: filename (including subdirectories) for the file
                   12916:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12917:   allfiles: reference to hash used to store objects found by parser
                   12918:   codebase: reference to hash used for codebases of java objects found by parser
                   12919:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12920:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12921:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12922:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12923:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12924:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12925:   mimetype: reference to scalar to accommodate mime type determined
                   12926:             from File::MMagic if $parser = parse.
1.608     albertel 12927: 
                   12928:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12929:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12930:  was 'overwrite').
                   12931:  
1.608     albertel 12932: 
                   12933: =item *
                   12934: 
                   12935: renameuserfile(): renames an existing userfile to a new name
                   12936: 
                   12937:   Args:
                   12938:    docuname: username or courseid of destination for the file
                   12939:    docudom: domain of user/course of destination for the file
                   12940:    old: current file name (including any subdirs under userfiles)
                   12941:    new: desired file name (including any subdirs under userfiles)
                   12942: 
                   12943: =item *
                   12944: 
                   12945: mkdiruserfile(): creates a directory is a userfiles dir
                   12946: 
                   12947:   Args:
                   12948:    docuname: username or courseid of destination for the file
                   12949:    docudom: domain of user/course of destination for the file
                   12950:    dir: dir to create (including any subdirs under userfiles)
                   12951: 
                   12952: =item *
                   12953: 
                   12954: removeuserfile(): removes a file that exists in userfiles
                   12955: 
                   12956:   Args:
                   12957:    docuname: username or courseid of destination for the file
                   12958:    docudom: domain of user/course of destination for the file
                   12959:    fname: filname to delete (including any subdirs under userfiles)
                   12960: 
                   12961: =item *
                   12962: 
                   12963: removeuploadedurl(): convience function for removeuserfile()
                   12964: 
                   12965:   Args:
                   12966:    url:  a full /uploaded/... url to delete
                   12967: 
1.747     albertel 12968: =item * 
                   12969: 
                   12970: get_portfile_permissions():
                   12971:   Args:
                   12972:     domain: domain of user or course contain the portfolio files
                   12973:     user: name of user or num of course contain the portfolio files
                   12974:   Returns:
                   12975:     hashref of a dump of the proper file_permissions.db
                   12976:    
                   12977: 
                   12978: =item * 
                   12979: 
                   12980: get_access_controls():
                   12981: 
                   12982: Args:
                   12983:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12984:   group: (optional) the group you want the files associated with
                   12985:   file: (optional) the file you want access info on
                   12986: 
                   12987: Returns:
1.749     raeburn  12988:     a hash (keys are file names) of hashes containing
                   12989:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12990:         values are XML containing access control settings (see below) 
1.747     albertel 12991: 
                   12992: Internal notes:
                   12993: 
1.749     raeburn  12994:  access controls are stored in file_permissions.db as key=value pairs.
                   12995:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12996:         where scope -> public,guest,course,group,domains or users.
                   12997:               end -> UNIX time for end of access (0 -> no end date)
                   12998:               start -> UNIX time for start of access
                   12999: 
                   13000:     value -> XML description of access control
                   13001:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13002:             <start></start>
                   13003:             <end></end>
                   13004: 
                   13005:             <password></password>  for scope type = guest
                   13006: 
                   13007:             <domain></domain>     for scope type = course or group
                   13008:             <number></number>
                   13009:             <roles id="">
                   13010:              <role></role>
                   13011:              <access></access>
                   13012:              <section></section>
                   13013:              <group></group>
                   13014:             </roles>
                   13015: 
                   13016:             <dom></dom>         for scope type = domains
                   13017: 
                   13018:             <users>             for scope type = users
                   13019:              <user>
                   13020:               <uname></uname>
                   13021:               <udom></udom>
                   13022:              </user>
                   13023:             </users>
                   13024:            </scope> 
                   13025:               
                   13026:  Access data is also aggregated for each file in an additional key=value pair:
                   13027:  key -> path to file/file_name\0accesscontrol 
                   13028:  value -> reference to hash
                   13029:           hash contains key = value pairs
                   13030:           where key = uniqueID:scope_end_start
                   13031:                 value = UNIX time record was last updated
                   13032: 
                   13033:           Used to improve speed of look-ups of access controls for each file.  
                   13034:  
                   13035:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13036: 
                   13037: modify_access_controls():
                   13038: 
                   13039: Modifies access controls for a portfolio file
                   13040: Args
                   13041: 1. file name
                   13042: 2. reference to hash of required changes,
                   13043: 3. domain
                   13044: 4. username
                   13045:   where domain,username are the domain of the portfolio owner 
                   13046:   (either a user or a course) 
                   13047: 
                   13048: Returns:
                   13049: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13050: 2. result of deletions ('ok' or 'error', with error message).
                   13051: 3. reference to hash of any new or updated access controls.
                   13052: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13053:    key = integer (inbound ID)
                   13054:    value = uniqueID  
1.747     albertel 13055: 
1.608     albertel 13056: =back
                   13057: 
1.243     albertel 13058: =head2 HTTP Helper Routines
                   13059: 
                   13060: =over 4
                   13061: 
1.191     harris41 13062: =item *
                   13063: 
                   13064: escape() : unpack non-word characters into CGI-compatible hex codes
                   13065: 
                   13066: =item *
                   13067: 
                   13068: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13069: 
1.243     albertel 13070: =back
                   13071: 
                   13072: =head1 PRIVATE SUBROUTINES
                   13073: 
                   13074: =head2 Underlying communication routines (Shouldn't call)
                   13075: 
                   13076: =over 4
                   13077: 
                   13078: =item *
                   13079: 
                   13080: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13081: 
                   13082: =item *
                   13083: 
                   13084: reply() : uses subreply to send a message to remote machine, logs all failures
                   13085: 
                   13086: =item *
                   13087: 
                   13088: critical() : passes a critical message to another server; if cannot
                   13089: get through then place message in connection buffer directory and
                   13090: returns con_delayed, if incapable of saving message, returns
                   13091: con_failed
                   13092: 
                   13093: =item *
                   13094: 
                   13095: reconlonc() : tries to reconnect lonc client processes.
                   13096: 
                   13097: =back
                   13098: 
                   13099: =head2 Resource Access Logging
                   13100: 
                   13101: =over 4
                   13102: 
                   13103: =item *
                   13104: 
                   13105: flushcourselogs() : flush (save) buffer logs and access logs
                   13106: 
                   13107: =item *
                   13108: 
                   13109: courselog($what) : save message for course in hash
                   13110: 
                   13111: =item *
                   13112: 
                   13113: courseacclog($what) : save message for course using &courselog().  Perform
                   13114: special processing for specific resource types (problems, exams, quizzes, etc).
                   13115: 
1.191     harris41 13116: =item *
                   13117: 
                   13118: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13119: as a PerlChildExitHandler
1.243     albertel 13120: 
                   13121: =back
                   13122: 
                   13123: =head2 Other
                   13124: 
                   13125: =over 4
                   13126: 
                   13127: =item *
                   13128: 
                   13129: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13130: 
                   13131: =back
                   13132: 
                   13133: =cut
1.877     foxr     13134: 

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