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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1245  ! raeburn     4: # $Id: lonnet.pm,v 1.1244 2013/12/05 05:19:18 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.1245  ! raeburn    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 {
1.1241    raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364:     return $response;
                    365: }
                    366: 
1.1       albertel  367: # -------------------------------------------------- Non-critical communication
                    368: sub subreply {
                    369:     my ($cmd,$server)=@_;
1.838     albertel  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      371:     #
                    372:     #  With loncnew process trimming, there's a timing hole between lonc server
                    373:     #  process exit and the master server picking up the listen on the AF_UNIX
                    374:     #  socket.  In that time interval, a lock file will exist:
                    375: 
                    376:     my $lockfile=$peerfile.".lock";
                    377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    378: 	sleep(1);
                    379:     }
                    380:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      381:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      382:     #
1.550     foxr      383:     #   We'll give the connection a few tries before abandoning it.  If
                    384:     #   connection is not possible, we'll con_lost back to the client.
                    385:     #   
                    386:     my $client;
                    387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    389: 				      Type    => SOCK_STREAM,
                    390: 				      Timeout => 10);
1.869     albertel  391: 	if ($client) {
1.550     foxr      392: 	    last;		# Connected!
1.850     albertel  393: 	} else {
1.853     albertel  394: 	    &create_connection(&hostname($server),$server);
1.550     foxr      395: 	}
1.850     albertel  396:         sleep(1);		# Try again later if failed connection.
1.550     foxr      397:     }
                    398:     my $answer;
                    399:     if ($client) {
1.704     albertel  400: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      401: 	$answer=<$client>;
                    402: 	if (!$answer) { $answer="con_lost"; }
                    403: 	chomp($answer);
                    404:     } else {
                    405: 	$answer = 'con_lost';	# Failed connection.
                    406:     }
1.1       albertel  407:     return $answer;
                    408: }
                    409: 
                    410: sub reply {
                    411:     my ($cmd,$server)=@_;
1.838     albertel  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  413:     my $answer=subreply($cmd,$server);
1.65      www       414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  415:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       416:                 " $cmd to $server returned $answer</font>");
                    417:     }
1.1       albertel  418:     return $answer;
                    419: }
                    420: 
                    421: # ----------------------------------------------------------- Send USR1 to lonc
                    422: 
                    423: sub reconlonc {
1.891     albertel  424:     my ($lonid) = @_;
                    425:     my $hostname = &hostname($lonid);
                    426:     if ($lonid) {
                    427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    428: 	if ($hostname && -e $peerfile) {
                    429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    431: 					     Type    => SOCK_STREAM,
                    432: 					     Timeout => 10);
                    433: 	    if ($client) {
                    434: 		print $client ("reset_retries\n");
                    435: 		my $answer=<$client>;
                    436: 		#reset just this one.
                    437: 	    }
                    438: 	}
                    439: 	return;
                    440:     }
                    441: 
1.836     www       442:     &logthis("Trying to reconnect lonc");
1.1       albertel  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  444:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  445: 	my $loncpid=<$fh>;
                    446:         chomp($loncpid);
                    447:         if (kill 0 => $loncpid) {
                    448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    449:             kill USR1 => $loncpid;
                    450:             sleep 1;
1.836     www       451:          } else {
1.12      www       452: 	    &logthis(
1.672     albertel  453:                "<font color=\"blue\">WARNING:".
1.12      www       454:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  455:         }
                    456:     } else {
1.836     www       457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  458:     }
                    459: }
                    460: 
                    461: # ------------------------------------------------------ Critical communication
1.12      www       462: 
1.1       albertel  463: sub critical {
                    464:     my ($cmd,$server)=@_;
1.838     albertel  465:     unless (&hostname($server)) {
1.672     albertel  466:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       467:                " Critical message to unknown server ($server)</font>");
                    468:         return 'no_such_host';
                    469:     }
1.1       albertel  470:     my $answer=reply($cmd,$server);
                    471:     if ($answer eq 'con_lost') {
                    472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  473: 	my $answer=reply($cmd,$server);
1.1       albertel  474:         if ($answer eq 'con_lost') {
                    475:             my $now=time;
                    476:             my $middlename=$cmd;
1.5       www       477:             $middlename=substr($middlename,0,16);
1.1       albertel  478:             $middlename=~s/\W//g;
                    479:             my $dfilename=
1.305     www       480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    481:             $dumpcount++;
1.1       albertel  482:             {
1.448     albertel  483: 		my $dfh;
                    484: 		if (open($dfh,">$dfilename")) {
                    485: 		    print $dfh "$cmd\n"; 
                    486: 		    close($dfh);
                    487: 		}
1.1       albertel  488:             }
                    489:             sleep 2;
                    490:             my $wcmd='';
                    491:             {
1.448     albertel  492: 		my $dfh;
                    493: 		if (open($dfh,"<$dfilename")) {
                    494: 		    $wcmd=<$dfh>; 
                    495: 		    close($dfh);
                    496: 		}
1.1       albertel  497:             }
                    498:             chomp($wcmd);
1.7       www       499:             if ($wcmd eq $cmd) {
1.672     albertel  500: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       501:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  502:                 &logperm("D:$server:$cmd");
                    503: 	        return 'con_delayed';
                    504:             } else {
1.672     albertel  505:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       506:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  507:                 &logperm("F:$server:$cmd");
                    508:                 return 'con_failed';
                    509:             }
                    510:         }
                    511:     }
                    512:     return $answer;
1.405     albertel  513: }
                    514: 
1.755     albertel  515: # ------------------------------------------- check if return value is an error
                    516: 
                    517: sub error {
                    518:     my ($result) = @_;
1.756     albertel  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  520: 	if ($2 == 2) { return undef; }
                    521: 	return $1;
                    522:     }
                    523:     return undef;
                    524: }
                    525: 
1.783     albertel  526: sub convert_and_load_session_env {
                    527:     my ($lonidsdir,$handle)=@_;
                    528:     my @profile;
                    529:     {
1.917     albertel  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    531: 	if (!$opened) {
1.915     albertel  532: 	    return 0;
                    533: 	}
1.783     albertel  534: 	flock($idf,LOCK_SH);
                    535: 	@profile=<$idf>;
                    536: 	close($idf);
                    537:     }
                    538:     my %temp_env;
                    539:     foreach my $line (@profile) {
1.786     albertel  540: 	if ($line !~ m/=/) {
                    541: 	    return 0;
                    542: 	}
1.783     albertel  543: 	chomp($line);
                    544: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    546:     }
                    547:     unlink("$lonidsdir/$handle.id");
                    548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    549: 	    0640)) {
                    550: 	%disk_env = %temp_env;
                    551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    552: 	untie(%disk_env);
                    553:     }
1.786     albertel  554:     return 1;
1.783     albertel  555: }
                    556: 
1.374     www       557: # ------------------------------------------- Transfer profile into environment
1.780     albertel  558: my $env_loaded;
                    559: sub transfer_profile_to_env {
1.788     albertel  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    561:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       562: 
1.720     albertel  563:     if (!defined($lonidsdir)) {
                    564: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    565:     }
                    566:     if (!defined($handle)) {
                    567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    568:     }
                    569: 
1.786     albertel  570:     my $convert;
                    571:     {
1.917     albertel  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    573: 	if (!$opened) {
1.915     albertel  574: 	    return;
                    575: 	}
1.786     albertel  576: 	flock($idf,LOCK_SH);
                    577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    578: 		&GDBM_READER(),0640)) {
                    579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    580: 	    untie(%disk_env);
                    581: 	} else {
                    582: 	    $convert = 1;
                    583: 	}
                    584:     }
                    585:     if ($convert) {
                    586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    587: 	    &logthis("Failed to load session, or convert session.");
                    588: 	}
1.374     www       589:     }
1.783     albertel  590: 
1.786     albertel  591:     my %remove;
1.783     albertel  592:     while ( my $envname = each(%env) ) {
1.433     matthew   593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    594:             if ($time < time-300) {
1.783     albertel  595:                 $remove{$key}++;
1.433     matthew   596:             }
                    597:         }
                    598:     }
1.783     albertel  599: 
1.619     albertel  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  601:     $env_loaded=1;
1.783     albertel  602:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   603:         &delenv($expired_key);
1.374     www       604:     }
1.1       albertel  605: }
                    606: 
1.916     albertel  607: # ---------------------------------------------------- Check for valid session 
                    608: sub check_for_valid_session {
1.1245  ! raeburn   609:     my ($r,$name,$userhashref) = @_;
1.916     albertel  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   611:     if ($name eq '') {
                    612:         $name = 'lonID';
                    613:     }
                    614:     my $lonid=$cookies{$name};
1.916     albertel  615:     return undef if (!$lonid);
                    616: 
                    617:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   618:     my $lonidsdir;
                    619:     if ($name eq 'lonDAV') {
                    620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    621:     } else {
                    622:         $lonidsdir=$r->dir_config('lonIDsDir');
                    623:     }
1.916     albertel  624:     return undef if (!-e "$lonidsdir/$handle.id");
                    625: 
1.917     albertel  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    627:     return undef if (!$opened);
1.916     albertel  628: 
                    629:     flock($idf,LOCK_SH);
                    630:     my %disk_env;
                    631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    632: 	    &GDBM_READER(),0640)) {
                    633: 	return undef;	
                    634:     }
                    635: 
                    636:     if (!defined($disk_env{'user.name'})
                    637: 	|| !defined($disk_env{'user.domain'})) {
                    638: 	return undef;
                    639:     }
1.1245  ! raeburn   640: 
        !           641:     if (ref($userhashref) eq 'HASH') {
        !           642:         $userhashref->{'name'} = $disk_env{'user.name'};
        !           643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   644:     }
1.1245  ! raeburn   645: 
1.916     albertel  646:     return $handle;
                    647: }
                    648: 
1.830     albertel  649: sub timed_flock {
                    650:     my ($file,$lock_type) = @_;
                    651:     my $failed=0;
                    652:     eval {
                    653: 	local $SIG{__DIE__}='DEFAULT';
                    654: 	local $SIG{ALRM}=sub {
                    655: 	    $failed=1;
                    656: 	    die("failed lock");
                    657: 	};
                    658: 	alarm(13);
                    659: 	flock($file,$lock_type);
                    660: 	alarm(0);
                    661:     };
                    662:     if ($failed) {
                    663: 	return undef;
                    664:     } else {
                    665: 	return 1;
                    666:     }
                    667: }
                    668: 
1.5       www       669: # ---------------------------------------------------------- Append Environment
                    670: 
                    671: sub appenv {
1.949     raeburn   672:     my ($newenv,$roles) = @_;
                    673:     if (ref($newenv) eq 'HASH') {
                    674:         foreach my $key (keys(%{$newenv})) {
                    675:             my $refused = 0;
                    676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    677:                 $refused = 1;
                    678:                 if (ref($roles) eq 'ARRAY') {
                    679:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    681:                         $refused = 0;
                    682:                     }
                    683:                 }
                    684:             }
                    685:             if ($refused) {
                    686:                 &logthis("<font color=\"blue\">WARNING: ".
                    687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    688:                          .'</font>');
                    689: 	        delete($newenv->{$key});
                    690:             } else {
                    691:                 $env{$key}=$newenv->{$key};
                    692:             }
                    693:         }
                    694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    695:         if ($opened
                    696: 	    && &timed_flock($env_file,LOCK_EX)
                    697: 	    &&
                    698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    700: 	    while (my ($key,$value) = each(%{$newenv})) {
                    701: 	        $disk_env{$key} = $value;
                    702: 	    }
                    703: 	    untie(%disk_env);
1.35      www       704:         }
1.191     harris41  705:     }
1.56      www       706:     return 'ok';
                    707: }
                    708: # ----------------------------------------------------- Delete from Environment
                    709: 
                    710: sub delenv {
1.1104    raeburn   711:     my ($delthis,$regexp,$roles) = @_;
                    712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    713:         my $refused = 1;
                    714:         if (ref($roles) eq 'ARRAY') {
                    715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    716:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    717:                 $refused = 0;
                    718:             }
                    719:         }
                    720:         if ($refused) {
                    721:             &logthis("<font color=\"blue\">WARNING: ".
                    722:                      "Attempt to delete from environment ".$delthis);
                    723:             return 'error';
                    724:         }
1.56      www       725:     }
1.917     albertel  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    727:     if ($opened
1.915     albertel  728: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  729: 	&&
                    730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  732: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   733: 	    if ($regexp) {
                    734:                 if ($key=~/^$delthis/) {
                    735:                     delete($env{$key});
                    736:                     delete($disk_env{$key});
                    737:                 } 
                    738:             } else {
                    739:                 if ($key=~/^\Q$delthis\E/) {
                    740: 		    delete($env{$key});
                    741: 		    delete($disk_env{$key});
                    742: 	        }
                    743:             }
1.448     albertel  744: 	}
1.783     albertel  745: 	untie(%disk_env);
1.5       www       746:     }
                    747:     return 'ok';
1.369     albertel  748: }
                    749: 
1.790     albertel  750: sub get_env_multiple {
                    751:     my ($name) = @_;
                    752:     my @values;
                    753:     if (defined($env{$name})) {
                    754:         # exists is it an array
                    755:         if (ref($env{$name})) {
                    756:             @values=@{ $env{$name} };
                    757:         } else {
                    758:             $values[0]=$env{$name};
                    759:         }
                    760:     }
                    761:     return(@values);
                    762: }
                    763: 
1.958     www       764: # ------------------------------------------------------------------- Locking
                    765: 
                    766: sub set_lock {
                    767:     my ($text)=@_;
                    768:     $locknum++;
                    769:     my $id=$$.'-'.$locknum;
                    770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    771:              'session.lock.'.$id => $text});
                    772:     return $id;
                    773: }
                    774: 
                    775: sub get_locks {
                    776:     my $num=0;
                    777:     my %texts=();
                    778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    779:        if ($lock=~/\w/) {
                    780:           $num++;
                    781:           $texts{$lock}=$env{'session.lock.'.$lock};
                    782:        }
                    783:    }
                    784:    return ($num,%texts);
                    785: }
                    786: 
                    787: sub remove_lock {
                    788:     my ($id)=@_;
                    789:     my $newlocks='';
                    790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    791:        if (($lock=~/\w/) && ($lock ne $id)) {
                    792:           $newlocks.=','.$lock;
                    793:        }
                    794:     }
                    795:     &appenv({'session.locks' => $newlocks});
                    796:     &delenv('session.lock.'.$id);
                    797: }
                    798: 
                    799: sub remove_all_locks {
                    800:     my $activelocks=$env{'session.locks'};
                    801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    802:        if ($lock=~/\w/) {
                    803:           &remove_lock($lock);
                    804:        }
                    805:     }
                    806: }
                    807: 
                    808: 
1.369     albertel  809: # ------------------------------------------ Find out current server userload
                    810: sub userload {
                    811:     my $numusers=0;
                    812:     {
                    813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    814: 	my $filename;
                    815: 	my $curtime=time;
                    816: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  817: 	    next if ($filename eq '.' || $filename eq '..');
                    818: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  821: 	}
                    822: 	closedir(LONIDS);
                    823:     }
                    824:     my $userloadpercent=0;
                    825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    826:     if ($maxuserload) {
1.371     albertel  827: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  828:     }
1.372     albertel  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  830:     return $userloadpercent;
1.283     www       831: }
                    832: 
1.1       albertel  833: # ------------------------------ Find server with least workload from spare.tab
1.11      www       834: 
1.1       albertel  835: sub spareserver {
1.1083    raeburn   836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  837:     my $spare_server;
1.370     albertel  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    840:                                                      :  $userloadpercent;
1.1083    raeburn   841:     my ($uint_dom,$remotesessions);
                    842:     if (($udom ne '') && (&domain($udom) ne '')) {
                    843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    846:         $remotesessions = $udomdefaults{'remotesessions'};
                    847:     }
1.1123    raeburn   848:     my $spareshash = &this_host_spares($udom);
                    849:     if (ref($spareshash) eq 'HASH') {
                    850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    852:                 if ($uint_dom) {
                    853:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    854:                                                  $try_server));
                    855:                 }
                    856: 	        ($spare_server, $lowest_load) =
                    857: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    858:             }
1.1083    raeburn   859:         }
1.784     albertel  860: 
1.1123    raeburn   861:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    862: 
                    863:         if (!$found_server) {
                    864:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    865: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    866:                     if ($uint_dom) {
                    867:                         next unless (&spare_can_host($udom,$uint_dom,
                    868:                                                      $remotesessions,$try_server));
                    869:                     }
                    870: 	            ($spare_server, $lowest_load) =
                    871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    872:                 }
                    873: 	    }
                    874:         }
1.784     albertel  875:     }
                    876: 
                    877:     if (!$want_server_name) {
1.968     raeburn   878:         my $protocol = 'http';
                    879:         if ($protocol{$spare_server} eq 'https') {
                    880:             $protocol = $protocol{$spare_server};
                    881:         }
1.1001    raeburn   882:         if (defined($spare_server)) {
                    883:             my $hostname = &hostname($spare_server);
1.1083    raeburn   884:             if (defined($hostname)) {
1.1001    raeburn   885: 	        $spare_server = $protocol.'://'.$hostname;
                    886:             }
                    887:         }
1.784     albertel  888:     }
                    889:     return $spare_server;
                    890: }
                    891: 
                    892: sub compare_server_load {
                    893:     my ($try_server, $spare_server, $lowest_load) = @_;
                    894: 
                    895:     my $loadans     = &reply('load',    $try_server);
                    896:     my $userloadans = &reply('userload',$try_server);
                    897: 
                    898:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   899: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  900:     }
                    901: 
                    902:     my $load;
                    903:     if ($loadans =~ /\d/) {
                    904: 	if ($userloadans =~ /\d/) {
                    905: 	    #both are numbers, pick the bigger one
                    906: 	    $load = ($loadans > $userloadans) ? $loadans 
                    907: 		                              : $userloadans;
1.411     albertel  908: 	} else {
1.784     albertel  909: 	    $load = $loadans;
1.411     albertel  910: 	}
1.784     albertel  911:     } else {
                    912: 	$load = $userloadans;
                    913:     }
                    914: 
                    915:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    916: 	$spare_server = $try_server;
                    917: 	$lowest_load  = $load;
1.370     albertel  918:     }
1.784     albertel  919:     return ($spare_server,$lowest_load);
1.202     matthew   920: }
1.914     albertel  921: 
                    922: # --------------------------- ask offload servers if user already has a session
                    923: sub find_existing_session {
                    924:     my ($udom,$uname) = @_;
1.1123    raeburn   925:     my $spareshash = &this_host_spares($udom);
                    926:     if (ref($spareshash) eq 'HASH') {
                    927:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    928:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    929:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    930:             }
                    931:         }
                    932:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    933:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    934:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    935:             }
                    936:         }
1.914     albertel  937:     }
                    938:     return;
                    939: }
                    940: 
                    941: # -------------------------------- ask if server already has a session for user
                    942: sub has_user_session {
                    943:     my ($lonid,$udom,$uname) = @_;
                    944:     my $result = &reply(join(':','userhassession',
                    945: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    946:     return 1 if ($result eq 'ok');
                    947: 
                    948:     return 0;
                    949: }
                    950: 
1.1076    raeburn   951: # --------- determine least loaded server in a user's domain which allows login
                    952: 
                    953: sub choose_server {
1.1115    raeburn   954:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   955:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   956:     my %servers = &get_servers($udom);
1.1076    raeburn   957:     my $lowest_load = 30000;
1.1151    raeburn   958:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   959:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   960:         my $loginvia;
                    961:         if ($checkloginvia) {
                    962:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   963:             if ($loginvia) {
                    964:                 my ($server,$path) = split(/:/,$loginvia);
                    965:                 ($login_host, $lowest_load) =
                    966:                     &compare_server_load($server, $login_host, $lowest_load);
                    967:                 if ($login_host eq $server) {
                    968:                     $portal_path = $path;
1.1151    raeburn   969:                     $isredirect = 1;
1.1116    raeburn   970:                 }
                    971:             } else {
                    972:                 ($login_host, $lowest_load) =
                    973:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    974:                 if ($login_host eq $lonhost) {
                    975:                     $portal_path = '';
1.1151    raeburn   976:                     $isredirect = ''; 
1.1116    raeburn   977:                 }
                    978:             }
                    979:         } else {
1.1076    raeburn   980:             ($login_host, $lowest_load) =
1.1116    raeburn   981:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   982:         }
                    983:     }
                    984:     if ($login_host ne '') {
1.1116    raeburn   985:         $hostname = &hostname($login_host);
1.1076    raeburn   986:     }
1.1151    raeburn   987:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   988: }
                    989: 
1.202     matthew   990: # --------------------------------------------- Try to change a user's password
                    991: 
                    992: sub changepass {
1.799     raeburn   993:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   994:     $currentpass = &escape($currentpass);
                    995:     $newpass     = &escape($newpass);
1.1030    raeburn   996:     my $lonhost = $perlvar{'lonHostID'};
                    997:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   998: 		       $server);
                    999:     if (! $answer) {
                   1000: 	&logthis("No reply on password change request to $server ".
                   1001: 		 "by $uname in domain $udom.");
                   1002:     } elsif ($answer =~ "^ok") {
                   1003:         &logthis("$uname in $udom successfully changed their password ".
                   1004: 		 "on $server.");
                   1005:     } elsif ($answer =~ "^pwchange_failure") {
                   1006: 	&logthis("$uname in $udom was unable to change their password ".
                   1007: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1008: 		 "or pwchange");
                   1009:     } elsif ($answer =~ "^non_authorized") {
                   1010:         &logthis("$uname in $udom did not get their password correct when ".
                   1011: 		 "attempting to change it on $server.");
                   1012:     } elsif ($answer =~ "^auth_mode_error") {
                   1013:         &logthis("$uname in $udom attempted to change their password despite ".
                   1014: 		 "not being locally or internally authenticated on $server.");
                   1015:     } elsif ($answer =~ "^unknown_user") {
                   1016:         &logthis("$uname in $udom attempted to change their password ".
                   1017: 		 "on $server but were unable to because $server is not ".
                   1018: 		 "their home server.");
                   1019:     } elsif ($answer =~ "^refused") {
                   1020: 	&logthis("$server refused to change $uname in $udom password because ".
                   1021: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1022:     } elsif ($answer =~ "invalid_client") {
                   1023:         &logthis("$server refused to change $uname in $udom password because ".
                   1024:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1025:     }
                   1026:     return $answer;
1.1       albertel 1027: }
                   1028: 
1.169     harris41 1029: # ----------------------- Try to determine user's current authentication scheme
                   1030: 
                   1031: sub queryauthenticate {
                   1032:     my ($uname,$udom)=@_;
1.456     albertel 1033:     my $uhome=&homeserver($uname,$udom);
                   1034:     if (!$uhome) {
                   1035: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1036: 	return 'no_host';
                   1037:     }
                   1038:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1039:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1040: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1041:     }
1.456     albertel 1042:     return $answer;
1.169     harris41 1043: }
                   1044: 
1.1       albertel 1045: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1046: 
1.1       albertel 1047: sub authenticate {
1.1073    raeburn  1048:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1049:     $upass=&escape($upass);
                   1050:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1051:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1052:     my $newhome;
1.836     www      1053:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1054: # Maybe the machine was offline and only re-appeared again recently?
                   1055:         &reconlonc();
                   1056: # One more
1.952     raeburn  1057: 	$uhome=&homeserver($uname,$udom,1);
                   1058:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1059:             if (defined(&domain($udom,'primary'))) {
                   1060:                 $newhome=&domain($udom,'primary');
                   1061:             }
                   1062:             if ($newhome ne '') {
                   1063:                 $uhome = $newhome;
                   1064:             }
                   1065:         }
1.836     www      1066: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1067: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1068: 	    return 'no_host';
                   1069:         }
1.1       albertel 1070:     }
1.1073    raeburn  1071:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1072:     if ($answer eq 'authorized') {
1.952     raeburn  1073:         if ($newhome) {
                   1074:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1075:             return 'no_account_on_host'; 
                   1076:         } else {
                   1077:             &logthis("User $uname at $udom authorized by $uhome");
                   1078:             return $uhome;
                   1079:         }
1.471     albertel 1080:     }
                   1081:     if ($answer eq 'non_authorized') {
                   1082: 	&logthis("User $uname at $udom rejected by $uhome");
                   1083: 	return 'no_host'; 
1.9       www      1084:     }
1.471     albertel 1085:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1086:     return 'no_host';
                   1087: }
                   1088: 
1.1073    raeburn  1089: sub can_host_session {
1.1074    raeburn  1090:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1091:     my $canhost = 1;
1.1074    raeburn  1092:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1093:     if (ref($remotesessions) eq 'HASH') {
                   1094:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1095:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1096:                 $canhost = 0;
                   1097:             } else {
                   1098:                 $canhost = 1;
                   1099:             }
                   1100:         }
                   1101:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1102:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1103:                 $canhost = 1;
                   1104:             } else {
                   1105:                 $canhost = 0;
                   1106:             }
                   1107:         }
                   1108:         if ($canhost) {
                   1109:             if ($remotesessions->{'version'} ne '') {
                   1110:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1111:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1112:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1113:                         my $major = $1;
                   1114:                         my $minor = $2;
                   1115:                         if (($major < $reqmajor ) ||
                   1116:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1117:                             $canhost = 0;
                   1118:                         }
                   1119:                     } else {
                   1120:                         $canhost = 0;
                   1121:                     }
                   1122:                 }
                   1123:             }
                   1124:         }
                   1125:     }
                   1126:     if ($canhost) {
                   1127:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1128:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1129:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1130:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1131:                 if (($uint_dom ne '') && 
                   1132:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1133:                     $canhost = 0;
                   1134:                 } else {
                   1135:                     $canhost = 1;
                   1136:                 }
                   1137:             }
                   1138:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1139:                 if (($uint_dom ne '') && 
                   1140:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1141:                     $canhost = 1;
                   1142:                 } else {
                   1143:                     $canhost = 0;
                   1144:                 }
                   1145:             }
                   1146:         }
                   1147:     }
                   1148:     return $canhost;
                   1149: }
                   1150: 
1.1083    raeburn  1151: sub spare_can_host {
                   1152:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1153:     my $canhost=1;
                   1154:     my @intdoms;
                   1155:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1156:     if (ref($internet_names) eq 'ARRAY') {
                   1157:         @intdoms = @{$internet_names};
                   1158:     }
                   1159:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1160:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1161:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1162:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1163:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1164:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1165:                                      $remotesessions,
                   1166:                                      $defdomdefaults{'hostedsessions'});
                   1167:     }
                   1168:     return $canhost;
                   1169: }
                   1170: 
1.1123    raeburn  1171: sub this_host_spares {
                   1172:     my ($dom) = @_;
1.1126    raeburn  1173:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1174:     my @hosts = &current_machine_ids();
                   1175:     foreach my $lonhost (@hosts) {
                   1176:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1177:             $dom_in_use = $dom;
                   1178:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1179:             last;
                   1180:         }
                   1181:     }
1.1126    raeburn  1182:     if ($dom_in_use ne '') {
                   1183:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1184:     }
                   1185:     if (ref($result) ne 'HASH') {
                   1186:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1187:         $dom_in_use = &host_domain($lonhost_in_use);
                   1188:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1189:         if (ref($result) ne 'HASH') {
                   1190:             $result = \%spareid;
                   1191:         }
                   1192:     }
                   1193:     return $result;
                   1194: }
                   1195: 
                   1196: sub spares_for_offload  {
                   1197:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1198:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1199:     if (defined($cached)) {
                   1200:         return $result;
                   1201:     } else {
1.1126    raeburn  1202:         my $cachetime = 60*60*24;
                   1203:         my %domconfig =
                   1204:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1205:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1206:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1207:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1208:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1209:                 }
                   1210:             }
                   1211:         }
                   1212:     }
1.1126    raeburn  1213:     return;
1.1123    raeburn  1214: }
                   1215: 
1.1129    raeburn  1216: sub get_lonbalancer_config {
                   1217:     my ($servers) = @_;
                   1218:     my ($currbalancer,$currtargets);
                   1219:     if (ref($servers) eq 'HASH') {
                   1220:         foreach my $server (keys(%{$servers})) {
                   1221:             my %what = (
                   1222:                          spareid => 1,
                   1223:                          perlvar => 1,
                   1224:                        );
                   1225:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1226:             if ($result eq 'ok') {
                   1227:                 if (ref($returnhash) eq 'HASH') {
                   1228:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1229:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1230:                             $currbalancer = $server;
                   1231:                             $currtargets = {};
                   1232:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1233:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1234:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1235:                                 }
                   1236:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1237:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1238:                                 }
                   1239:                             }
                   1240:                             last;
                   1241:                         }
                   1242:                     }
                   1243:                 }
                   1244:             }
                   1245:         }
                   1246:     }
                   1247:     return ($currbalancer,$currtargets);
                   1248: }
                   1249: 
                   1250: sub check_loadbalancing {
                   1251:     my ($uname,$udom) = @_;
1.1191    raeburn  1252:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1253:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1254:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1255:     my @hosts = &current_machine_ids();
1.1129    raeburn  1256:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1257:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1258:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1259:     my $serverhomedom = &host_domain($lonhost);
                   1260: 
                   1261:     my $cachetime = 60*60*24;
                   1262: 
                   1263:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1264:         $dom_in_use = $udom;
                   1265:         $homeintdom = 1;
                   1266:     } else {
                   1267:         $dom_in_use = $serverhomedom;
                   1268:     }
                   1269:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1270:     unless (defined($cached)) {
                   1271:         my %domconfig =
                   1272:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1273:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1274:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1275:         }
                   1276:     }
                   1277:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1278:         ($is_balancer,$currtargets,$currrules) = 
                   1279:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1280:         if ($is_balancer) {
                   1281:             if (ref($currrules) eq 'HASH') {
                   1282:                 if ($homeintdom) {
                   1283:                     if ($uname ne '') {
                   1284:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1285:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1286:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1287:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1288:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1289:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1290:                             }
                   1291:                         }
                   1292:                         if ($rule_in_effect eq '') {
                   1293:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1294:                             if ($userenv{'inststatus'} ne '') {
                   1295:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1296:                                 my ($othertitle,$usertypes,$types) =
                   1297:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1298:                                 if (ref($types) eq 'ARRAY') {
                   1299:                                     foreach my $type (@{$types}) {
                   1300:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1301:                                             if (exists($currrules->{$type})) {
                   1302:                                                 $rule_in_effect = $currrules->{$type};
                   1303:                                             }
                   1304:                                         }
                   1305:                                     }
                   1306:                                 }
                   1307:                             } else {
                   1308:                                 if (exists($currrules->{'default'})) {
                   1309:                                     $rule_in_effect = $currrules->{'default'};
                   1310:                                 }
                   1311:                             }
                   1312:                         }
                   1313:                     } else {
                   1314:                         if (exists($currrules->{'default'})) {
                   1315:                             $rule_in_effect = $currrules->{'default'};
                   1316:                         }
                   1317:                     }
                   1318:                 } else {
                   1319:                     if ($currrules->{'_LC_external'} ne '') {
                   1320:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1321:                     }
                   1322:                 }
                   1323:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1324:                                                        $uname,$udom);
                   1325:             }
                   1326:         }
                   1327:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1328:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1329:         unless (defined($cached)) {
                   1330:             my %domconfig =
                   1331:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1332:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1333:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1334:             }
                   1335:         }
                   1336:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1337:             ($is_balancer,$currtargets,$currrules) = 
                   1338:                 &check_balancer_result($result,@hosts);
                   1339:             if ($is_balancer) {
1.1129    raeburn  1340:                 if (ref($currrules) eq 'HASH') {
                   1341:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1342:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1343:                     }
                   1344:                 }
                   1345:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1346:                                                        $uname,$udom);
                   1347:             }
                   1348:         } else {
                   1349:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1350:                 $is_balancer = 1;
                   1351:                 $offloadto = &this_host_spares($dom_in_use);
                   1352:             }
                   1353:         }
                   1354:     } else {
                   1355:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1356:             $is_balancer = 1;
                   1357:             $offloadto = &this_host_spares($dom_in_use);
                   1358:         }
                   1359:     }
1.1176    raeburn  1360:     if ($is_balancer) {
                   1361:         my $lowest_load = 30000;
                   1362:         if (ref($offloadto) eq 'HASH') {
                   1363:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1364:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1365:                     ($otherserver,$lowest_load) =
                   1366:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1367:                 }
1.1129    raeburn  1368:             }
1.1176    raeburn  1369:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1370: 
1.1176    raeburn  1371:             if (!$found_server) {
                   1372:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1373:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1374:                         ($otherserver,$lowest_load) =
                   1375:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1376:                     }
                   1377:                 }
                   1378:             }
                   1379:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1380:             if (@{$offloadto} == 1) {
                   1381:                 $otherserver = $offloadto->[0];
                   1382:             } elsif (@{$offloadto} > 1) {
                   1383:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1384:                     ($otherserver,$lowest_load) =
                   1385:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1386:                 }
                   1387:             }
                   1388:         }
1.1176    raeburn  1389:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1390:             $is_balancer = 0;
                   1391:             if ($uname ne '' && $udom ne '') {
                   1392:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1393:                     
                   1394:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1395:                              'user.loadbalcheck.time' => time});
                   1396:                 }
1.1129    raeburn  1397:             }
                   1398:         }
                   1399:     }
                   1400:     return ($is_balancer,$otherserver);
                   1401: }
                   1402: 
1.1191    raeburn  1403: sub check_balancer_result {
                   1404:     my ($result,@hosts) = @_;
                   1405:     my ($is_balancer,$currtargets,$currrules);
                   1406:     if (ref($result) eq 'HASH') {
                   1407:         if ($result->{'lonhost'} ne '') {
                   1408:             my $currbalancer = $result->{'lonhost'};
                   1409:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1410:                 $is_balancer = 1;
                   1411:                 $currtargets = $result->{'targets'};
                   1412:                 $currrules = $result->{'rules'};
                   1413:             }
                   1414:         } else {
                   1415:             foreach my $key (keys(%{$result})) {
                   1416:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1417:                     (ref($result->{$key}) eq 'HASH')) {
                   1418:                     $is_balancer = 1;
                   1419:                     $currrules = $result->{$key}{'rules'};
                   1420:                     $currtargets = $result->{$key}{'targets'};
                   1421:                     last;
                   1422:                 }
                   1423:             }
                   1424:         }
                   1425:     }
                   1426:     return ($is_balancer,$currtargets,$currrules);
                   1427: }
                   1428: 
1.1129    raeburn  1429: sub get_loadbalancer_targets {
                   1430:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1431:     my $offloadto;
1.1175    raeburn  1432:     if ($rule_in_effect eq 'none') {
                   1433:         return [$perlvar{'lonHostID'}];
                   1434:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1435:         $offloadto = $currtargets;
                   1436:     } else {
                   1437:         if ($rule_in_effect eq 'homeserver') {
                   1438:             my $homeserver = &homeserver($uname,$udom);
                   1439:             if ($homeserver ne 'no_host') {
                   1440:                 $offloadto = [$homeserver];
                   1441:             }
                   1442:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1443:             my %domconfig =
                   1444:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1445:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1446:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1447:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1448:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1449:                     }
                   1450:                 }
                   1451:             } else {
1.1178    raeburn  1452:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1453:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1454:                 if (&hostname($remotebalancer) ne '') {
                   1455:                     $offloadto = [$remotebalancer];
                   1456:                 }
                   1457:             }
                   1458:         } elsif (&hostname($rule_in_effect) ne '') {
                   1459:             $offloadto = [$rule_in_effect];
                   1460:         }
                   1461:     }
                   1462:     return $offloadto;
                   1463: }
                   1464: 
1.1127    raeburn  1465: sub internet_dom_servers {
                   1466:     my ($dom) = @_;
                   1467:     my (%uniqservers,%servers);
                   1468:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1469:     my @machinedoms = &machine_domains($primaryserver);
                   1470:     foreach my $mdom (@machinedoms) {
                   1471:         my %currservers = %servers;
                   1472:         my %server = &get_servers($mdom);
                   1473:         %servers = (%currservers,%server);
                   1474:     }
                   1475:     my %by_hostname;
                   1476:     foreach my $id (keys(%servers)) {
                   1477:         push(@{$by_hostname{$servers{$id}}},$id);
                   1478:     }
                   1479:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1480:         if (@{$by_hostname{$hostname}} > 1) {
                   1481:             my $match = 0;
                   1482:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1483:                 if (&host_domain($id) eq $dom) {
                   1484:                     $uniqservers{$id} = $hostname;
                   1485:                     $match = 1;
                   1486:                 }
                   1487:             }
                   1488:             unless ($match) {
                   1489:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1490:             }
                   1491:         } else {
                   1492:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1493:         }
                   1494:     }
                   1495:     return %uniqservers;
                   1496: }
                   1497: 
1.1       albertel 1498: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1499: 
1.599     albertel 1500: my %homecache;
1.1       albertel 1501: sub homeserver {
1.230     stredwic 1502:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1503:     my $index="$uname:$udom";
1.426     albertel 1504: 
1.599     albertel 1505:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1506: 
                   1507:     my %servers = &get_servers($udom,'library');
                   1508:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1509:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1510: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1511: 
                   1512: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1513: 	if ($answer eq 'found') {
                   1514: 	    delete($badServerCache{$tryserver}); 
                   1515: 	    return $homecache{$index}=$tryserver;
                   1516: 	} elsif ($answer eq 'no_host') {
                   1517: 	    $badServerCache{$tryserver}=1;
                   1518: 	}
1.1       albertel 1519:     }    
                   1520:     return 'no_host';
1.70      www      1521: }
                   1522: 
                   1523: # ------------------------------------- Find the usernames behind a list of IDs
                   1524: 
                   1525: sub idget {
                   1526:     my ($udom,@ids)=@_;
                   1527:     my %returnhash=();
                   1528:     
1.841     albertel 1529:     my %servers = &get_servers($udom,'library');
                   1530:     foreach my $tryserver (keys(%servers)) {
                   1531: 	my $idlist=join('&',@ids);
                   1532: 	$idlist=~tr/A-Z/a-z/; 
                   1533: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1534: 	my @answer=();
                   1535: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1536: 	    @answer=split(/\&/,$reply);
                   1537: 	}                    ;
                   1538: 	my $i;
                   1539: 	for ($i=0;$i<=$#ids;$i++) {
                   1540: 	    if ($answer[$i]) {
                   1541: 		$returnhash{$ids[$i]}=$answer[$i];
                   1542: 	    } 
                   1543: 	}
                   1544:     } 
1.70      www      1545:     return %returnhash;
                   1546: }
                   1547: 
                   1548: # ------------------------------------- Find the IDs behind a list of usernames
                   1549: 
                   1550: sub idrget {
                   1551:     my ($udom,@unames)=@_;
                   1552:     my %returnhash=();
1.800     albertel 1553:     foreach my $uname (@unames) {
                   1554:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1555:     }
1.70      www      1556:     return %returnhash;
                   1557: }
                   1558: 
                   1559: # ------------------------------- Store away a list of names and associated IDs
                   1560: 
                   1561: sub idput {
                   1562:     my ($udom,%ids)=@_;
                   1563:     my %servers=();
1.800     albertel 1564:     foreach my $uname (keys(%ids)) {
                   1565: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1566:         my $uhom=&homeserver($uname,$udom);
1.70      www      1567:         if ($uhom ne 'no_host') {
1.800     albertel 1568:             my $id=&escape($ids{$uname});
1.70      www      1569:             $id=~tr/A-Z/a-z/;
1.800     albertel 1570:             my $esc_unam=&escape($uname);
1.70      www      1571: 	    if ($servers{$uhom}) {
1.800     albertel 1572: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1573:             } else {
1.800     albertel 1574:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1575:             }
                   1576:         }
1.191     harris41 1577:     }
1.800     albertel 1578:     foreach my $server (keys(%servers)) {
                   1579:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1580:     }
1.344     www      1581: }
                   1582: 
1.1231    raeburn  1583: # ---------------------------------------- Delete unwanted IDs from ids.db file 
                   1584: 
                   1585: sub iddel {
                   1586:     my ($udom,$idshashref,$uhome)=@_;
                   1587:     my %result=();
                   1588:     unless (ref($idshashref) eq 'HASH') {
                   1589:         return %result;
                   1590:     }
                   1591:     my %servers=();
                   1592:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1593:         my $uhom;
                   1594:         if ($uhome) {
                   1595:             $uhom = $uhome;
                   1596:         } else {
                   1597:             $uhom=&homeserver($uname,$udom);
                   1598:         }
                   1599:         if ($uhom ne 'no_host') {
                   1600:             if ($servers{$uhom}) {
                   1601:                 $servers{$uhom}.='&'.&escape($id);
                   1602:             } else {
                   1603:                 $servers{$uhom}=&escape($id);
                   1604:             }
                   1605:         }
                   1606:     }
                   1607:     foreach my $server (keys(%servers)) {
                   1608:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1609:     }
                   1610:     return %result;
                   1611: }
                   1612: 
1.1023    raeburn  1613: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1614: sub dump_dom {
1.1165    droeschl 1615:     my ($namespace, $udom, $regexp) = @_;
                   1616: 
                   1617:     $udom ||= $env{'user.domain'};
                   1618: 
                   1619:     return () unless $udom;
                   1620: 
                   1621:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1622: }
                   1623: 
1.1023    raeburn  1624: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1625: 
                   1626: sub get_dom {
1.860     raeburn  1627:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1628:     my $items='';
                   1629:     foreach my $item (@$storearr) {
                   1630:         $items.=&escape($item).'&';
                   1631:     }
                   1632:     $items=~s/\&$//;
1.860     raeburn  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 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1649:         my %returnhash;
1.875     albertel 1650:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1651:             return %returnhash;
                   1652:         }
1.806     raeburn  1653:         my @pairs=split(/\&/,$rep);
                   1654:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1655:             return @pairs;
                   1656:         }
                   1657:         my $i=0;
                   1658:         foreach my $item (@$storearr) {
                   1659:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1660:             $i++;
                   1661:         }
                   1662:         return %returnhash;
                   1663:     } else {
1.880     banghart 1664:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1665:     }
                   1666: }
                   1667: 
                   1668: # -------------------------------------------- put items in domain db files 
                   1669: 
                   1670: sub put_dom {
1.860     raeburn  1671:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1672:     if (!$udom) {
                   1673:         $udom=$env{'user.domain'};
                   1674:         if (defined(&domain($udom,'primary'))) {
                   1675:             $uhome=&domain($udom,'primary');
                   1676:         } else {
1.874     albertel 1677:             undef($uhome);
1.860     raeburn  1678:         }
                   1679:     } else {
                   1680:         if (!$uhome) {
                   1681:             if (defined(&domain($udom,'primary'))) {
                   1682:                 $uhome=&domain($udom,'primary');
                   1683:             }
                   1684:         }
                   1685:     } 
                   1686:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1687:         my $items='';
                   1688:         foreach my $item (keys(%$storehash)) {
                   1689:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1690:         }
                   1691:         $items=~s/\&$//;
                   1692:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1693:     } else {
1.860     raeburn  1694:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1695:     }
                   1696: }
                   1697: 
1.1023    raeburn  1698: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1699: sub newput_dom {
1.1023    raeburn  1700:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1701:     my $result;
                   1702:     if (!$udom) {
                   1703:         $udom=$env{'user.domain'};
                   1704:     }
1.1023    raeburn  1705:     if ($udom) {
                   1706:         my $uname = &get_domainconfiguser($udom);
                   1707:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1708:     }
                   1709:     return $result;
                   1710: }
                   1711: 
1.1023    raeburn  1712: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1713: sub del_dom {
1.1023    raeburn  1714:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1715:     if (ref($storearr) eq 'ARRAY') {
                   1716:         if (!$udom) {
                   1717:             $udom=$env{'user.domain'};
                   1718:         }
1.1023    raeburn  1719:         if ($udom) {
                   1720:             my $uname = &get_domainconfiguser($udom); 
                   1721:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1722:         }
                   1723:     }
                   1724: }
                   1725: 
1.1023    raeburn  1726: # ----------------------------------construct domainconfig user for a domain 
                   1727: sub get_domainconfiguser {
                   1728:     my ($udom) = @_;
                   1729:     return $udom.'-domainconfig';
                   1730: }
                   1731: 
1.837     raeburn  1732: sub retrieve_inst_usertypes {
                   1733:     my ($udom) = @_;
                   1734:     my (%returnhash,@order);
1.989     raeburn  1735:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1736:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1737:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1738:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1739:         @order = @{$domdefs{'inststatusorder'}};
                   1740:     } else {
                   1741:         if (defined(&domain($udom,'primary'))) {
                   1742:             my $uhome=&domain($udom,'primary');
                   1743:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1744:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1745:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1746:                 return (\%returnhash,\@order);
                   1747:             }
                   1748:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1749:             my @pairs=split(/\&/,$hashitems);
                   1750:             foreach my $item (@pairs) {
                   1751:                 my ($key,$value)=split(/=/,$item,2);
                   1752:                 $key = &unescape($key);
                   1753:                 next if ($key =~ /^error: 2 /);
                   1754:                 $returnhash{$key}=&thaw_unescape($value);
                   1755:             }
                   1756:             my @esc_order = split(/\&/,$orderitems);
                   1757:             foreach my $item (@esc_order) {
                   1758:                 push(@order,&unescape($item));
                   1759:             }
                   1760:         } else {
                   1761:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1762:         }
                   1763:     }
                   1764:     return (\%returnhash,\@order);
                   1765: }
                   1766: 
1.868     raeburn  1767: sub is_domainimage {
                   1768:     my ($url) = @_;
                   1769:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1770:         if (&domain($1) ne '') {
                   1771:             return '1';
                   1772:         }
                   1773:     }
                   1774:     return;
                   1775: }
                   1776: 
1.899     raeburn  1777: sub inst_directory_query {
                   1778:     my ($srch) = @_;
                   1779:     my $udom = $srch->{'srchdomain'};
                   1780:     my %results;
                   1781:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1782:     my $outcome;
1.899     raeburn  1783:     if ($homeserver ne '') {
1.904     albertel 1784: 	my $queryid=&reply("querysend:instdirsearch:".
                   1785: 			   &escape($srch->{'srchby'}).':'.
                   1786: 			   &escape($srch->{'srchterm'}).':'.
                   1787: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1788: 	my $host=&hostname($homeserver);
                   1789: 	if ($queryid !~/^\Q$host\E\_/) {
                   1790: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1791: 	    return;
                   1792: 	}
                   1793: 	my $response = &get_query_reply($queryid);
                   1794: 	my $maxtries = 5;
                   1795: 	my $tries = 1;
                   1796: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1797: 	    $response = &get_query_reply($queryid);
                   1798: 	    $tries ++;
                   1799: 	}
                   1800: 
                   1801:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1802:             if ($response eq 'unavailable') {
                   1803:                 $outcome = $response;
                   1804:             } else {
                   1805:                 $outcome = 'ok';
                   1806:                 my @matches = split(/\n/,$response);
                   1807:                 foreach my $match (@matches) {
                   1808:                     my ($key,$value) = split(/=/,$match);
                   1809:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1810:                 }
1.899     raeburn  1811:             }
                   1812:         }
                   1813:     }
1.909     raeburn  1814:     return ($outcome,%results);
1.899     raeburn  1815: }
                   1816: 
                   1817: sub usersearch {
                   1818:     my ($srch) = @_;
                   1819:     my $dom = $srch->{'srchdomain'};
                   1820:     my %results;
                   1821:     my %libserv = &all_library();
                   1822:     my $query = 'usersearch';
                   1823:     foreach my $tryserver (keys(%libserv)) {
                   1824:         if (&host_domain($tryserver) eq $dom) {
                   1825:             my $host=&hostname($tryserver);
                   1826:             my $queryid=
1.911     raeburn  1827:                 &reply("querysend:".&escape($query).':'.
                   1828:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1829:                        &escape($srch->{'srchtype'}).':'.
                   1830:                        &escape($srch->{'srchterm'}),$tryserver);
                   1831:             if ($queryid !~/^\Q$host\E\_/) {
                   1832:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1833:                 next;
1.899     raeburn  1834:             }
                   1835:             my $reply = &get_query_reply($queryid);
                   1836:             my $maxtries = 1;
                   1837:             my $tries = 1;
                   1838:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1839:                 $reply = &get_query_reply($queryid);
                   1840:                 $tries ++;
                   1841:             }
                   1842:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1843:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1844:             } else {
1.911     raeburn  1845:                 my @matches;
                   1846:                 if ($reply =~ /\n/) {
                   1847:                     @matches = split(/\n/,$reply);
                   1848:                 } else {
                   1849:                     @matches = split(/\&/,$reply);
                   1850:                 }
1.899     raeburn  1851:                 foreach my $match (@matches) {
                   1852:                     my ($uname,$udom,%userhash);
1.911     raeburn  1853:                     foreach my $entry (split(/:/,$match)) {
                   1854:                         my ($key,$value) =
                   1855:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1856:                         $userhash{$key} = $value;
                   1857:                         if ($key eq 'username') {
                   1858:                             $uname = $value;
                   1859:                         } elsif ($key eq 'domain') {
                   1860:                             $udom = $value;
1.911     raeburn  1861:                         }
1.899     raeburn  1862:                     }
                   1863:                     $results{$uname.':'.$udom} = \%userhash;
                   1864:                 }
                   1865:             }
                   1866:         }
                   1867:     }
                   1868:     return %results;
                   1869: }
                   1870: 
1.912     raeburn  1871: sub get_instuser {
                   1872:     my ($udom,$uname,$id) = @_;
                   1873:     my $homeserver = &domain($udom,'primary');
                   1874:     my ($outcome,%results);
                   1875:     if ($homeserver ne '') {
                   1876:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1877:                            &escape($id).':'.&escape($udom),$homeserver);
                   1878:         my $host=&hostname($homeserver);
                   1879:         if ($queryid !~/^\Q$host\E\_/) {
                   1880:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1881:             return;
                   1882:         }
                   1883:         my $response = &get_query_reply($queryid);
                   1884:         my $maxtries = 5;
                   1885:         my $tries = 1;
                   1886:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1887:             $response = &get_query_reply($queryid);
                   1888:             $tries ++;
                   1889:         }
                   1890:         if (!&error($response) && $response ne 'refused') {
                   1891:             if ($response eq 'unavailable') {
                   1892:                 $outcome = $response;
                   1893:             } else {
                   1894:                 $outcome = 'ok';
                   1895:                 my @matches = split(/\n/,$response);
                   1896:                 foreach my $match (@matches) {
                   1897:                     my ($key,$value) = split(/=/,$match);
                   1898:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1899:                 }
                   1900:             }
                   1901:         }
                   1902:     }
                   1903:     my %userinfo;
                   1904:     if (ref($results{$uname}) eq 'HASH') {
                   1905:         %userinfo = %{$results{$uname}};
                   1906:     } 
                   1907:     return ($outcome,%userinfo);
                   1908: }
                   1909: 
                   1910: sub inst_rulecheck {
1.923     raeburn  1911:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1912:     my %returnhash;
                   1913:     if ($udom ne '') {
                   1914:         if (ref($rules) eq 'ARRAY') {
                   1915:             @{$rules} = map {&escape($_);} (@{$rules});
                   1916:             my $rulestr = join(':',@{$rules});
                   1917:             my $homeserver=&domain($udom,'primary');
                   1918:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1919:                 my $response;
                   1920:                 if ($item eq 'username') {                
                   1921:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1922:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1923:                                               $homeserver));
1.923     raeburn  1924:                 } elsif ($item eq 'id') {
                   1925:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1926:                                               ':'.&escape($id).':'.$rulestr,
                   1927:                                               $homeserver));
1.945     raeburn  1928:                 } elsif ($item eq 'selfcreate') {
                   1929:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1930:                                                &escape($udom).':'.&escape($uname).
                   1931:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1932:                 }
1.912     raeburn  1933:                 if ($response ne 'refused') {
                   1934:                     my @pairs=split(/\&/,$response);
                   1935:                     foreach my $item (@pairs) {
                   1936:                         my ($key,$value)=split(/=/,$item,2);
                   1937:                         $key = &unescape($key);
                   1938:                         next if ($key =~ /^error: 2 /);
                   1939:                         $returnhash{$key}=&thaw_unescape($value);
                   1940:                     }
                   1941:                 }
                   1942:             }
                   1943:         }
                   1944:     }
                   1945:     return %returnhash;
                   1946: }
                   1947: 
                   1948: sub inst_userrules {
1.923     raeburn  1949:     my ($udom,$check) = @_;
1.912     raeburn  1950:     my (%ruleshash,@ruleorder);
                   1951:     if ($udom ne '') {
                   1952:         my $homeserver=&domain($udom,'primary');
                   1953:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1954:             my $response;
                   1955:             if ($check eq 'id') {
                   1956:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1957:                                  $homeserver);
1.943     raeburn  1958:             } elsif ($check eq 'email') {
                   1959:                 $response=&reply('instemailrules:'.&escape($udom),
                   1960:                                  $homeserver);
1.923     raeburn  1961:             } else {
                   1962:                 $response=&reply('instuserrules:'.&escape($udom),
                   1963:                                  $homeserver);
                   1964:             }
1.912     raeburn  1965:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1966:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1967:                 ($response ne 'no_such_host')) {
                   1968:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1969:                 my @pairs=split(/\&/,$hashitems);
                   1970:                 foreach my $item (@pairs) {
                   1971:                     my ($key,$value)=split(/=/,$item,2);
                   1972:                     $key = &unescape($key);
                   1973:                     next if ($key =~ /^error: 2 /);
                   1974:                     $ruleshash{$key}=&thaw_unescape($value);
                   1975:                 }
                   1976:                 my @esc_order = split(/\&/,$orderitems);
                   1977:                 foreach my $item (@esc_order) {
                   1978:                     push(@ruleorder,&unescape($item));
                   1979:                 }
                   1980:             }
                   1981:         }
                   1982:     }
                   1983:     return (\%ruleshash,\@ruleorder);
                   1984: }
                   1985: 
1.976     raeburn  1986: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1987: 
                   1988: sub get_domain_defaults {
1.1240    raeburn  1989:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  1990:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  1991:     my $cachetime = 60*60*24;
1.1240    raeburn  1992:     unless ($ignore_cache) {
                   1993:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1994:         if (defined($cached)) {
                   1995:             if (ref($result) eq 'HASH') {
                   1996:                 return %{$result};
                   1997:             }
1.943     raeburn  1998:         }
                   1999:     }
                   2000:     my %domdefaults;
                   2001:     my %domconfig =
1.989     raeburn  2002:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2003:                                   'requestcourses','inststatus',
1.1183    raeburn  2004:                                   'coursedefaults','usersessions',
                   2005:                                   'requestauthor'],$domain);
1.943     raeburn  2006:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2007:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2008:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2009:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2010:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2011:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2012:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2013:     } else {
                   2014:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2015:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2016:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2017:     }
1.976     raeburn  2018:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2019:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2020:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2021:         } else {
                   2022:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2023:         }
1.1177    raeburn  2024:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2025:         foreach my $item (@usertools) {
                   2026:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2027:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2028:             }
                   2029:         }
1.1229    raeburn  2030:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2031:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2032:         }
1.976     raeburn  2033:     }
1.985     raeburn  2034:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  2035:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  2036:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2037:         }
                   2038:     }
1.1183    raeburn  2039:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2040:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2041:     }
1.989     raeburn  2042:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2043:         foreach my $item ('inststatustypes','inststatusorder') {
                   2044:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2045:         }
                   2046:     }
1.1047    raeburn  2047:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2048:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216    raeburn  2049:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2050:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2051:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
                   2052:         }
1.1230    raeburn  2053:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2054:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
                   2055:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
                   2056:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
                   2057:         }
1.1047    raeburn  2058:     }
1.1073    raeburn  2059:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2060:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2061:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2062:         }
                   2063:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2064:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2065:         }
                   2066:     }
1.1219    raeburn  2067:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2068:     return %domdefaults;
                   2069: }
                   2070: 
1.344     www      2071: # --------------------------------------------------- Assign a key to a student
                   2072: 
                   2073: sub assign_access_key {
1.364     www      2074: #
                   2075: # a valid key looks like uname:udom#comments
                   2076: # comments are being appended
                   2077: #
1.498     www      2078:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2079:     $kdom=
1.620     albertel 2080:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2081:     $knum=
1.620     albertel 2082:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2083:     $cdom=
1.620     albertel 2084:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2085:     $cnum=
1.620     albertel 2086:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2087:     $udom=$env{'user.name'} unless (defined($udom));
                   2088:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2089:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2090:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2091:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2092:                                                   # assigned to this person
                   2093:                                                   # - this should not happen,
1.345     www      2094:                                                   # unless something went wrong
                   2095:                                                   # the first time around
                   2096: # ready to assign
1.364     www      2097:         $logentry=$1.'; '.$logentry;
1.496     www      2098:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2099:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2100: # key now belongs to user
1.346     www      2101: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2102:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2103:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2104:                 return 'ok';
                   2105:             } else {
                   2106:                 return 
                   2107:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2108: 	    }
                   2109:         } else {
                   2110:             return 'error: Could not assign key, try again later.';
                   2111:         }
1.364     www      2112:     } elsif (!$existing{$ckey}) {
1.345     www      2113: # the key does not exist
                   2114: 	return 'error: The key does not exist';
                   2115:     } else {
                   2116: # the key is somebody else's
                   2117: 	return 'error: The key is already in use';
                   2118:     }
1.344     www      2119: }
                   2120: 
1.364     www      2121: # ------------------------------------------ put an additional comment on a key
                   2122: 
                   2123: sub comment_access_key {
                   2124: #
                   2125: # a valid key looks like uname:udom#comments
                   2126: # comments are being appended
                   2127: #
                   2128:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2129:     $cdom=
1.620     albertel 2130:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2131:     $cnum=
1.620     albertel 2132:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2133:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2134:     if ($existing{$ckey}) {
                   2135:         $existing{$ckey}.='; '.$logentry;
                   2136: # ready to assign
1.367     www      2137:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2138:                                                  $cdom,$cnum) eq 'ok') {
                   2139: 	    return 'ok';
                   2140:         } else {
                   2141: 	    return 'error: Count not store comment.';
                   2142:         }
                   2143:     } else {
                   2144: # the key does not exist
                   2145: 	return 'error: The key does not exist';
                   2146:     }
                   2147: }
                   2148: 
1.344     www      2149: # ------------------------------------------------------ Generate a set of keys
                   2150: 
                   2151: sub generate_access_keys {
1.364     www      2152:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2153:     $cdom=
1.620     albertel 2154:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2155:     $cnum=
1.620     albertel 2156:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2157:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2158:     unless (($cdom) && ($cnum)) { return 0; }
                   2159:     if ($number>10000) { return 0; }
                   2160:     sleep(2); # make sure don't get same seed twice
                   2161:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2162:     my $total=0;
                   2163:     for (my $i=1;$i<=$number;$i++) {
                   2164:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2165:                   sprintf("%lx",int(100000*rand)).'-'.
                   2166:                   sprintf("%lx",int(100000*rand));
                   2167:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2168:        $newkey=~s/0/h/g; # and also 0 and O
                   2169:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2170:        if ($existing{$newkey}) {
                   2171:            $i--;
                   2172:        } else {
1.364     www      2173: 	  if (&put('accesskeys',
                   2174:               { $newkey => '# generated '.localtime().
1.620     albertel 2175:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2176:                            '; '.$logentry },
                   2177: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2178:               $total++;
                   2179: 	  }
                   2180:        }
                   2181:     }
1.620     albertel 2182:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2183:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2184:     return $total;
                   2185: }
                   2186: 
                   2187: # ------------------------------------------------------- Validate an accesskey
                   2188: 
                   2189: sub validate_access_key {
                   2190:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2191:     $cdom=
1.620     albertel 2192:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2193:     $cnum=
1.620     albertel 2194:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2195:     $udom=$env{'user.domain'} unless (defined($udom));
                   2196:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2197:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2198:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2199: }
                   2200: 
                   2201: # ------------------------------------- Find the section of student in a course
1.652     albertel 2202: sub devalidate_getsection_cache {
                   2203:     my ($udom,$unam,$courseid)=@_;
                   2204:     my $hashid="$udom:$unam:$courseid";
                   2205:     &devalidate_cache_new('getsection',$hashid);
                   2206: }
1.298     matthew  2207: 
1.815     albertel 2208: sub courseid_to_courseurl {
                   2209:     my ($courseid) = @_;
                   2210:     #already url style courseid
                   2211:     return $courseid if ($courseid =~ m{^/});
                   2212: 
                   2213:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2214: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2215: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2216: 	return "/$cdom/$cnum";
                   2217:     }
                   2218: 
                   2219:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2220:     if (exists($courseinfo{'num'})) {
                   2221: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2222:     }
                   2223: 
                   2224:     return undef;
                   2225: }
                   2226: 
1.298     matthew  2227: sub getsection {
                   2228:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2229:     my $cachetime=1800;
1.551     albertel 2230: 
                   2231:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2232:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2233:     if (defined($cached)) { return $result; }
                   2234: 
1.298     matthew  2235:     my %Pending; 
                   2236:     my %Expired;
                   2237:     #
                   2238:     # Each role can either have not started yet (pending), be active, 
                   2239:     #    or have expired.
                   2240:     #
                   2241:     # If there is an active role, we are done.
                   2242:     #
                   2243:     # If there is more than one role which has not started yet, 
                   2244:     #     choose the one which will start sooner
                   2245:     # If there is one role which has not started yet, return it.
                   2246:     #
                   2247:     # If there is more than one expired role, choose the one which ended last.
                   2248:     # If there is a role which has expired, return it.
                   2249:     #
1.815     albertel 2250:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2251:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2252:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2253:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2254:         my $section=$1;
                   2255:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2256:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2257:         my $now=time;
1.548     albertel 2258:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2259:             $Expired{$end}=$section;
                   2260:             next;
                   2261:         }
1.548     albertel 2262:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2263:             $Pending{$start}=$section;
                   2264:             next;
                   2265:         }
1.599     albertel 2266:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2267:     }
                   2268:     #
                   2269:     # Presumedly there will be few matching roles from the above
                   2270:     # loop and the sorting time will be negligible.
                   2271:     if (scalar(keys(%Pending))) {
                   2272:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2273:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2274:     } 
                   2275:     if (scalar(keys(%Expired))) {
                   2276:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2277:         my $time = pop(@sorted);
1.599     albertel 2278:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2279:     }
1.599     albertel 2280:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2281: }
1.70      www      2282: 
1.599     albertel 2283: sub save_cache {
                   2284:     &purge_remembered();
1.722     albertel 2285:     #&Apache::loncommon::validate_page();
1.620     albertel 2286:     undef(%env);
1.780     albertel 2287:     undef($env_loaded);
1.599     albertel 2288: }
1.452     albertel 2289: 
1.599     albertel 2290: my $to_remember=-1;
                   2291: my %remembered;
                   2292: my %accessed;
                   2293: my $kicks=0;
                   2294: my $hits=0;
1.849     albertel 2295: sub make_key {
                   2296:     my ($name,$id) = @_;
1.872     albertel 2297:     if (length($id) > 65 
                   2298: 	&& length(&escape($id)) > 200) {
                   2299: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2300:     }
1.849     albertel 2301:     return &escape($name.':'.$id);
                   2302: }
                   2303: 
1.599     albertel 2304: sub devalidate_cache_new {
                   2305:     my ($name,$id,$debug) = @_;
                   2306:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2307:     $id=&make_key($name,$id);
1.599     albertel 2308:     $memcache->delete($id);
                   2309:     delete($remembered{$id});
                   2310:     delete($accessed{$id});
                   2311: }
                   2312: 
                   2313: sub is_cached_new {
                   2314:     my ($name,$id,$debug) = @_;
1.849     albertel 2315:     $id=&make_key($name,$id);
1.599     albertel 2316:     if (exists($remembered{$id})) {
1.1133    foxr     2317: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2318: 	$accessed{$id}=[&gettimeofday()];
                   2319: 	$hits++;
                   2320: 	return ($remembered{$id},1);
                   2321:     }
                   2322:     my $value = $memcache->get($id);
                   2323:     if (!(defined($value))) {
                   2324: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2325: 	return (undef,undef);
1.416     albertel 2326:     }
1.599     albertel 2327:     if ($value eq '__undef__') {
                   2328: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2329: 	$value=undef;
                   2330:     }
                   2331:     &make_room($id,$value,$debug);
                   2332:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2333:     return ($value,1);
                   2334: }
                   2335: 
                   2336: sub do_cache_new {
                   2337:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2338:     $id=&make_key($name,$id);
1.599     albertel 2339:     my $setvalue=$value;
                   2340:     if (!defined($setvalue)) {
                   2341: 	$setvalue='__undef__';
                   2342:     }
1.623     albertel 2343:     if (!defined($time) ) {
                   2344: 	$time=600;
                   2345:     }
1.599     albertel 2346:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2347:     my $result = $memcache->set($id,$setvalue,$time);
                   2348:     if (! $result) {
1.872     albertel 2349: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2350: 	$memcache->disconnect_all();
1.872     albertel 2351:     }
1.600     albertel 2352:     # need to make a copy of $value
1.919     albertel 2353:     &make_room($id,$value,$debug);
1.599     albertel 2354:     return $value;
                   2355: }
                   2356: 
                   2357: sub make_room {
                   2358:     my ($id,$value,$debug)=@_;
1.919     albertel 2359: 
                   2360:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2361:                                     : $value;
1.599     albertel 2362:     if ($to_remember<0) { return; }
                   2363:     $accessed{$id}=[&gettimeofday()];
                   2364:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2365:     my $to_kick;
                   2366:     my $max_time=0;
                   2367:     foreach my $other (keys(%accessed)) {
                   2368: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2369: 	    $to_kick=$other;
                   2370: 	    $max_time=&tv_interval($accessed{$other});
                   2371: 	}
                   2372:     }
                   2373:     delete($remembered{$to_kick});
                   2374:     delete($accessed{$to_kick});
                   2375:     $kicks++;
                   2376:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2377:     return;
                   2378: }
                   2379: 
1.599     albertel 2380: sub purge_remembered {
1.604     albertel 2381:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2382:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2383:     undef(%remembered);
                   2384:     undef(%accessed);
1.428     albertel 2385: }
1.70      www      2386: # ------------------------------------- Read an entry from a user's environment
                   2387: 
                   2388: sub userenvironment {
                   2389:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2390:     my $items;
                   2391:     foreach my $item (@what) {
                   2392:         $items.=&escape($item).'&';
                   2393:     }
                   2394:     $items=~s/\&$//;
1.70      www      2395:     my %returnhash=();
1.1009    raeburn  2396:     my $uhome = &homeserver($unam,$udom);
                   2397:     unless ($uhome eq 'no_host') {
                   2398:         my @answer=split(/\&/, 
                   2399:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2400:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2401:             return %returnhash;
                   2402:         }
1.1009    raeburn  2403:         my $i;
                   2404:         for ($i=0;$i<=$#what;$i++) {
                   2405: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2406:         }
1.70      www      2407:     }
                   2408:     return %returnhash;
1.1       albertel 2409: }
                   2410: 
1.617     albertel 2411: # ---------------------------------------------------------- Get a studentphoto
                   2412: sub studentphoto {
                   2413:     my ($udom,$unam,$ext) = @_;
                   2414:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2415:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2416:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2417:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2418:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2419:             } else {
                   2420:                 my ($result,$perm_reqd)=
1.707     albertel 2421: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2422:                 if ($result eq 'ok') {
                   2423:                     if (!($perm_reqd eq 'yes')) {
                   2424:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2425:                     }
                   2426:                 }
                   2427:             }
                   2428:         }
                   2429:     } else {
                   2430:         my ($result,$perm_reqd) = 
1.707     albertel 2431: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2432:         if ($result eq 'ok') {
                   2433:             if (!($perm_reqd eq 'yes')) {
                   2434:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2435:             }
                   2436:         }
                   2437:     }
                   2438:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2439: }
                   2440: 
                   2441: sub retrievestudentphoto {
                   2442:     my ($udom,$unam,$ext,$type) = @_;
                   2443:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2444:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2445:     if ($ret eq 'ok') {
                   2446:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2447:         if ($type eq 'thumbnail') {
                   2448:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2449:         }
                   2450:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2451:         return $tokenurl;
                   2452:     } else {
                   2453:         if ($type eq 'thumbnail') {
                   2454:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2455:         } else { 
                   2456:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2457:         }
1.617     albertel 2458:     }
                   2459: }
                   2460: 
1.263     www      2461: # -------------------------------------------------------------------- New chat
                   2462: 
                   2463: sub chatsend {
1.724     raeburn  2464:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2465:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2466:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2467:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2468:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2469: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2470: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2471: }
                   2472: 
                   2473: # ------------------------------------------ Find current version of a resource
                   2474: 
                   2475: sub getversion {
                   2476:     my $fname=&clutter(shift);
1.1189    raeburn  2477:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2478:     return &currentversion(&filelocation('',$fname));
                   2479: }
                   2480: 
                   2481: sub currentversion {
                   2482:     my $fname=shift;
                   2483:     my $author=$fname;
                   2484:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2485:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2486:     my $home=&homeserver($uname,$udom);
1.292     www      2487:     if ($home eq 'no_host') { 
                   2488:         return -1; 
                   2489:     }
1.1112    www      2490:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2491:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2492: 	return -1;
                   2493:     }
1.1112    www      2494:     return $answer;
1.263     www      2495: }
                   2496: 
1.1111    www      2497: #
                   2498: # Return special version number of resource if set by override, empty otherwise
                   2499: #
                   2500: sub usedversion {
                   2501:     my $fname=shift;
                   2502:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2503:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2504:     if ($urlversion) { return $urlversion; }
                   2505:     return '';
                   2506: }
                   2507: 
1.1       albertel 2508: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2509: 
1.1       albertel 2510: sub subscribe {
                   2511:     my $fname=shift;
1.761     raeburn  2512:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2513:     $fname=~s/[\n\r]//g;
1.1       albertel 2514:     my $author=$fname;
                   2515:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2516:     my ($udom,$uname)=split(/\//,$author);
                   2517:     my $home=homeserver($uname,$udom);
1.335     albertel 2518:     if ($home eq 'no_host') {
                   2519:         return 'not_found';
1.1       albertel 2520:     }
                   2521:     my $answer=reply("sub:$fname",$home);
1.64      www      2522:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2523: 	$answer.=' by '.$home;
                   2524:     }
1.1       albertel 2525:     return $answer;
                   2526: }
                   2527:     
1.8       www      2528: # -------------------------------------------------------------- Replicate file
                   2529: 
                   2530: sub repcopy {
                   2531:     my $filename=shift;
1.23      www      2532:     $filename=~s/\/+/\//g;
1.1142    raeburn  2533:     my $londocroot = $perlvar{'lonDocRoot'};
                   2534:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2535:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2536:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2537: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2538: 	return &repcopy_userfile($filename);
                   2539:     }
1.532     albertel 2540:     $filename=~s/[\n\r]//g;
1.8       www      2541:     my $transname="$filename.in.transfer";
1.828     www      2542: # FIXME: this should flock
1.607     raeburn  2543:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2544:     my $remoteurl=subscribe($filename);
1.64      www      2545:     if ($remoteurl =~ /^con_lost by/) {
                   2546: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2547:            return 'unavailable';
1.8       www      2548:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2549: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2550: 	   return 'not_found';
1.64      www      2551:     } elsif ($remoteurl =~ /^rejected by/) {
                   2552: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2553:            return 'forbidden';
1.20      www      2554:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2555:            return 'ok';
1.8       www      2556:     } else {
1.290     www      2557:         my $author=$filename;
                   2558:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2559:         my ($udom,$uname)=split(/\//,$author);
                   2560:         my $home=homeserver($uname,$udom);
                   2561:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2562:            my @parts=split(/\//,$filename);
                   2563:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2564:            if ($path ne "$londocroot/res") {
1.8       www      2565:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2566: 	       return 'bad_request';
1.8       www      2567:            }
                   2568:            my $count;
                   2569:            for ($count=5;$count<$#parts;$count++) {
                   2570:                $path.="/$parts[$count]";
                   2571:                if ((-e $path)!=1) {
                   2572: 		   mkdir($path,0777);
                   2573:                }
                   2574:            }
                   2575:            my $ua=new LWP::UserAgent;
                   2576:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2577:            my $response=$ua->request($request,$transname);
                   2578:            if ($response->is_error()) {
                   2579: 	       unlink($transname);
                   2580:                my $message=$response->status_line;
1.672     albertel 2581:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2582:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2583:                return 'unavailable';
1.8       www      2584:            } else {
1.16      www      2585: 	       if ($remoteurl!~/\.meta$/) {
                   2586:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2587:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2588:                   if ($mresponse->is_error()) {
                   2589: 		      unlink($filename.'.meta');
                   2590:                       &logthis(
1.672     albertel 2591:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2592:                   }
                   2593: 	       }
1.8       www      2594:                rename($transname,$filename);
1.607     raeburn  2595:                return 'ok';
1.8       www      2596:            }
1.290     www      2597:        }
1.8       www      2598:     }
1.330     www      2599: }
                   2600: 
                   2601: # ------------------------------------------------ Get server side include body
                   2602: sub ssi_body {
1.381     albertel 2603:     my ($filelink,%form)=@_;
1.606     matthew  2604:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2605:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2606:     }
1.953     www      2607:     my $output='';
                   2608:     my $response;
1.980     raeburn  2609:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2610:        ($output,$response)=&externalssi($filelink);
1.953     www      2611:     } else {
1.1004    droeschl 2612:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2613:        $filelink .= 'inhibitmenu=yes';
1.953     www      2614:        ($output,$response)=&ssi($filelink,%form);
                   2615:     }
1.778     albertel 2616:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2617:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2618:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2619:     if (wantarray) {
                   2620:         return ($output, $response);
                   2621:     } else {
                   2622:         return $output;
                   2623:     }
1.8       www      2624: }
                   2625: 
1.15      www      2626: # --------------------------------------------------------- Server Side Include
                   2627: 
1.782     albertel 2628: sub absolute_url {
                   2629:     my ($host_name) = @_;
                   2630:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2631:     if ($host_name eq '') {
                   2632: 	$host_name = $ENV{'SERVER_NAME'};
                   2633:     }
                   2634:     return $protocol.$host_name;
                   2635: }
                   2636: 
1.942     foxr     2637: #
                   2638: #   Server side include.
                   2639: # Parameters:
                   2640: #  fn     Possibly encrypted resource name/id.
                   2641: #  form   Hash that describes how the rendering should be done
                   2642: #         and other things.
1.944     foxr     2643: # Returns:
1.950     raeburn  2644: #   Scalar context: The content of the response.
                   2645: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2646: #     
1.15      www      2647: sub ssi {
                   2648: 
1.944     foxr     2649:     my ($fn,%form)=@_;
1.15      www      2650:     my $ua=new LWP::UserAgent;
1.23      www      2651:     my $request;
1.711     albertel 2652: 
                   2653:     $form{'no_update_last_known'}=1;
1.895     albertel 2654:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2655:     if (%form) {
1.782     albertel 2656:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2657:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2658:     } else {
1.782     albertel 2659:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2660:     }
                   2661: 
1.15      www      2662:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2663:     my $response= $ua->request($request);
1.1182    foxr     2664:     my $content = $response->content;
                   2665: 
                   2666: 
1.944     foxr     2667:     if (wantarray) {
1.1173    foxr     2668: 	return ($content, $response);
1.944     foxr     2669:     } else {
1.1173    foxr     2670: 	return $content;
1.942     foxr     2671:     }
1.324     www      2672: }
                   2673: 
                   2674: sub externalssi {
                   2675:     my ($url)=@_;
                   2676:     my $ua=new LWP::UserAgent;
                   2677:     my $request=new HTTP::Request('GET',$url);
                   2678:     my $response=$ua->request($request);
1.954     raeburn  2679:     if (wantarray) {
                   2680:         return ($response->content, $response);
                   2681:     } else {
                   2682:         return $response->content;
                   2683:     }
1.15      www      2684: }
1.254     www      2685: 
1.492     albertel 2686: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2687: 
                   2688: sub allowuploaded {
                   2689:     my ($srcurl,$url)=@_;
                   2690:     $url=&clutter(&declutter($url));
                   2691:     my $dir=$url;
                   2692:     $dir=~s/\/[^\/]+$//;
                   2693:     my %httpref=();
                   2694:     my $httpurl=&hreflocation('',$url);
                   2695:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2696:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2697: }
1.477     raeburn  2698: 
1.1193    raeburn  2699: #
                   2700: # Determine if the current user should be able to edit a particular resource,
                   2701: # when viewing in course context.
                   2702: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2703: #     Functions.
                   2704: # (b) When displaying folder contents in course editor, used to determine if
                   2705: #     "Edit" link will be displayed alongside resource.
                   2706: #
1.1196    raeburn  2707: #  input: six args -- filename (decluttered), course number, course domain,
                   2708: #                   url, symb (if registered) and group (if this is a group
                   2709: #                   item -- e.g., bulletin board, group page etc.).
                   2710: #  output: array of five scalars -- 
1.1193    raeburn  2711: #          $cfile -- url for file editing if editable on current server
                   2712: #          $home -- homeserver of resource (i.e., for author if published,
                   2713: #                                           or course if uploaded.).
                   2714: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2715: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2716: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2717: #
                   2718: 
                   2719: sub can_edit_resource {
1.1194    raeburn  2720:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2721:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2722: #
                   2723: # For aboutme pages user can only edit his/her own.
                   2724: #
1.1199    raeburn  2725:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2726:         my ($sdom,$sname) = ($1,$2);
                   2727:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2728:             $home = $env{'user.home'};
                   2729:             $cfile = $resurl;
                   2730:             if ($env{'form.forceedit'}) {
                   2731:                 $forceview = 1;
                   2732:             } else {
                   2733:                 $forceedit = 1;
                   2734:             }
                   2735:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2736:         } else {
                   2737:             return;
                   2738:         }
                   2739:     }
                   2740: 
                   2741:     if ($env{'request.course.id'}) {
                   2742:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2743:         if ($group ne '') {
                   2744: # if this is a group homepage or group bulletin board, check group privs
                   2745:             my $allowed = 0;
1.1197    raeburn  2746:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2747:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2748:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2749:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2750:                     $allowed = 1;
                   2751:                 }
1.1197    raeburn  2752:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2753:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2754:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2755:                     $allowed = 1;
                   2756:                 }
                   2757:             }
                   2758:             if ($allowed) {
                   2759:                 $home=&homeserver($cnum,$cdom);
                   2760:                 if ($env{'form.forceedit'}) {
                   2761:                     $forceview = 1;
                   2762:                 } else {
                   2763:                     $forceedit = 1;
                   2764:                 }
                   2765:                 $cfile = $resurl;
                   2766:             } else {
                   2767:                 return;
                   2768:             }
                   2769:         } else {
1.1208    raeburn  2770:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2771:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2772:                     return;
                   2773:                 }
                   2774:             } elsif (!$crsedit) {
1.1194    raeburn  2775: #
                   2776: # No edit allowed where CC has switched to student role.
                   2777: #
                   2778:                 return;
                   2779:             }
                   2780:         }
                   2781:     }
                   2782: 
1.1193    raeburn  2783:     if ($file ne '') {
                   2784:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2785:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2786:                 $uploaded = 1;
                   2787:                 $incourse = 1;
1.1193    raeburn  2788:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2789:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2790:                     if ($env{'form.forceedit'}) {
                   2791:                         $forceview = 1;
                   2792:                     } else {
                   2793:                         $forceedit = 1;
                   2794:                     }
1.1194    raeburn  2795:                 }
                   2796:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2797:                 $incourse = 1;
                   2798:                 if ($env{'form.forceedit'}) {
                   2799:                     $forceview = 1;
                   2800:                 } else {
                   2801:                     $forceedit = 1;
                   2802:                 }
                   2803:                 $cfile = $resurl;
                   2804:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2805:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2806:                     $incourse = 1;
                   2807:                     if ($env{'form.forceedit'}) {
                   2808:                         $forceview = 1;
                   2809:                     } else {
                   2810:                         $forceedit = 1;
                   2811:                     }
                   2812:                     $cfile = $resurl;
1.1199    raeburn  2813:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2814:                     $incourse = 1;
                   2815:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2816:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2817:                     $incourse = 1;
1.1199    raeburn  2818:                     if ($env{'form.forceedit'}) {
                   2819:                         $forceview = 1;
                   2820:                     } else {
                   2821:                         $forceedit = 1;
                   2822:                     }
                   2823:                     $cfile = $resurl;
1.1208    raeburn  2824:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2825:                     $incourse = 1;
                   2826:                     if ($env{'form.forceedit'}) {
                   2827:                         $forceview = 1;
                   2828:                     } else {
                   2829:                         $forceedit = 1;
                   2830:                     }
                   2831:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2832:                 }
                   2833:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2834:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2835:                 if (&is_on_map($template)) { 
                   2836:                     $incourse = 1;
                   2837:                     $forceview = 1;
                   2838:                     $cfile = $template;
1.1193    raeburn  2839:                 }
1.1199    raeburn  2840:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2841:                     $incourse = 1;
                   2842:                     if ($env{'form.forceedit'}) {
                   2843:                         $forceview = 1;
                   2844:                     } else {
                   2845:                         $forceedit = 1;
                   2846:                     }
                   2847:                     $cfile = $resurl;
                   2848:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2849:                 $incourse = 1;
                   2850:                 $forceview = 1;
                   2851:                 if ($symb) {
                   2852:                     my ($map,$id,$res)=&decode_symb($symb);
                   2853:                     $env{'request.symb'} = $symb;
                   2854:                     $cfile = &clutter($res);
                   2855:                 } else {
                   2856:                     $cfile = $env{'form.suppurl'};
                   2857:                     $cfile =~ s{^http://}{};
                   2858:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2859:                 }
1.1234    raeburn  2860:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2861:                 if ($env{'form.forceedit'}) {
                   2862:                     $forceview = 1;
                   2863:                 } else {
                   2864:                     $forceedit = 1;
                   2865:                 }
                   2866:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  2867:             }
                   2868:         }
1.1194    raeburn  2869:         if ($uploaded || $incourse) {
                   2870:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2871:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2872:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2873:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2874:             # Check that the user has permission to edit this resource
                   2875:             my $setpriv = 1;
                   2876:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2877:             if (defined($cfudom)) {
                   2878:                 $home=&homeserver($cfuname,$cfudom);
                   2879:                 $cfile=$file;
                   2880:             }
                   2881:         }
1.1194    raeburn  2882:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2883:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2884:             my @ids=&current_machine_ids();
                   2885:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2886:                 $switchserver=1;
                   2887:             }
                   2888:         }
                   2889:     }
1.1194    raeburn  2890:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2891: }
                   2892: 
                   2893: sub is_course_upload {
                   2894:     my ($file,$cnum,$cdom) = @_;
                   2895:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2896:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2897:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2898:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2899:         return 1;
                   2900:     }
                   2901:     return;
                   2902: }
                   2903: 
1.1194    raeburn  2904: sub in_course {
1.1195    raeburn  2905:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2906:     if ($hideprivileged) {
                   2907:         my $skipuser;
1.1219    raeburn  2908:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2909:         my @possdoms = ($cdom);  
                   2910:         if ($coursehash{'checkforpriv'}) { 
                   2911:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   2912:         }
                   2913:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  2914:             $skipuser = 1;
                   2915:             if ($coursehash{'nothideprivileged'}) {
                   2916:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2917:                     my $user;
                   2918:                     if ($item =~ /:/) {
                   2919:                         $user = $item;
                   2920:                     } else {
                   2921:                         $user = join(':',split(/[\@]/,$item));
                   2922:                     }
                   2923:                     if ($user eq $uname.':'.$udom) {
                   2924:                         undef($skipuser);
                   2925:                         last;
                   2926:                     }
                   2927:                 }
                   2928:             }
                   2929:             if ($skipuser) {
                   2930:                 return 0;
                   2931:             }
                   2932:         }
                   2933:     }
1.1194    raeburn  2934:     $type ||= 'any';
                   2935:     if (!defined($cdom) || !defined($cnum)) {
                   2936:         my $cid  = $env{'request.course.id'};
                   2937:         $cdom = $env{'course.'.$cid.'.domain'};
                   2938:         $cnum = $env{'course.'.$cid.'.num'};
                   2939:     }
                   2940:     my $typesref;
1.1195    raeburn  2941:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  2942:         $typesref = ['active','previous','future'];
                   2943:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2944:         $typesref = [$type];
                   2945:     }
                   2946:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2947:                               $typesref,undef,[$cdom]);
                   2948:     my ($tmp) = keys(%roles);
                   2949:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2950:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2951:     if (@course_roles > 0) {
                   2952:         return 1;
                   2953:     }
                   2954:     return 0;
                   2955: }
                   2956: 
1.478     albertel 2957: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2958: # input: action, courseID, current domain, intended
1.637     raeburn  2959: #        path to file, source of file, instruction to parse file for objects,
                   2960: #        ref to hash for embedded objects,
                   2961: #        ref to hash for codebase of java objects.
1.1095    raeburn  2962: #        reference to scalar to accommodate mime type determined
                   2963: #          from File::MMagic if $parser = parse.
1.637     raeburn  2964: #
1.485     raeburn  2965: # output: url to file (if action was uploaddoc), 
                   2966: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2967: #
1.478     albertel 2968: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2969: # course.
1.477     raeburn  2970: #
1.478     albertel 2971: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2972: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2973: #          course's home server.
1.477     raeburn  2974: #
1.478     albertel 2975: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2976: #          be copied from $source (current location) to 
                   2977: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2978: #         and will then be copied to
                   2979: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2980: #         course's home server.
1.485     raeburn  2981: #
1.481     raeburn  2982: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2983: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2984: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2985: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2986: #         in course's home server.
1.637     raeburn  2987: #
1.477     raeburn  2988: 
                   2989: sub process_coursefile {
1.1095    raeburn  2990:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2991:         $mimetype)=@_;
1.477     raeburn  2992:     my $fetchresult;
1.638     albertel 2993:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2994:     if ($action eq 'propagate') {
1.638     albertel 2995:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2996: 			     $home);
1.481     raeburn  2997:     } else {
1.477     raeburn  2998:         my $fpath = '';
                   2999:         my $fname = $file;
1.478     albertel 3000:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3001:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3002:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3003:         if ($action eq 'copy') {
                   3004:             if ($source eq '') {
                   3005:                 $fetchresult = 'no source file';
                   3006:                 return $fetchresult;
                   3007:             } else {
                   3008:                 my $destination = $filepath.'/'.$fname;
                   3009:                 rename($source,$destination);
                   3010:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3011:                                  $home);
1.481     raeburn  3012:             }
                   3013:         } elsif ($action eq 'uploaddoc') {
                   3014:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3015:             print $fh $env{'form.'.$source};
1.481     raeburn  3016:             close($fh);
1.637     raeburn  3017:             if ($parser eq 'parse') {
1.1024    raeburn  3018:                 my $mm = new File::MMagic;
1.1095    raeburn  3019:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3020:                 if ($type eq 'text/html') {
1.1024    raeburn  3021:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3022:                     unless ($parse_result eq 'ok') {
                   3023:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3024:                     }
1.637     raeburn  3025:                 }
1.1095    raeburn  3026:                 if (ref($mimetype)) {
                   3027:                     $$mimetype = $type;
                   3028:                 } 
1.637     raeburn  3029:             }
1.477     raeburn  3030:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3031:                                  $home);
1.481     raeburn  3032:             if ($fetchresult eq 'ok') {
                   3033:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3034:             } else {
                   3035:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3036:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3037:                 return '/adm/notfound.html';
                   3038:             }
1.477     raeburn  3039:         }
                   3040:     }
1.485     raeburn  3041:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3042:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3043:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3044:     }
                   3045:     return $fetchresult;
                   3046: }
                   3047: 
1.637     raeburn  3048: sub build_filepath {
                   3049:     my ($fpath) = @_;
                   3050:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3051:     unless ($fpath eq '') {
                   3052:         my @parts=split('/',$fpath);
                   3053:         foreach my $part (@parts) {
                   3054:             $filepath.= '/'.$part;
                   3055:             if ((-e $filepath)!=1) {
                   3056:                 mkdir($filepath,0777);
                   3057:             }
                   3058:         }
                   3059:     }
                   3060:     return $filepath;
                   3061: }
                   3062: 
                   3063: sub store_edited_file {
1.638     albertel 3064:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3065:     my $file = $primary_url;
                   3066:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3067:     my $fpath = '';
                   3068:     my $fname = $file;
                   3069:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3070:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3071:     my $filepath = &build_filepath($fpath);
                   3072:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3073:     print $fh $content;
                   3074:     close($fh);
1.638     albertel 3075:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3076:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3077: 			  $home);
1.637     raeburn  3078:     if ($$fetchresult eq 'ok') {
                   3079:         return '/uploaded/'.$fpath.'/'.$fname;
                   3080:     } else {
1.638     albertel 3081:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3082: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3083:         return '/adm/notfound.html';
                   3084:     }
                   3085: }
                   3086: 
1.531     albertel 3087: sub clean_filename {
1.831     albertel 3088:     my ($fname,$args)=@_;
1.315     www      3089: # Replace Windows backslashes by forward slashes
1.257     www      3090:     $fname=~s/\\/\//g;
1.831     albertel 3091:     if (!$args->{'keep_path'}) {
                   3092:         # Get rid of everything but the actual filename
                   3093: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3094:     }
1.315     www      3095: # Replace spaces by underscores
                   3096:     $fname=~s/\s+/\_/g;
                   3097: # Replace all other weird characters by nothing
1.831     albertel 3098:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3099: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3100: # numbers
                   3101:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3102:     return $fname;
                   3103: }
1.1051    raeburn  3104: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3105: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3106: # image with the same aspect ratio as the original, but with dimensions which do 
                   3107: # not exceed $resizewidth and $resizeheight.
                   3108:  
1.984     neumanie 3109: sub resizeImage {
1.1051    raeburn  3110:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3111:     my $ima = Image::Magick->new;
                   3112:     my $resized;
                   3113:     if (-e $img_path) {
                   3114:         $ima->Read($img_path);
                   3115:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3116:             my $width = $ima->Get('width');
                   3117:             my $height = $ima->Get('height');
                   3118:             if ($width > $resizewidth) {
                   3119: 	        my $factor = $width/$resizewidth;
                   3120:                 my $newheight = $height/$factor;
                   3121:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3122:                 $resized = 1;
                   3123:             }
                   3124:         }
                   3125:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3126:             my $width = $ima->Get('width');
                   3127:             my $height = $ima->Get('height');
                   3128:             if ($height > $resizeheight) {
                   3129:                 my $factor = $height/$resizeheight;
                   3130:                 my $newwidth = $width/$factor;
                   3131:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3132:                 $resized = 1;
                   3133:             }
                   3134:         }
                   3135:         if ($resized) {
                   3136:             $ima->Write($img_path);
                   3137:         }
                   3138:     }
                   3139:     return;
1.977     amueller 3140: }
                   3141: 
1.608     albertel 3142: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3143: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3144: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3145: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3146: #                                    canceloverwrite, or ''. 
                   3147: #                   if 'coursedoc': upload to the current course
                   3148: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3149: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3150: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3151: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3152: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3153: #        $allfiles - reference to hash for embedded objects
                   3154: #        $codebase - reference to hash for codebase of java objects
                   3155: #        $desuname - username for permanent storage of uploaded file
                   3156: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3157: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3158: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3159: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3160: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3161: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3162: #                    from File::MMagic.
1.858     raeburn  3163: # 
1.686     albertel 3164: # output: url of file in userspace, or error: <message> 
                   3165: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3166: 
1.531     albertel 3167: sub userfileupload {
1.1090    raeburn  3168:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3169:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3170:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3171:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3172:     $fname=&clean_filename($fname);
1.1090    raeburn  3173:     # See if there is anything left
1.257     www      3174:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3175:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3176:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3177:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3178:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3179:         my $now = time;
1.1090    raeburn  3180:         my $filepath;
1.1095    raeburn  3181:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3182:              $filepath = 'tmp/helprequests/'.$now;
                   3183:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3184:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3185:                          '_'.$env{'user.domain'}.'/pending';
                   3186:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3187:             my ($docuname,$docudom);
                   3188:             if ($destudom) {
                   3189:                 $docudom = $destudom;
                   3190:             } else {
                   3191:                 $docudom = $env{'user.domain'};
                   3192:             }
                   3193:             if ($destuname) {
                   3194:                 $docuname = $destuname;
                   3195:             } else {
                   3196:                 $docuname = $env{'user.name'};
                   3197:             }
                   3198:             if (exists($env{'form.group'})) {
                   3199:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3200:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3201:             }
                   3202:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3203:             if ($context eq 'canceloverwrite') {
                   3204:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3205:                 if (-e  $tempfile) {
                   3206:                     my @info = stat($tempfile);
                   3207:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3208:                         unlink($tempfile);
                   3209:                     }
                   3210:                 }
                   3211:                 return;
1.523     raeburn  3212:             }
                   3213:         }
1.1090    raeburn  3214:         # Create the directory if not present
1.741     raeburn  3215:         my @parts=split(/\//,$filepath);
                   3216:         my $fullpath = $perlvar{'lonDaemons'};
                   3217:         for (my $i=0;$i<@parts;$i++) {
                   3218:             $fullpath .= '/'.$parts[$i];
                   3219:             if ((-e $fullpath)!=1) {
                   3220:                 mkdir($fullpath,0777);
                   3221:             }
                   3222:         }
                   3223:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3224:         print $fh $env{'form.'.$formname};
                   3225:         close($fh);
1.1090    raeburn  3226:         if ($context eq 'existingfile') {
                   3227:             my @info = stat($fullpath.'/'.$fname);
                   3228:             return ($fullpath.'/'.$fname,$info[9]);
                   3229:         } else {
                   3230:             return $fullpath.'/'.$fname;
                   3231:         }
1.523     raeburn  3232:     }
1.995     raeburn  3233:     if ($subdir eq 'scantron') {
                   3234:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3235:     } else {
1.995     raeburn  3236:         $fname="$subdir/$fname";
                   3237:     }
1.1090    raeburn  3238:     if ($context eq 'coursedoc') {
1.638     albertel 3239: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3240: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3241:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3242:             return &finishuserfileupload($docuname,$docudom,
                   3243: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3244: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3245:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3246:         } else {
1.1218    raeburn  3247:             if ($env{'form.folder'}) {
                   3248:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3249:             }
1.638     albertel 3250:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3251: 				       $fname,$formname,$parser,
1.1095    raeburn  3252: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3253:         }
1.719     banghart 3254:     } elsif (defined($destuname)) {
                   3255:         my $docuname=$destuname;
                   3256:         my $docudom=$destudom;
1.860     raeburn  3257: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3258: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3259:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3260:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3261:     } else {
1.638     albertel 3262:         my $docuname=$env{'user.name'};
                   3263:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3264:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3265:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3266:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3267:         }
1.860     raeburn  3268: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3269: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3270:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3271:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3272:     }
1.271     www      3273: }
                   3274: 
                   3275: sub finishuserfileupload {
1.860     raeburn  3276:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3277:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3278:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3279:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3280:   
1.860     raeburn  3281:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3282:     $file=$fname;
                   3283:     if ($fname=~m|/|) {
                   3284:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3285: 	$path.=$fnamepath.'/';
                   3286:     }
1.259     www      3287:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3288:     my $count;
                   3289:     for ($count=4;$count<=$#parts;$count++) {
                   3290:         $filepath.="/$parts[$count]";
                   3291:         if ((-e $filepath)!=1) {
                   3292: 	    mkdir($filepath,0777);
                   3293:         }
                   3294:     }
1.984     neumanie 3295: 
1.258     www      3296: # Save the file
                   3297:     {
1.701     albertel 3298: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3299: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3300: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3301: 	    return '/adm/notfound.html';
                   3302: 	}
1.1090    raeburn  3303:         if ($context eq 'overwrite') {
1.1117    foxr     3304:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3305:             my $target = $filepath.'/'.$file;
                   3306:             if (-e $source) {
                   3307:                 my @info = stat($source);
                   3308:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3309:                     unless (&File::Copy::move($source,$target)) {
                   3310:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3311:                         return "Moving from $source failed";
                   3312:                     }
                   3313:                 } else {
                   3314:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3315:                 }
                   3316:             } else {
                   3317:                 return "Temporary file: $source missing";
                   3318:             }
                   3319:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3320: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3321: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3322: 	    return '/adm/notfound.html';
                   3323: 	}
1.570     albertel 3324: 	close(FH);
1.1051    raeburn  3325:         if ($resizewidth && $resizeheight) {
                   3326:             my $mm = new File::MMagic;
                   3327:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3328:             if ($mime_type =~ m{^image/}) {
                   3329: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3330:             }  
1.977     amueller 3331: 	}
1.258     www      3332:     }
1.1152    raeburn  3333:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3334:         if (ref($mimetype)) {
                   3335:             if ($$mimetype eq '') {
                   3336:                 my $mm = new File::MMagic;
                   3337:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3338:                 $$mimetype = $type;
                   3339:             }
                   3340:         }
                   3341:     }
1.637     raeburn  3342:     if ($parser eq 'parse') {
1.1152    raeburn  3343:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3344:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3345:                                                        $allfiles,$codebase);
                   3346:             unless ($parse_result eq 'ok') {
                   3347:                 &logthis('Failed to parse '.$filepath.$file.
                   3348: 	   	         ' for embedded media: '.$parse_result); 
                   3349:             }
1.637     raeburn  3350:         }
                   3351:     }
1.860     raeburn  3352:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3353:         my $input = $filepath.'/'.$file;
                   3354:         my $output = $filepath.'/'.'tn-'.$file;
                   3355:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3356:         system("convert -sample $thumbsize $input $output");
                   3357:         if (-e $filepath.'/'.'tn-'.$file) {
                   3358:             $fetchthumb  = 1; 
                   3359:         }
                   3360:     }
1.858     raeburn  3361:  
1.259     www      3362: # Notify homeserver to grep it
                   3363: #
1.984     neumanie 3364:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3365:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3366:     if ($fetchresult eq 'ok') {
1.860     raeburn  3367:         if ($fetchthumb) {
                   3368:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3369:             if ($thumbresult ne 'ok') {
                   3370:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3371:                          $docuhome.': '.$thumbresult);
                   3372:             }
                   3373:         }
1.259     www      3374: #
1.258     www      3375: # Return the URL to it
1.494     albertel 3376:         return '/uploaded/'.$path.$file;
1.263     www      3377:     } else {
1.494     albertel 3378:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3379: 		 ': '.$fetchresult);
1.263     www      3380:         return '/adm/notfound.html';
1.858     raeburn  3381:     }
1.493     albertel 3382: }
                   3383: 
1.637     raeburn  3384: sub extract_embedded_items {
1.961     raeburn  3385:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3386:     my @state = ();
1.1164    raeburn  3387:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3388:     my %javafiles = (
                   3389:                       codebase => '',
                   3390:                       code => '',
                   3391:                       archive => ''
                   3392:                     );
                   3393:     my %mediafiles = (
                   3394:                       src => '',
                   3395:                       movie => '',
                   3396:                      );
1.648     raeburn  3397:     my $p;
                   3398:     if ($content) {
                   3399:         $p = HTML::LCParser->new($content);
                   3400:     } else {
1.961     raeburn  3401:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3402:     }
1.641     albertel 3403:     while (my $t=$p->get_token()) {
1.640     albertel 3404: 	if ($t->[0] eq 'S') {
                   3405: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3406: 	    push(@state, $tagname);
1.648     raeburn  3407:             if (lc($tagname) eq 'allow') {
                   3408:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3409:             }
1.640     albertel 3410: 	    if (lc($tagname) eq 'img') {
                   3411: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3412: 	    }
1.886     albertel 3413: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3414:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3415:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3416:                 }
1.886     albertel 3417: 	    }
1.645     raeburn  3418:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3419:                 my $src;
1.645     raeburn  3420:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3421:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3422:                 } else {
1.1164    raeburn  3423:                     if ($attr->{'src'} ne '') {
                   3424:                         $src = $attr->{'src'};
                   3425:                         &add_filetype($allfiles,$src,'src');
                   3426:                     }
                   3427:                 }
                   3428:                 my $text = $p->get_trimmed_text();
                   3429:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3430:                     my @swfargs = split(/,/,$1);
                   3431:                     foreach my $item (@swfargs) {
                   3432:                         $item =~ s/["']//g;
                   3433:                         $item =~ s/^\s+//;
                   3434:                         $item =~ s/\s+$//;
                   3435:                     }
                   3436:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3437:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3438:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3439:                         } else {
                   3440:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3441:                         }
                   3442:                     }
1.645     raeburn  3443:                 }
                   3444:             }
                   3445:             if (lc($tagname) eq 'link') {
                   3446:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3447:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3448:                 }
                   3449:             }
1.640     albertel 3450: 	    if (lc($tagname) eq 'object' ||
                   3451: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3452: 		foreach my $item (keys(%javafiles)) {
                   3453: 		    $javafiles{$item} = '';
                   3454: 		}
1.1164    raeburn  3455:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3456:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3457:                 }
1.640     albertel 3458: 	    }
                   3459: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3460: 		my $name = lc($attr->{'name'});
                   3461: 		foreach my $item (keys(%javafiles)) {
                   3462: 		    if ($name eq $item) {
                   3463: 			$javafiles{$item} = $attr->{'value'};
                   3464: 			last;
                   3465: 		    }
                   3466: 		}
1.1164    raeburn  3467:                 my $pathfrom;
1.640     albertel 3468: 		foreach my $item (keys(%mediafiles)) {
                   3469: 		    if ($name eq $item) {
1.1164    raeburn  3470:                         $pathfrom = $attr->{'value'};
                   3471:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3472: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3473: 			last;
                   3474: 		    }
                   3475: 		}
1.1164    raeburn  3476:                 if ($name eq 'flashvars') {
                   3477:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3478:                 }
                   3479:                 if ($pathfrom ne '') {
                   3480:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3481:                                          $pathfrom);
                   3482:                 }
1.640     albertel 3483: 	    }
                   3484: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3485: 		foreach my $item (keys(%javafiles)) {
                   3486: 		    if ($attr->{$item}) {
                   3487: 			$javafiles{$item} = $attr->{$item};
                   3488: 			last;
                   3489: 		    }
                   3490: 		}
                   3491: 		foreach my $item (keys(%mediafiles)) {
                   3492: 		    if ($attr->{$item}) {
                   3493: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3494: 			last;
                   3495: 		    }
                   3496: 		}
1.1164    raeburn  3497:                 if (lc($tagname) eq 'embed') {
                   3498:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3499:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3500:                                              $attr->{'src'});
                   3501:                     }
                   3502:                 }
1.640     albertel 3503: 	    }
1.1243    raeburn  3504:             if (lc($tagname) eq 'iframe') {
                   3505:                 my $src = $attr->{'src'} ;
                   3506:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3507:                     &add_filetype($allfiles,$src,'src');
                   3508:                 } elsif ($src =~ m{^/}) {
                   3509:                     if ($env{'request.course.id'}) {
                   3510:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3511:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3512:                         my $url = &hreflocation('',$fullpath);
                   3513:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3514:                             my $relpath = $1;
                   3515:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3516:                                 &add_filetype($allfiles,$1,'src');
                   3517:                             }
                   3518:                         }
                   3519:                     }
                   3520:                 }
                   3521:             }
1.1164    raeburn  3522:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3523:                 pop(@state);
1.1164    raeburn  3524:             }
1.640     albertel 3525: 	} elsif ($t->[0] eq 'E') {
                   3526: 	    my ($tagname) = ($t->[1]);
                   3527: 	    if ($javafiles{'codebase'} ne '') {
                   3528: 		$javafiles{'codebase'} .= '/';
                   3529: 	    }  
                   3530: 	    if (lc($tagname) eq 'applet' ||
                   3531: 		lc($tagname) eq 'object' ||
                   3532: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3533: 		) {
                   3534: 		foreach my $item (keys(%javafiles)) {
                   3535: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3536: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3537: 			&add_filetype($allfiles,$file,$item);
                   3538: 		    }
                   3539: 		}
                   3540: 	    } 
                   3541: 	    pop @state;
                   3542: 	}
                   3543:     }
1.1164    raeburn  3544:     foreach my $id (sort(keys(%flashvars))) {
                   3545:         if ($shockwave{$id} ne '') {
                   3546:             my @pairs = split(/\&/,$flashvars{$id});
                   3547:             foreach my $pair (@pairs) {
                   3548:                 my ($key,$value) = split(/\=/,$pair);
                   3549:                 if ($key eq 'thumb') {
                   3550:                     &add_filetype($allfiles,$value,$key);
                   3551:                 } elsif ($key eq 'content') {
                   3552:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3553:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3554:                     if ($ext ne '') {
                   3555:                         &add_filetype($allfiles,$path.$value,$ext);
                   3556:                     }
                   3557:                 }
                   3558:             }
                   3559:         }
                   3560:     }
1.637     raeburn  3561:     return 'ok';
                   3562: }
                   3563: 
1.639     albertel 3564: sub add_filetype {
                   3565:     my ($allfiles,$file,$type)=@_;
                   3566:     if (exists($allfiles->{$file})) {
                   3567: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3568: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3569: 	}
                   3570:     } else {
                   3571: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3572:     }
                   3573: }
                   3574: 
1.1164    raeburn  3575: sub embedded_dependency {
                   3576:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3577:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3578:         if (($identifier ne '') &&
                   3579:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3580:             ($pathfrom ne '')) {
                   3581:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3582:             foreach my $dep (@{$related->{$identifier}}) {
                   3583:                 &add_filetype($allfiles,$path.$dep,'object');
                   3584:             }
                   3585:         }
                   3586:     }
                   3587:     return;
                   3588: }
                   3589: 
1.493     albertel 3590: sub removeuploadedurl {
1.984     neumanie 3591:     my ($url)=@_;	
                   3592:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3593:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3594: }
                   3595: 
                   3596: sub removeuserfile {
                   3597:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3598:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3599:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3600:     if ($result eq 'ok') {	
1.798     raeburn  3601:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3602:             my $metafile = $fname.'.meta';
                   3603:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3604: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3605:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3606:             my $sqlresult = 
1.823     albertel 3607:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3608:                                         'portfolio_metadata',$group,
                   3609:                                         'delete');
1.798     raeburn  3610:         }
                   3611:     }
                   3612:     return $result;
1.257     www      3613: }
1.15      www      3614: 
1.530     albertel 3615: sub mkdiruserfile {
                   3616:     my ($docuname,$docudom,$dir)=@_;
                   3617:     my $home=&homeserver($docuname,$docudom);
                   3618:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3619: }
                   3620: 
1.531     albertel 3621: sub renameuserfile {
                   3622:     my ($docuname,$docudom,$old,$new)=@_;
                   3623:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3624:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3625:                         &escape("$old").':'.&escape("$new"),$home);
                   3626:     if ($result eq 'ok') {
                   3627:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3628:             my $oldmeta = $old.'.meta';
                   3629:             my $newmeta = $new.'.meta';
                   3630:             my $metaresult = 
                   3631:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3632: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3633:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3634:             my $sqlresult = 
1.823     albertel 3635:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3636:                                         'portfolio_metadata',$group,
                   3637:                                         'delete');
1.798     raeburn  3638:         }
                   3639:     }
                   3640:     return $result;
1.531     albertel 3641: }
                   3642: 
1.14      www      3643: # ------------------------------------------------------------------------- Log
                   3644: 
                   3645: sub log {
                   3646:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3647:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3648: }
                   3649: 
                   3650: # ------------------------------------------------------------------ Course Log
1.352     www      3651: #
                   3652: # This routine flushes several buffers of non-mission-critical nature
                   3653: #
1.157     www      3654: 
                   3655: sub flushcourselogs {
1.352     www      3656:     &logthis('Flushing log buffers');
                   3657: #
                   3658: # course logs
                   3659: # This is a log of all transactions in a course, which can be used
                   3660: # for data mining purposes
                   3661: #
                   3662: # It also collects the courseid database, which lists last transaction
                   3663: # times and course titles for all courseids
                   3664: #
                   3665:     my %courseidbuffer=();
1.921     raeburn  3666:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3667:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3668: 		          &escape($courselogs{$crsid}),
                   3669: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3670: 	    delete $courselogs{$crsid};
                   3671:         } else {
                   3672:             &logthis('Failed to flush log buffer for '.$crsid);
                   3673:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3674:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3675:                         " exceeded maximum size, deleting.</font>");
                   3676:                delete $courselogs{$crsid};
                   3677:             }
1.352     www      3678:         }
1.920     raeburn  3679:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3680:             'description' => $coursedescrbuf{$crsid},
                   3681:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3682:             'type'        => $coursetypebuf{$crsid},
                   3683:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3684:         };
1.191     harris41 3685:     }
1.352     www      3686: #
                   3687: # Write course id database (reverse lookup) to homeserver of courses 
                   3688: # Is used in pickcourse
                   3689: #
1.840     albertel 3690:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3691:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3692:                                     $courseidbuffer{$crs_home},
                   3693:                                     $crs_home,'timeonly');
1.352     www      3694:     }
                   3695: #
                   3696: # File accesses
                   3697: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3698: #
1.449     matthew  3699:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3700:         if ($entry =~ /___count$/) {
                   3701:             my ($dom,$name);
1.807     albertel 3702:             ($dom,$name,undef)=
1.811     albertel 3703: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3704:             if (! defined($dom) || $dom eq '' || 
                   3705:                 ! defined($name) || $name eq '') {
1.620     albertel 3706:                 my $cid = $env{'request.course.id'};
                   3707:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3708:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3709:             }
1.450     matthew  3710:             my $value = $accesshash{$entry};
                   3711:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3712:             my %temphash=($url => $value);
1.449     matthew  3713:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3714:             if ($result eq 'ok') {
                   3715:                 delete $accesshash{$entry};
                   3716:             }
                   3717:         } else {
1.811     albertel 3718:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3719:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3720:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3721:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3722:                 delete $accesshash{$entry};
                   3723:             }
1.185     www      3724:         }
1.191     harris41 3725:     }
1.352     www      3726: #
                   3727: # Roles
                   3728: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3729: #
1.800     albertel 3730:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3731:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3732: 	    split(/\:/,$entry);
                   3733:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3734:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3735:                 $rudom,$runame) eq 'ok') {
                   3736: 	    delete $userrolehash{$entry};
                   3737:         }
                   3738:     }
1.662     raeburn  3739: #
                   3740: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3741: #
                   3742:     my %domrolebuffer = ();
1.1000    raeburn  3743:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3744:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3745:         if ($domrolebuffer{$rudom}) {
                   3746:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3747:                       '='.&escape($domainrolehash{$entry});
                   3748:         } else {
                   3749:             $domrolebuffer{$rudom}.=&escape($entry).
                   3750:                       '='.&escape($domainrolehash{$entry});
                   3751:         }
                   3752:         delete $domainrolehash{$entry};
                   3753:     }
                   3754:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3755: 	my %servers = &get_servers($dom,'library');
                   3756: 	foreach my $tryserver (keys(%servers)) {
                   3757: 	    unless (&reply('domroleput:'.$dom.':'.
                   3758: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3759: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3760: 	    }
1.662     raeburn  3761:         }
                   3762:     }
1.186     www      3763:     $dumpcount++;
1.157     www      3764: }
                   3765: 
                   3766: sub courselog {
                   3767:     my $what=shift;
1.158     www      3768:     $what=time.':'.$what;
1.620     albertel 3769:     unless ($env{'request.course.id'}) { return ''; }
                   3770:     $coursedombuf{$env{'request.course.id'}}=
                   3771:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3772:     $coursenumbuf{$env{'request.course.id'}}=
                   3773:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3774:     $coursehombuf{$env{'request.course.id'}}=
                   3775:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3776:     $coursedescrbuf{$env{'request.course.id'}}=
                   3777:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3778:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3779:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3780:     $courseownerbuf{$env{'request.course.id'}}=
                   3781:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3782:     $coursetypebuf{$env{'request.course.id'}}=
                   3783:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3784:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3785: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3786:     } else {
1.620     albertel 3787: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3788:     }
1.620     albertel 3789:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3790: 	&flushcourselogs();
                   3791:     }
1.158     www      3792: }
                   3793: 
                   3794: sub courseacclog {
                   3795:     my $fnsymb=shift;
1.620     albertel 3796:     unless ($env{'request.course.id'}) { return ''; }
                   3797:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3798:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3799:         $what.=':POST';
1.583     matthew  3800:         # FIXME: Probably ought to escape things....
1.800     albertel 3801: 	foreach my $key (keys(%env)) {
                   3802:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3803:                 my $formitem = $1;
                   3804:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3805:                     $what.=':'.$formitem.'='.$env{$key};
                   3806:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3807:                     $what.=':'.$formitem.'='.$env{$key};
                   3808:                 }
1.158     www      3809:             }
1.191     harris41 3810:         }
1.583     matthew  3811:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3812:         # FIXME: We should not be depending on a form parameter that someone
                   3813:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3814:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3815:             $what.= ':POST';
                   3816:             # FIXME: Probably ought to escape things....
                   3817:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3818:                                  'crsdiscuss') {
1.620     albertel 3819:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3820:             }
                   3821:         }
1.158     www      3822:     }
                   3823:     &courselog($what);
1.149     www      3824: }
                   3825: 
1.185     www      3826: sub countacc {
                   3827:     my $url=&declutter(shift);
1.458     matthew  3828:     return if (! defined($url) || $url eq '');
1.620     albertel 3829:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3830: #
                   3831: # Mark that this url was used in this course
                   3832: #
1.620     albertel 3833:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3834: #
                   3835: # Increase the access count for this resource in this child process
                   3836: #
1.281     www      3837:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3838:     $accesshash{$key}++;
1.185     www      3839: }
1.349     www      3840: 
1.361     www      3841: sub linklog {
                   3842:     my ($from,$to)=@_;
                   3843:     $from=&declutter($from);
                   3844:     $to=&declutter($to);
                   3845:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3846:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3847: }
1.1160    www      3848: 
                   3849: sub statslog {
                   3850:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3851:     if ($users<2) { return; }
                   3852:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3853:             'course'       => $env{'request.course.id'},
                   3854:             'sections'     => '"all"',
                   3855:             'num_students' => $users,
                   3856:             'part'         => $part,
                   3857:             'symb'         => $symb,
                   3858:             'mean_tries'   => $av_attempts,
                   3859:             'deg_of_diff'  => $degdiff});
                   3860:     foreach my $key (keys(%dynstore)) {
                   3861:         $accesshash{$key}=$dynstore{$key};
                   3862:     }
                   3863: }
1.361     www      3864:   
1.349     www      3865: sub userrolelog {
                   3866:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3867:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3868:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3869:        $userrolehash
                   3870:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3871:                     =$tend.':'.$tstart;
1.662     raeburn  3872:     }
1.1169    droeschl 3873:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3874:        $userrolehash
                   3875:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3876:                     =$tend.':'.$tstart;
                   3877:     }
1.1169    droeschl 3878:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3879:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3880:        $domainrolehash
                   3881:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3882:                     = $tend.':'.$tstart;
                   3883:     }
1.351     www      3884: }
                   3885: 
1.957     raeburn  3886: sub courserolelog {
                   3887:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3888:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3889:         my $cdom = $1;
                   3890:         my $cnum = $2;
                   3891:         my $sec = $3;
                   3892:         my $namespace = 'rolelog';
                   3893:         my %storehash = (
                   3894:                            role    => $trole,
                   3895:                            start   => $tstart,
                   3896:                            end     => $tend,
                   3897:                            selfenroll => $selfenroll,
                   3898:                            context    => $context,
                   3899:                         );
                   3900:         if ($trole eq 'gr') {
                   3901:             $namespace = 'groupslog';
                   3902:             $storehash{'group'} = $sec;
                   3903:         } else {
                   3904:             $storehash{'section'} = $sec;
                   3905:         }
1.1188    raeburn  3906:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3907:                    $domain,$cnum,$cdom);
1.1184    raeburn  3908:         if (($trole ne 'st') || ($sec ne '')) {
                   3909:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3910:         }
                   3911:     }
                   3912:     return;
                   3913: }
                   3914: 
1.1184    raeburn  3915: sub domainrolelog {
                   3916:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3917:     if ($area =~ m{^/($match_domain)/$}) {
                   3918:         my $cdom = $1;
                   3919:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3920:         my $namespace = 'rolelog';
                   3921:         my %storehash = (
                   3922:                            role    => $trole,
                   3923:                            start   => $tstart,
                   3924:                            end     => $tend,
                   3925:                            context => $context,
                   3926:                         );
1.1188    raeburn  3927:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3928:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3929:     }
                   3930:     return;
                   3931: 
                   3932: }
                   3933: 
                   3934: sub coauthorrolelog {
                   3935:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3936:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3937:         my $audom = $1;
                   3938:         my $auname = $2;
                   3939:         my $namespace = 'rolelog';
                   3940:         my %storehash = (
                   3941:                            role    => $trole,
                   3942:                            start   => $tstart,
                   3943:                            end     => $tend,
                   3944:                            context => $context,
                   3945:                         );
1.1188    raeburn  3946:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3947:                    $domain,$auname,$audom);
1.1184    raeburn  3948:     }
                   3949:     return;
                   3950: }
                   3951: 
1.351     www      3952: sub get_course_adv_roles {
1.948     raeburn  3953:     my ($cid,$codes) = @_;
1.620     albertel 3954:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3955:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3956:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3957:     my %nothide=();
1.800     albertel 3958:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3959:         if ($user !~ /:/) {
                   3960: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3961:         } else {
                   3962:             $nothide{$user}=1;
                   3963:         }
1.470     www      3964:     }
1.1219    raeburn  3965:     my @possdoms = ($coursehash{'domain'});
                   3966:     if ($coursehash{'checkforpriv'}) {
                   3967:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3968:     }
1.351     www      3969:     my %returnhash=();
                   3970:     my %dumphash=
                   3971:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3972:     my $now=time;
1.997     raeburn  3973:     my %privileged;
1.1000    raeburn  3974:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3975: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3976:         if (($tstart) && ($tstart<0)) { next; }
                   3977:         if (($tend) && ($tend<$now)) { next; }
                   3978:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3979:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3980: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  3981:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3982:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3983: 	if ($role eq 'cr') { next; }
1.948     raeburn  3984:         if ($codes) {
                   3985:             if ($section) { $role .= ':'.$section; }
                   3986:             if ($returnhash{$role}) {
                   3987:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3988:             } else {
                   3989:                 $returnhash{$role}=$username.':'.$domain;
                   3990:             }
1.351     www      3991:         } else {
1.988     raeburn  3992:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3993:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3994:             if ($returnhash{$key}) {
                   3995: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3996:             } else {
                   3997:                 $returnhash{$key}=$username.':'.$domain;
                   3998:             }
1.351     www      3999:         }
1.948     raeburn  4000:     }
1.400     www      4001:     return %returnhash;
                   4002: }
                   4003: 
                   4004: sub get_my_roles {
1.937     raeburn  4005:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4006:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4007:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4008:     my (%dumphash,%nothide);
1.1086    raeburn  4009:     if ($context eq 'userroles') {
1.1166    raeburn  4010:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4011:     } else {
1.1219    raeburn  4012:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4013:         if ($hidepriv) {
                   4014:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4015:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4016:                 if ($user !~ /:/) {
                   4017:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4018:                 } else {
                   4019:                     $nothide{$user} = 1;
                   4020:                 }
                   4021:             }
                   4022:         }
1.858     raeburn  4023:     }
1.400     www      4024:     my %returnhash=();
                   4025:     my $now=time;
1.999     raeburn  4026:     my %privileged;
1.800     albertel 4027:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4028:         my ($role,$tend,$tstart);
                   4029:         if ($context eq 'userroles') {
1.1149    raeburn  4030:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4031: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4032:         } else {
                   4033:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4034:         }
1.400     www      4035:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4036:         my $status = 'active';
1.939     raeburn  4037:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4038:             $status = 'previous';
                   4039:         } 
                   4040:         if (($tstart) && ($now<$tstart)) {
                   4041:             $status = 'future';
                   4042:         }
                   4043:         if (ref($types) eq 'ARRAY') {
                   4044:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4045:                 next;
                   4046:             } 
                   4047:         } else {
                   4048:             if ($status ne 'active') {
                   4049:                 next;
                   4050:             }
                   4051:         }
1.867     raeburn  4052:         my ($rolecode,$username,$domain,$section,$area);
                   4053:         if ($context eq 'userroles') {
1.1186    raeburn  4054:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4055:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4056:         } else {
                   4057:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4058:         }
1.832     raeburn  4059:         if (ref($roledoms) eq 'ARRAY') {
                   4060:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4061:                 next;
                   4062:             }
                   4063:         }
                   4064:         if (ref($roles) eq 'ARRAY') {
                   4065:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4066:                 if ($role =~ /^cr\//) {
                   4067:                     if (!grep(/^cr$/,@{$roles})) {
                   4068:                         next;
                   4069:                     }
1.1104    raeburn  4070:                 } elsif ($role =~ /^gr\//) {
                   4071:                     if (!grep(/^gr$/,@{$roles})) {
                   4072:                         next;
                   4073:                     }
1.922     raeburn  4074:                 } else {
                   4075:                     next;
                   4076:                 }
1.832     raeburn  4077:             }
1.867     raeburn  4078:         }
1.937     raeburn  4079:         if ($hidepriv) {
1.1219    raeburn  4080:             my @privroles = ('dc','su');
1.999     raeburn  4081:             if ($context eq 'userroles') {
1.1219    raeburn  4082:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4083:             } else {
1.1219    raeburn  4084:                 my $possdoms = [$domain];
                   4085:                 if (ref($roledoms) eq 'ARRAY') {
                   4086:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4087:                 }
1.1219    raeburn  4088:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4089:                     if (!$nothide{$username.':'.$domain}) {
                   4090:                         next;
                   4091:                     }
                   4092:                 }
1.937     raeburn  4093:             }
                   4094:         }
1.933     raeburn  4095:         if ($withsec) {
                   4096:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4097:                 $tstart.':'.$tend;
                   4098:         } else {
                   4099:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4100:         }
1.832     raeburn  4101:     }
1.373     www      4102:     return %returnhash;
1.399     www      4103: }
                   4104: 
                   4105: # ----------------------------------------------------- Frontpage Announcements
                   4106: #
                   4107: #
                   4108: 
                   4109: sub postannounce {
                   4110:     my ($server,$text)=@_;
1.844     albertel 4111:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4112:     unless ($text=~/\w/) { $text=''; }
                   4113:     return &reply('setannounce:'.&escape($text),$server);
                   4114: }
                   4115: 
                   4116: sub getannounce {
1.448     albertel 4117: 
                   4118:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4119: 	my $announcement='';
1.800     albertel 4120: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4121: 	close($fh);
1.399     www      4122: 	if ($announcement=~/\w/) { 
                   4123: 	    return 
                   4124:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4125:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4126: 	} else {
                   4127: 	    return '';
                   4128: 	}
                   4129:     } else {
                   4130: 	return '';
                   4131:     }
1.351     www      4132: }
1.353     www      4133: 
                   4134: # ---------------------------------------------------------- Course ID routines
                   4135: # Deal with domain's nohist_courseid.db files
                   4136: #
                   4137: 
                   4138: sub courseidput {
1.921     raeburn  4139:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4140:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4141:     my $outcome;
                   4142:     if ($caller eq 'timeonly') {
                   4143:         my $cids = '';
                   4144:         foreach my $item (keys(%$storehash)) {
                   4145:             $cids.=&escape($item).'&';
                   4146:         }
                   4147:         $cids=~s/\&$//;
                   4148:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4149:                           $coursehome);       
                   4150:     } else {
                   4151:         my $items = '';
                   4152:         foreach my $item (keys(%$storehash)) {
                   4153:             $items.= &escape($item).'='.
                   4154:                      &freeze_escape($$storehash{$item}).'&';
                   4155:         }
                   4156:         $items=~s/\&$//;
                   4157:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4158:                           $coursehome);
1.918     raeburn  4159:     }
                   4160:     if ($outcome eq 'unknown_cmd') {
                   4161:         my $what;
                   4162:         foreach my $cid (keys(%$storehash)) {
                   4163:             $what .= &escape($cid).'=';
1.921     raeburn  4164:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4165:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4166:             }
                   4167:             $what =~ s/\:$/&/;
                   4168:         }
                   4169:         $what =~ s/\&$//;  
                   4170:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4171:     } else {
                   4172:         return $outcome;
                   4173:     }
1.353     www      4174: }
                   4175: 
                   4176: sub courseiddump {
1.921     raeburn  4177:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4178:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4179:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4180:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4181:     my $as_hash = 1;
                   4182:     my %returnhash;
                   4183:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4184:     my %libserv = &all_library();
                   4185:     foreach my $tryserver (keys(%libserv)) {
                   4186:         if ( (  $hostidflag == 1 
                   4187: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4188: 	     || (!defined($hostidflag)) ) {
                   4189: 
1.918     raeburn  4190: 	    if (($domfilter eq '') ||
                   4191: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4192:                 my $rep;
                   4193:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4194:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4195:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4196:                                 &escape($descfilter), &escape($instcodefilter), 
                   4197:                                 &escape($ownerfilter), &escape($coursefilter),
                   4198:                                 &escape($typefilter), &escape($regexp_ok), 
                   4199:                                 $as_hash, &escape($selfenrollonly), 
                   4200:                                 &escape($catfilter), $showhidden, $caller, 
                   4201:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4202:                                 &escape($createdbefore), &escape($createdafter), 
                   4203:                                 &escape($creationcontext), $domcloner)));
                   4204:                 } else {
                   4205:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4206:                              $sincefilter.':'.&escape($descfilter).':'.
                   4207:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4208:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4209:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4210:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4211:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4212:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4213:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4214:                              &escape($creationcontext).':'.$domcloner,
                   4215:                              $tryserver);
                   4216:                 }
                   4217:                      
1.918     raeburn  4218:                 my @pairs=split(/\&/,$rep);
                   4219:                 foreach my $item (@pairs) {
                   4220:                     my ($key,$value)=split(/\=/,$item,2);
                   4221:                     $key = &unescape($key);
                   4222:                     next if ($key =~ /^error: 2 /);
                   4223:                     my $result = &thaw_unescape($value);
                   4224:                     if (ref($result) eq 'HASH') {
                   4225:                         $returnhash{$key}=$result;
                   4226:                     } else {
1.921     raeburn  4227:                         my @responses = split(/:/,$value);
                   4228:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4229:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4230:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4231:                         }
1.1008    raeburn  4232:                     }
1.353     www      4233:                 }
                   4234:             }
                   4235:         }
                   4236:     }
                   4237:     return %returnhash;
                   4238: }
                   4239: 
1.1055    raeburn  4240: sub courselastaccess {
                   4241:     my ($cdom,$cnum,$hostidref) = @_;
                   4242:     my %returnhash;
                   4243:     if ($cdom && $cnum) {
                   4244:         my $chome = &homeserver($cnum,$cdom);
                   4245:         if ($chome ne 'no_host') {
                   4246:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4247:             &extract_lastaccess(\%returnhash,$rep);
                   4248:         }
                   4249:     } else {
                   4250:         if (!$cdom) { $cdom=''; }
                   4251:         my %libserv = &all_library();
                   4252:         foreach my $tryserver (keys(%libserv)) {
                   4253:             if (ref($hostidref) eq 'ARRAY') {
                   4254:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4255:             } 
                   4256:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4257:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4258:                 &extract_lastaccess(\%returnhash,$rep);
                   4259:             }
                   4260:         }
                   4261:     }
                   4262:     return %returnhash;
                   4263: }
                   4264: 
                   4265: sub extract_lastaccess {
                   4266:     my ($returnhash,$rep) = @_;
                   4267:     if (ref($returnhash) eq 'HASH') {
                   4268:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4269:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4270:                  $rep eq '') {
                   4271:             my @pairs=split(/\&/,$rep);
                   4272:             foreach my $item (@pairs) {
                   4273:                 my ($key,$value)=split(/\=/,$item,2);
                   4274:                 $key = &unescape($key);
                   4275:                 next if ($key =~ /^error: 2 /);
                   4276:                 $returnhash->{$key} = &thaw_unescape($value);
                   4277:             }
                   4278:         }
                   4279:     }
                   4280:     return;
                   4281: }
                   4282: 
1.658     raeburn  4283: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4284: 
                   4285: sub dcmailput {
1.685     raeburn  4286:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4287:     my $status = &Apache::lonnet::critical(
1.740     www      4288:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4289:        &escape($message),$server);
1.662     raeburn  4290:     return $status;
                   4291: }
                   4292: 
1.658     raeburn  4293: sub dcmaildump {
                   4294:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4295:     my %returnhash=();
1.846     albertel 4296: 
                   4297:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4298:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4299:                                                          &escape($enddate).':';
                   4300: 	my @esc_senders=map { &escape($_)} @$senders;
                   4301: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4302: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4303:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4304:             if (($key) && ($value)) {
                   4305:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4306:             }
                   4307:         }
                   4308:     }
                   4309:     return %returnhash;
                   4310: }
1.662     raeburn  4311: # ---------------------------------------------------------- Domain roles
                   4312: 
                   4313: sub get_domain_roles {
                   4314:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4315:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4316:         $startdate = '.';
                   4317:     }
1.1018    raeburn  4318:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4319:         $enddate = '.';
                   4320:     }
1.922     raeburn  4321:     my $rolelist;
                   4322:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4323:         $rolelist = join('&',@{$roles});
1.922     raeburn  4324:     }
1.662     raeburn  4325:     my %personnel = ();
1.841     albertel 4326: 
                   4327:     my %servers = &get_servers($dom,'library');
                   4328:     foreach my $tryserver (keys(%servers)) {
                   4329: 	%{$personnel{$tryserver}}=();
                   4330: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4331: 					    &escape($startdate).':'.
                   4332: 					    &escape($enddate).':'.
                   4333: 					    &escape($rolelist), $tryserver))) {
                   4334: 	    my ($key,$value) = split(/\=/,$line,2);
                   4335: 	    if (($key) && ($value)) {
                   4336: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4337: 	    }
                   4338: 	}
1.662     raeburn  4339:     }
                   4340:     return %personnel;
                   4341: }
1.658     raeburn  4342: 
1.1057    www      4343: # ----------------------------------------------------------- Interval timing 
1.149     www      4344: 
1.1153    www      4345: {
                   4346: # Caches needed for speedup of navmaps
                   4347: # We don't want to cache this for very long at all (5 seconds at most)
                   4348: # 
                   4349: # The user for whom we cache
                   4350: my $cachedkey='';
                   4351: # The cached times for this user
                   4352: my %cachedtimes=();
                   4353: # When this was last done
                   4354: my $cachedtime=();
                   4355: 
                   4356: sub load_all_first_access {
1.1154    raeburn  4357:     my ($uname,$udom)=@_;
1.1156    www      4358:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4359:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4360:         return;
                   4361:     }
                   4362:     $cachedtime=time;
                   4363:     $cachedkey=$uname.':'.$udom;
                   4364:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4365: }
                   4366: 
1.504     albertel 4367: sub get_first_access {
1.1162    raeburn  4368:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4369:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4370:     if ($argsymb) { $symb=$argsymb; }
                   4371:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4372:     if ($argmap) { $map = $argmap; }
1.926     albertel 4373:     if ($type eq 'course') {
                   4374: 	$res='course';
                   4375:     } elsif ($type eq 'map') {
1.588     albertel 4376: 	$res=&symbread($map);
                   4377:     } else {
                   4378: 	$res=$symb;
                   4379:     }
1.1153    www      4380:     &load_all_first_access($uname,$udom);
                   4381:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4382: }
                   4383: 
                   4384: sub set_first_access {
1.1162    raeburn  4385:     my ($type,$interval)=@_;
1.790     albertel 4386:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4387:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4388:     if ($type eq 'course') {
                   4389: 	$res='course';
                   4390:     } elsif ($type eq 'map') {
1.588     albertel 4391: 	$res=&symbread($map);
                   4392:     } else {
                   4393: 	$res=$symb;
                   4394:     }
1.1153    www      4395:     $cachedkey='';
1.1162    raeburn  4396:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4397:     if (!$firstaccess) {
1.1162    raeburn  4398:         my $start = time;
                   4399: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4400:                           $udom,$uname);
                   4401:         if ($putres eq 'ok') {
                   4402:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4403:                  $udom,$uname); 
                   4404:             &appenv(
                   4405:                      {
                   4406:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4407:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4408:                      }
                   4409:                   );
                   4410:         }
                   4411:         return $putres;
1.505     albertel 4412:     }
                   4413:     return 'already_set';
1.504     albertel 4414: }
1.1153    www      4415: }
1.110     www      4416: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4417: 
                   4418: sub expirespread {
                   4419:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4420:     my $cid=$env{'request.course.id'}; 
1.110     www      4421:     if ($cid) {
                   4422:        my $now=time;
                   4423:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4424:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4425:                             $env{'course.'.$cid.'.num'}.
1.110     www      4426: 	        	    ':nohist_expirationdates:'.
                   4427:                             &escape($key).'='.$now,
1.620     albertel 4428:                             $env{'course.'.$cid.'.home'})
1.110     www      4429:     }
                   4430:     return 'ok';
1.14      www      4431: }
                   4432: 
1.109     www      4433: # ----------------------------------------------------- Devalidate Spreadsheets
                   4434: 
                   4435: sub devalidate {
1.325     www      4436:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4437:     my $cid=$env{'request.course.id'}; 
1.109     www      4438:     if ($cid) {
1.391     matthew  4439:         # delete the stored spreadsheets for
                   4440:         # - the student level sheet of this user in course's homespace
                   4441:         # - the assessment level sheet for this resource 
                   4442:         #   for this user in user's homespace
1.553     albertel 4443: 	# - current conditional state info
1.325     www      4444: 	my $key=$uname.':'.$udom.':';
1.109     www      4445:         my $status=
1.299     matthew  4446: 	    &del('nohist_calculatedsheets',
1.391     matthew  4447: 		 [$key.'studentcalc:'],
1.620     albertel 4448: 		 $env{'course.'.$cid.'.domain'},
                   4449: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4450: 		.' '.
                   4451: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4452: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4453:         unless ($status eq 'ok ok') {
                   4454:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4455:                     $uname.' at '.$udom.' for '.
1.109     www      4456: 		    $symb.': '.$status);
1.133     albertel 4457:         }
1.553     albertel 4458: 	&delenv('user.state.'.$cid);
1.109     www      4459:     }
                   4460: }
                   4461: 
1.265     albertel 4462: sub get_scalar {
                   4463:     my ($string,$end) = @_;
                   4464:     my $value;
                   4465:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4466: 	$value = $1;
                   4467:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4468: 	$value = $1;
                   4469:     }
                   4470:     return &unescape($value);
                   4471: }
                   4472: 
                   4473: sub array2str {
                   4474:   my (@array) = @_;
                   4475:   my $result=&arrayref2str(\@array);
                   4476:   $result=~s/^__ARRAY_REF__//;
                   4477:   $result=~s/__END_ARRAY_REF__$//;
                   4478:   return $result;
                   4479: }
                   4480: 
1.204     albertel 4481: sub arrayref2str {
                   4482:   my ($arrayref) = @_;
1.265     albertel 4483:   my $result='__ARRAY_REF__';
1.204     albertel 4484:   foreach my $elem (@$arrayref) {
1.265     albertel 4485:     if(ref($elem) eq 'ARRAY') {
                   4486:       $result.=&arrayref2str($elem).'&';
                   4487:     } elsif(ref($elem) eq 'HASH') {
                   4488:       $result.=&hashref2str($elem).'&';
                   4489:     } elsif(ref($elem)) {
                   4490:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4491:     } else {
                   4492:       $result.=&escape($elem).'&';
                   4493:     }
                   4494:   }
                   4495:   $result=~s/\&$//;
1.265     albertel 4496:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4497:   return $result;
                   4498: }
                   4499: 
1.168     albertel 4500: sub hash2str {
1.204     albertel 4501:   my (%hash) = @_;
                   4502:   my $result=&hashref2str(\%hash);
1.265     albertel 4503:   $result=~s/^__HASH_REF__//;
                   4504:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4505:   return $result;
                   4506: }
                   4507: 
                   4508: sub hashref2str {
                   4509:   my ($hashref)=@_;
1.265     albertel 4510:   my $result='__HASH_REF__';
1.800     albertel 4511:   foreach my $key (sort(keys(%$hashref))) {
                   4512:     if (ref($key) eq 'ARRAY') {
                   4513:       $result.=&arrayref2str($key).'=';
                   4514:     } elsif (ref($key) eq 'HASH') {
                   4515:       $result.=&hashref2str($key).'=';
                   4516:     } elsif (ref($key)) {
1.265     albertel 4517:       $result.='=';
1.800     albertel 4518:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4519:     } else {
1.1132    raeburn  4520: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4521:     }
                   4522: 
1.800     albertel 4523:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4524:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4525:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4526:       $result.=&hashref2str($hashref->{$key}).'&';
                   4527:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4528:        $result.='&';
1.800     albertel 4529:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4530:     } else {
1.800     albertel 4531:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4532:     }
                   4533:   }
1.168     albertel 4534:   $result=~s/\&$//;
1.265     albertel 4535:   $result .= '__END_HASH_REF__';
1.168     albertel 4536:   return $result;
                   4537: }
                   4538: 
                   4539: sub str2hash {
1.265     albertel 4540:     my ($string)=@_;
                   4541:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4542:     return %$hash;
                   4543: }
                   4544: 
                   4545: sub str2hashref {
1.168     albertel 4546:   my ($string) = @_;
1.265     albertel 4547: 
                   4548:   my %hash;
                   4549: 
                   4550:   if($string !~ /^__HASH_REF__/) {
                   4551:       if (! ($string eq '' || !defined($string))) {
                   4552: 	  $hash{'error'}='Not hash reference';
                   4553:       }
                   4554:       return (\%hash, $string);
                   4555:   }
                   4556: 
                   4557:   $string =~ s/^__HASH_REF__//;
                   4558: 
                   4559:   while($string !~ /^__END_HASH_REF__/) {
                   4560:       #key
                   4561:       my $key='';
                   4562:       if($string =~ /^__HASH_REF__/) {
                   4563:           ($key, $string)=&str2hashref($string);
                   4564:           if(defined($key->{'error'})) {
                   4565:               $hash{'error'}='Bad data';
                   4566:               return (\%hash, $string);
                   4567:           }
                   4568:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4569:           ($key, $string)=&str2arrayref($string);
                   4570:           if($key->[0] eq 'Array reference error') {
                   4571:               $hash{'error'}='Bad data';
                   4572:               return (\%hash, $string);
                   4573:           }
                   4574:       } else {
                   4575:           $string =~ s/^(.*?)=//;
1.267     albertel 4576: 	  $key=&unescape($1);
1.265     albertel 4577:       }
                   4578:       $string =~ s/^=//;
                   4579: 
                   4580:       #value
                   4581:       my $value='';
                   4582:       if($string =~ /^__HASH_REF__/) {
                   4583:           ($value, $string)=&str2hashref($string);
                   4584:           if(defined($value->{'error'})) {
                   4585:               $hash{'error'}='Bad data';
                   4586:               return (\%hash, $string);
                   4587:           }
                   4588:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4589:           ($value, $string)=&str2arrayref($string);
                   4590:           if($value->[0] eq 'Array reference error') {
                   4591:               $hash{'error'}='Bad data';
                   4592:               return (\%hash, $string);
                   4593:           }
                   4594:       } else {
                   4595: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4596:       }
                   4597:       $string =~ s/^&//;
                   4598: 
                   4599:       $hash{$key}=$value;
1.204     albertel 4600:   }
1.265     albertel 4601: 
                   4602:   $string =~ s/^__END_HASH_REF__//;
                   4603: 
                   4604:   return (\%hash, $string);
1.204     albertel 4605: }
                   4606: 
                   4607: sub str2array {
1.265     albertel 4608:     my ($string)=@_;
                   4609:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4610:     return @$array;
                   4611: }
                   4612: 
                   4613: sub str2arrayref {
1.204     albertel 4614:   my ($string) = @_;
1.265     albertel 4615:   my @array;
                   4616: 
                   4617:   if($string !~ /^__ARRAY_REF__/) {
                   4618:       if (! ($string eq '' || !defined($string))) {
                   4619: 	  $array[0]='Array reference error';
                   4620:       }
                   4621:       return (\@array, $string);
                   4622:   }
                   4623: 
                   4624:   $string =~ s/^__ARRAY_REF__//;
                   4625: 
                   4626:   while($string !~ /^__END_ARRAY_REF__/) {
                   4627:       my $value='';
                   4628:       if($string =~ /^__HASH_REF__/) {
                   4629:           ($value, $string)=&str2hashref($string);
                   4630:           if(defined($value->{'error'})) {
                   4631:               $array[0] ='Array reference error';
                   4632:               return (\@array, $string);
                   4633:           }
                   4634:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4635:           ($value, $string)=&str2arrayref($string);
                   4636:           if($value->[0] eq 'Array reference error') {
                   4637:               $array[0] ='Array reference error';
                   4638:               return (\@array, $string);
                   4639:           }
                   4640:       } else {
                   4641: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4642:       }
                   4643:       $string =~ s/^&//;
                   4644: 
                   4645:       push(@array, $value);
1.191     harris41 4646:   }
1.265     albertel 4647: 
                   4648:   $string =~ s/^__END_ARRAY_REF__//;
                   4649: 
                   4650:   return (\@array, $string);
1.168     albertel 4651: }
                   4652: 
1.167     albertel 4653: # -------------------------------------------------------------------Temp Store
                   4654: 
1.168     albertel 4655: sub tmpreset {
                   4656:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4657:   if (!$symb) {
                   4658:     $symb=&symbread();
1.620     albertel 4659:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4660:   }
                   4661:   $symb=escape($symb);
                   4662: 
1.620     albertel 4663:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4664:   $namespace=~s/\//\_/g;
                   4665:   $namespace=~s/\W//g;
                   4666: 
1.620     albertel 4667:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4668:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4669:   if ($domain eq 'public' && $stuname eq 'public') {
                   4670:       $stuname=$ENV{'REMOTE_ADDR'};
                   4671:   }
1.1117    foxr     4672:   my $path=LONCAPA::tempdir();
1.168     albertel 4673:   my %hash;
                   4674:   if (tie(%hash,'GDBM_File',
                   4675: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4676: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4677:     foreach my $key (keys(%hash)) {
1.180     albertel 4678:       if ($key=~ /:$symb/) {
1.168     albertel 4679: 	delete($hash{$key});
                   4680:       }
                   4681:     }
                   4682:   }
                   4683: }
                   4684: 
1.167     albertel 4685: sub tmpstore {
1.168     albertel 4686:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4687: 
                   4688:   if (!$symb) {
                   4689:     $symb=&symbread();
1.620     albertel 4690:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4691:   }
                   4692:   $symb=escape($symb);
                   4693: 
                   4694:   if (!$namespace) {
                   4695:     # I don't think we would ever want to store this for a course.
                   4696:     # it seems this will only be used if we don't have a course.
1.620     albertel 4697:     #$namespace=$env{'request.course.id'};
1.168     albertel 4698:     #if (!$namespace) {
1.620     albertel 4699:       $namespace=$env{'request.state'};
1.168     albertel 4700:     #}
                   4701:   }
                   4702:   $namespace=~s/\//\_/g;
                   4703:   $namespace=~s/\W//g;
1.620     albertel 4704:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4705:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4706:   if ($domain eq 'public' && $stuname eq 'public') {
                   4707:       $stuname=$ENV{'REMOTE_ADDR'};
                   4708:   }
1.168     albertel 4709:   my $now=time;
                   4710:   my %hash;
1.1117    foxr     4711:   my $path=LONCAPA::tempdir();
1.168     albertel 4712:   if (tie(%hash,'GDBM_File',
                   4713: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4714: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4715:     $hash{"version:$symb"}++;
                   4716:     my $version=$hash{"version:$symb"};
                   4717:     my $allkeys=''; 
                   4718:     foreach my $key (keys(%$storehash)) {
                   4719:       $allkeys.=$key.':';
1.591     albertel 4720:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4721:     }
                   4722:     $hash{"$version:$symb:timestamp"}=$now;
                   4723:     $allkeys.='timestamp';
                   4724:     $hash{"$version:keys:$symb"}=$allkeys;
                   4725:     if (untie(%hash)) {
                   4726:       return 'ok';
                   4727:     } else {
                   4728:       return "error:$!";
                   4729:     }
                   4730:   } else {
                   4731:     return "error:$!";
                   4732:   }
                   4733: }
1.167     albertel 4734: 
1.168     albertel 4735: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4736: 
1.168     albertel 4737: sub tmprestore {
                   4738:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4739: 
1.168     albertel 4740:   if (!$symb) {
                   4741:     $symb=&symbread();
1.620     albertel 4742:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4743:   }
                   4744:   $symb=escape($symb);
                   4745: 
1.620     albertel 4746:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4747: 
1.620     albertel 4748:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4749:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4750:   if ($domain eq 'public' && $stuname eq 'public') {
                   4751:       $stuname=$ENV{'REMOTE_ADDR'};
                   4752:   }
1.168     albertel 4753:   my %returnhash;
                   4754:   $namespace=~s/\//\_/g;
                   4755:   $namespace=~s/\W//g;
                   4756:   my %hash;
1.1117    foxr     4757:   my $path=LONCAPA::tempdir();
1.168     albertel 4758:   if (tie(%hash,'GDBM_File',
                   4759: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4760: 	  &GDBM_READER(),0640)) {
1.168     albertel 4761:     my $version=$hash{"version:$symb"};
                   4762:     $returnhash{'version'}=$version;
                   4763:     my $scope;
                   4764:     for ($scope=1;$scope<=$version;$scope++) {
                   4765:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4766:       my @keys=split(/:/,$vkeys);
                   4767:       my $key;
                   4768:       $returnhash{"$scope:keys"}=$vkeys;
                   4769:       foreach $key (@keys) {
1.591     albertel 4770: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4771: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4772:       }
                   4773:     }
1.168     albertel 4774:     if (!(untie(%hash))) {
                   4775:       return "error:$!";
                   4776:     }
                   4777:   } else {
                   4778:     return "error:$!";
                   4779:   }
                   4780:   return %returnhash;
1.167     albertel 4781: }
                   4782: 
1.9       www      4783: # ----------------------------------------------------------------------- Store
                   4784: 
                   4785: sub store {
1.124     www      4786:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4787:     my $home='';
                   4788: 
1.168     albertel 4789:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4790: 
1.213     www      4791:     $symb=&symbclean($symb);
1.122     albertel 4792:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4793: 
1.620     albertel 4794:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4795:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4796: 
                   4797:     &devalidate($symb,$stuname,$domain);
1.109     www      4798: 
                   4799:     $symb=escape($symb);
1.187     www      4800:     if (!$namespace) { 
1.620     albertel 4801:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4802:           return ''; 
                   4803:        } 
                   4804:     }
1.620     albertel 4805:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4806: 
                   4807:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4808:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4809: 
1.12      www      4810:     my $namevalue='';
1.800     albertel 4811:     foreach my $key (keys(%$storehash)) {
                   4812:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4813:     }
1.12      www      4814:     $namevalue=~s/\&$//;
1.187     www      4815:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4816:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4817: }
                   4818: 
1.47      www      4819: # -------------------------------------------------------------- Critical Store
                   4820: 
                   4821: sub cstore {
1.124     www      4822:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4823:     my $home='';
                   4824: 
1.168     albertel 4825:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4826: 
1.213     www      4827:     $symb=&symbclean($symb);
1.122     albertel 4828:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4829: 
1.620     albertel 4830:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4831:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4832: 
                   4833:     &devalidate($symb,$stuname,$domain);
1.109     www      4834: 
                   4835:     $symb=escape($symb);
1.187     www      4836:     if (!$namespace) { 
1.620     albertel 4837:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4838:           return ''; 
                   4839:        } 
                   4840:     }
1.620     albertel 4841:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4842: 
                   4843:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4844:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4845: 
1.47      www      4846:     my $namevalue='';
1.800     albertel 4847:     foreach my $key (keys(%$storehash)) {
                   4848:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4849:     }
1.47      www      4850:     $namevalue=~s/\&$//;
1.187     www      4851:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4852:     return critical
                   4853:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4854: }
                   4855: 
1.9       www      4856: # --------------------------------------------------------------------- Restore
                   4857: 
                   4858: sub restore {
1.124     www      4859:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4860:     my $home='';
                   4861: 
1.168     albertel 4862:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4863: 
1.122     albertel 4864:     if (!$symb) {
1.1224    raeburn  4865:         return if ($namespace eq 'courserequests');
                   4866:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4867:     } else {
1.1224    raeburn  4868:         unless ($namespace eq 'courserequests') {
                   4869:             $symb=&escape(&symbclean($symb));
                   4870:         }
1.122     albertel 4871:     }
1.188     www      4872:     if (!$namespace) { 
1.620     albertel 4873:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4874:           return ''; 
                   4875:        } 
                   4876:     }
1.620     albertel 4877:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4878:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4879:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4880:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4881: 
1.12      www      4882:     my %returnhash=();
1.800     albertel 4883:     foreach my $line (split(/\&/,$answer)) {
                   4884: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4885:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4886:     }
1.75      www      4887:     my $version;
                   4888:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4889:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4890:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4891:        }
1.75      www      4892:     }
1.13      www      4893:     return %returnhash;
1.34      www      4894: }
                   4895: 
                   4896: # ---------------------------------------------------------- Course Description
1.1118    foxr     4897: #
                   4898: #  
1.34      www      4899: 
                   4900: sub coursedescription {
1.731     albertel 4901:     my ($courseid,$args)=@_;
1.34      www      4902:     $courseid=~s/^\///;
1.49      www      4903:     $courseid=~s/\_/\//g;
1.34      www      4904:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4905:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4906:     my $normalid=$cdomain.'_'.$cnum;
                   4907:     # need to always cache even if we get errors otherwise we keep 
                   4908:     # trying and trying and trying to get the course description.
                   4909:     my %envhash=();
                   4910:     my %returnhash=();
1.731     albertel 4911:     
                   4912:     my $expiretime=600;
                   4913:     if ($env{'request.course.id'} eq $normalid) {
                   4914: 	$expiretime=120;
                   4915:     }
                   4916: 
                   4917:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4918:     if (!$args->{'freshen_cache'}
                   4919: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4920: 	foreach my $key (keys(%env)) {
                   4921: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4922: 	    my ($setting) = $1;
                   4923: 	    $returnhash{$setting} = $env{$key};
                   4924: 	}
                   4925: 	return %returnhash;
                   4926:     }
                   4927: 
1.1118    foxr     4928:     # get the data again
                   4929: 
1.731     albertel 4930:     if (!$args->{'one_time'}) {
                   4931: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4932:     }
1.811     albertel 4933: 
1.34      www      4934:     if ($chome ne 'no_host') {
1.302     albertel 4935:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4936:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4937: 	   my $username = $env{'user.name'}; # Defult username
                   4938: 	   if(defined $args->{'user'}) {
                   4939: 	       $username = $args->{'user'};
                   4940: 	   }
1.129     albertel 4941:            $returnhash{'home'}= $chome;
                   4942: 	   $returnhash{'domain'} = $cdomain;
                   4943: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4944:            if (!defined($returnhash{'type'})) {
                   4945:                $returnhash{'type'} = 'Course';
                   4946:            }
1.130     albertel 4947:            while (my ($name,$value) = each %returnhash) {
1.53      www      4948:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4949:            }
1.270     www      4950:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4951:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4952: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4953:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4954:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4955:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4956:        }
                   4957:     }
1.731     albertel 4958:     if (!$args->{'one_time'}) {
1.949     raeburn  4959: 	&appenv(\%envhash);
1.731     albertel 4960:     }
1.302     albertel 4961:     return %returnhash;
1.461     www      4962: }
                   4963: 
1.1080    raeburn  4964: sub update_released_required {
                   4965:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4966:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4967:         $cid = $env{'request.course.id'};
                   4968:         $cdom = $env{'course.'.$cid.'.domain'};
                   4969:         $cnum = $env{'course.'.$cid.'.num'};
                   4970:         $chome = $env{'course.'.$cid.'.home'};
                   4971:     }
                   4972:     if ($needsrelease) {
                   4973:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4974:         my $needsupdate;
                   4975:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4976:             $needsupdate = 1;
                   4977:         } else {
                   4978:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4979:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4980:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4981:                 $needsupdate = 1;
                   4982:             }
                   4983:         }
                   4984:         if ($needsupdate) {
                   4985:             my %needshash = (
                   4986:                              'internal.releaserequired' => $needsrelease,
                   4987:                             );
                   4988:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4989:             if ($putresult eq 'ok') {
                   4990:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4991:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4992:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4993:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4994:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4995:                 }
                   4996:             }
                   4997:         }
                   4998:     }
                   4999:     return;
                   5000: }
                   5001: 
1.461     www      5002: # -------------------------------------------------See if a user is privileged
                   5003: 
                   5004: sub privileged {
1.1219    raeburn  5005:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5006:     my $now = time;
1.1219    raeburn  5007:     my $roles;
                   5008:     if (ref($possroles) eq 'ARRAY') {
                   5009:         $roles = $possroles; 
                   5010:     } else {
                   5011:         $roles = ['dc','su'];
                   5012:     }
                   5013:     if (ref($possdomains) eq 'ARRAY') {
                   5014:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5015:         foreach my $dom (@{$possdomains}) {
                   5016:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5017:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5018:                 foreach my $role (@{$roles}) {
                   5019:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5020:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5021:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5022:                             return 1 unless (($end && $end < $now) ||
                   5023:                                              ($start && $start > $now));
                   5024:                         }
                   5025:                     }
                   5026:                 }
                   5027:             }
                   5028:         }
                   5029:     } else {
                   5030:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5031:         my $now = time;
1.1170    droeschl 5032: 
1.1219    raeburn  5033:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5034:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5035:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5036:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5037:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5038:             }
1.1219    raeburn  5039:         }
                   5040:     }
                   5041:     return 0;
                   5042: }
1.1170    droeschl 5043: 
1.1219    raeburn  5044: sub privileged_by_domain {
                   5045:     my ($domains,$roles) = @_;
                   5046:     my %privileged = ();
                   5047:     my $cachetime = 60*60*24;
                   5048:     my $now = time;
                   5049:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5050:         return %privileged;
                   5051:     }
                   5052:     foreach my $dom (@{$domains}) {
                   5053:         next if (ref($privileged{$dom}) eq 'HASH');
                   5054:         my $needroles;
                   5055:         foreach my $role (@{$roles}) {
                   5056:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5057:             if (defined($cached)) {
                   5058:                 if (ref($result) eq 'HASH') {
                   5059:                     $privileged{$dom}{$role} = $result;
                   5060:                 }
                   5061:             } else {
                   5062:                 $needroles = 1;
                   5063:             }
                   5064:         }
                   5065:         if ($needroles) {
                   5066:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5067:             $privileged{$dom} = {};
                   5068:             foreach my $server (keys(%dompersonnel)) {
                   5069:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5070:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5071:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5072:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5073:                         next if ($end && $end < $now);
                   5074:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5075:                             $dompersonnel{$server}{$item};
                   5076:                     }
                   5077:                 }
                   5078:             }
                   5079:             if (ref($privileged{$dom}) eq 'HASH') {
                   5080:                 foreach my $role (@{$roles}) {
                   5081:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5082:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5083:                     } else {
                   5084:                         my %hash = ();
                   5085:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5086:                     }
                   5087:                 }
                   5088:             }
                   5089:         }
                   5090:     }
                   5091:     return %privileged;
1.9       www      5092: }
1.1       albertel 5093: 
1.103     harris41 5094: # -------------------------------------------------------- Get user privileges
1.11      www      5095: 
                   5096: sub rolesinit {
1.1169    droeschl 5097:     my ($domain, $username) = @_;
                   5098:     my %userroles = ('user.login.time' => time);
                   5099:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5100: 
                   5101:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5102:     # also, blocking can be triggered by an activating timer
                   5103:     # it's saved in the user's %env.
                   5104:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5105:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5106:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5107:         %timerintchk, %timerintenv);
                   5108: 
1.1162    raeburn  5109:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5110:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5111:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5112:     }
1.1169    droeschl 5113: 
1.1162    raeburn  5114:     foreach my $key (keys(%timerinterval)) {
                   5115:         my ($cid,$rest) = split(/\0/,$key);
                   5116:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5117:     }
1.1169    droeschl 5118: 
1.11      www      5119:     my %allroles=();
1.1162    raeburn  5120:     my %allgroups=();
1.11      www      5121: 
1.1169    droeschl 5122:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5123:         my $role = $rolesdump{$area};
                   5124:         $area =~ s/\_\w\w$//;
                   5125: 
                   5126:         my ($trole, $tend, $tstart, $group_privs);
                   5127: 
                   5128:         if ($role =~ /^cr/) {
                   5129:         # Custom role, defined by a user 
                   5130:         # e.g., user.role.cr/msu/smith/mynewrole
                   5131:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5132:                 $trole = $1;
                   5133:                 ($tend, $tstart) = split('_', $2);
                   5134:             } else {
                   5135:                 $trole = $role;
                   5136:             }
                   5137:         } elsif ($role =~ m|^gr/|) {
                   5138:         # Role of member in a group, defined within a course/community
                   5139:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5140:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5141:             next if $tstart eq '-1';
                   5142:             ($trole, $group_privs) = split(/\//, $trole);
                   5143:             $group_privs = &unescape($group_privs);
                   5144:         } else {
                   5145:         # Just a normal role, defined in roles.tab
                   5146:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5147:         }
                   5148: 
                   5149:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5150:                  $username);
                   5151:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5152: 
                   5153:         # role expired or not available yet?
                   5154:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5155:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5156: 
                   5157:         next if $area eq '' or $trole eq '';
                   5158: 
                   5159:         my $spec = "$trole.$area";
                   5160:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5161: 
                   5162:         if ($trole =~ /^cr\//) {
                   5163:         # Custom role, defined by a user
                   5164:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5165:         } elsif ($trole eq 'gr') {
                   5166:         # Role of a member in a group, defined within a course/community
                   5167:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5168:             next;
                   5169:         } else {
                   5170:         # Normal role, defined in roles.tab
                   5171:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5172:         }
                   5173: 
                   5174:         my $cid = $tdomain.'_'.$trest;
                   5175:         unless ($firstaccchk{$cid}) {
                   5176:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5177:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5178:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5179:                         $coursetimerstarts{$cid}{$item}; 
                   5180:                 }
                   5181:             }
                   5182:             $firstaccchk{$cid} = 1;
                   5183:         }
                   5184:         unless ($timerintchk{$cid}) {
                   5185:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5186:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5187:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5188:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5189:                 }
1.12      www      5190:             }
1.1169    droeschl 5191:             $timerintchk{$cid} = 1;
1.191     harris41 5192:         }
1.11      www      5193:     }
1.1169    droeschl 5194: 
                   5195:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5196:         \%allroles, \%allgroups);
                   5197:     $env{'user.adv'} = $userroles{'user.adv'};
                   5198: 
1.1162    raeburn  5199:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5200: }
                   5201: 
1.567     raeburn  5202: sub set_arearole {
1.1215    raeburn  5203:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5204:     unless ($nolog) {
1.567     raeburn  5205: # log the associated role with the area
1.1215    raeburn  5206:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5207:     }
1.743     albertel 5208:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5209: }
                   5210: 
                   5211: sub custom_roleprivs {
                   5212:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5213:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5214:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5215:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5216:         my ($rdummy,$roledef)=
                   5217:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5218:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5219:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5220:             if (defined($syspriv)) {
1.1043    raeburn  5221:                 if ($trest =~ /^$match_community$/) {
                   5222:                     $syspriv =~ s/bre\&S//; 
                   5223:                 }
1.567     raeburn  5224:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5225:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5226:             }
                   5227:             if ($tdomain ne '') {
                   5228:                 if (defined($dompriv)) {
                   5229:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5230:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5231:                 }
                   5232:                 if (($trest ne '') && (defined($coursepriv))) {
                   5233:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5234:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5235:                 }
                   5236:             }
                   5237:         }
                   5238:     }
                   5239: }
                   5240: 
1.678     raeburn  5241: sub group_roleprivs {
                   5242:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5243:     my $access = 1;
                   5244:     my $now = time;
                   5245:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5246:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5247:     if ($access) {
1.811     albertel 5248:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5249:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5250:     }
                   5251: }
1.567     raeburn  5252: 
                   5253: sub standard_roleprivs {
                   5254:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5255:     if (defined($pr{$trole.':s'})) {
                   5256:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5257:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5258:     }
                   5259:     if ($tdomain ne '') {
                   5260:         if (defined($pr{$trole.':d'})) {
                   5261:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5262:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5263:         }
                   5264:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5265:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5266:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5267:         }
                   5268:     }
                   5269: }
                   5270: 
                   5271: sub set_userprivs {
1.1064    raeburn  5272:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5273:     my $author=0;
                   5274:     my $adv=0;
1.678     raeburn  5275:     my %grouproles = ();
                   5276:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5277:         my @groupkeys; 
1.1000    raeburn  5278:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5279:             push(@groupkeys,$role);
                   5280:         }
                   5281:         if (ref($groups_roles) eq 'HASH') {
                   5282:             foreach my $key (keys(%{$groups_roles})) {
                   5283:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5284:                     push(@groupkeys,$key);
                   5285:                 }
                   5286:             }
                   5287:         }
                   5288:         if (@groupkeys > 0) {
                   5289:             foreach my $role (@groupkeys) {
                   5290:                 my ($trole,$area,$sec,$extendedarea);
                   5291:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5292:                     $trole = $1;
                   5293:                     $area = $2;
                   5294:                     $sec = $3;
                   5295:                     $extendedarea = $area.$sec;
                   5296:                     if (exists($$allgroups{$area})) {
                   5297:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5298:                             my $spec = $trole.'.'.$extendedarea;
                   5299:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5300:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5301:                         }
1.678     raeburn  5302:                     }
                   5303:                 }
                   5304:             }
                   5305:         }
                   5306:     }
1.800     albertel 5307:     foreach my $group (keys(%grouproles)) {
                   5308:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5309:     }
1.800     albertel 5310:     foreach my $role (keys(%{$allroles})) {
                   5311:         my %thesepriv;
1.941     raeburn  5312:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5313:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5314:             if ($item ne '') {
                   5315:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5316:                 if ($restrictions eq '') {
                   5317:                     $thesepriv{$privilege}='F';
                   5318:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5319:                     $thesepriv{$privilege}.=$restrictions;
                   5320:                 }
                   5321:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5322:             }
                   5323:         }
                   5324:         my $thesestr='';
1.1104    raeburn  5325:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5326: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5327: 	}
                   5328:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5329:     }
                   5330:     return ($author,$adv);
                   5331: }
                   5332: 
1.994     raeburn  5333: sub role_status {
1.1104    raeburn  5334:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5335:     my @pwhere = ();
                   5336:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5337:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5338:         unless (!defined($$role) || $$role eq '') {
                   5339:             $$where=join('.',@pwhere);
                   5340:             $$trolecode=$$role.'.'.$$where;
                   5341:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5342:             $$tstatus='is';
1.1104    raeburn  5343:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5344:                 $$tstatus='future';
1.1034    raeburn  5345:                 if ($$tstart<$now) {
                   5346:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5347:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5348:                             my (%allroles,%allgroups,$group_privs,
                   5349:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5350:                             my %userroles = (
                   5351:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5352:                             );
1.1064    raeburn  5353:                             @rolecodes = ('cm'); 
1.1002    raeburn  5354:                             my $spec=$$role.'.'.$$where;
                   5355:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5356:                             if ($$role =~ /^cr\//) {
                   5357:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5358:                                 push(@rolecodes,'cr');
1.1002    raeburn  5359:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5360:                                 push(@rolecodes,$$role);
1.1002    raeburn  5361:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5362:                                                     $env{'user.name'});
1.1064    raeburn  5363:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5364:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5365:                                 $group_privs = &unescape($group_privs);
                   5366:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5367:                                 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  5368:                                 &get_groups_roles($tdomain,$trest,
                   5369:                                                   \%course_roles,\@rolecodes,
                   5370:                                                   \%groups_roles);
1.1002    raeburn  5371:                             } else {
1.1064    raeburn  5372:                                 push(@rolecodes,$$role);
1.1002    raeburn  5373:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5374:                             }
1.1064    raeburn  5375:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5376:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5377:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5378:                         }
                   5379:                     }
1.1034    raeburn  5380:                     $$tstatus = 'is';
1.1002    raeburn  5381:                 }
1.994     raeburn  5382:             }
                   5383:             if ($$tend) {
1.1104    raeburn  5384:                 if ($$tend<$update) {
1.994     raeburn  5385:                     $$tstatus='expired';
                   5386:                 } elsif ($$tend<$now) {
                   5387:                     $$tstatus='will_not';
                   5388:                 }
                   5389:             }
                   5390:         }
                   5391:     }
                   5392: }
                   5393: 
1.1104    raeburn  5394: sub get_groups_roles {
                   5395:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5396:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5397:                   (ref($rolecodes) eq 'ARRAY') && 
                   5398:                   (ref($groups_roles) eq 'HASH')); 
                   5399:     if (keys(%{$cdom_courseroles}) > 0) {
                   5400:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5401:         if ($cdom ne '' && $cnum ne '') {
                   5402:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5403:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5404:                     my $crsrole = $1;
                   5405:                     my $crssec = $2;
                   5406:                     if ($crsrole =~ /^cr/) {
                   5407:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5408:                             push(@{$rolecodes},'cr');
                   5409:                         }
                   5410:                     } else {
                   5411:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5412:                             push(@{$rolecodes},$crsrole);
                   5413:                         }
                   5414:                     }
                   5415:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5416:                     if ($crssec ne '') {
                   5417:                         $rolekey .= "/$crssec";
                   5418:                     }
                   5419:                     $rolekey .= './';
                   5420:                     $groups_roles->{$rolekey} = $rolecodes;
                   5421:                 }
                   5422:             }
                   5423:         }
                   5424:     }
                   5425:     return;
                   5426: }
                   5427: 
                   5428: sub delete_env_groupprivs {
                   5429:     my ($where,$courseroles,$possroles) = @_;
                   5430:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5431:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5432:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5433:         %{$courseroles->{$udom}} =
                   5434:             &get_my_roles('','','userroles',['active'],
                   5435:                           $possroles,[$udom],1);
                   5436:     }
                   5437:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5438:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5439:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5440:             my $area = '/'.$cdom.'/'.$cnum;
                   5441:             my $privkey = "user.priv.$crsrole.$area";
                   5442:             if ($crssec ne '') {
                   5443:                 $privkey .= '/'.$crssec;
                   5444:             }
                   5445:             $privkey .= ".$area/$group";
                   5446:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5447:         }
                   5448:     }
                   5449:     return;
                   5450: }
                   5451: 
1.994     raeburn  5452: sub check_adhoc_privs {
1.1104    raeburn  5453:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5454:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5455:     my $setprivs;
1.994     raeburn  5456:     if ($env{$cckey}) {
                   5457:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5458:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5459:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5460:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5461:             $setprivs = 1;
1.994     raeburn  5462:         }
                   5463:     } else {
1.1088    raeburn  5464:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5465:         $setprivs = 1;
1.994     raeburn  5466:     }
1.1185    raeburn  5467:     return $setprivs;
1.994     raeburn  5468: }
                   5469: 
                   5470: sub set_adhoc_privileges {
                   5471: # role can be cc or ca
1.1088    raeburn  5472:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5473:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5474:     my $spec = $role.'.'.$area;
                   5475:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5476:                                   $env{'user.name'},1);
1.994     raeburn  5477:     my %ccrole = ();
                   5478:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5479:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5480:     &appenv(\%userroles,[$role,'cm']);
                   5481:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5482:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5483:         &appenv( {'request.role'        => $spec,
                   5484:                   'request.role.domain' => $dcdom,
                   5485:                   'request.course.sec'  => ''
                   5486:                  }
                   5487:                );
                   5488:         my $tadv=0;
                   5489:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5490:         &appenv({'request.role.adv'    => $tadv});
                   5491:     }
1.994     raeburn  5492: }
                   5493: 
1.12      www      5494: # --------------------------------------------------------------- get interface
                   5495: 
                   5496: sub get {
1.131     albertel 5497:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5498:    my $items='';
1.800     albertel 5499:    foreach my $item (@$storearr) {
                   5500:        $items.=&escape($item).'&';
1.191     harris41 5501:    }
1.12      www      5502:    $items=~s/\&$//;
1.620     albertel 5503:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5504:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5505:    my $uhome=&homeserver($uname,$udomain);
                   5506: 
1.133     albertel 5507:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5508:    my @pairs=split(/\&/,$rep);
1.273     albertel 5509:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5510:      return @pairs;
                   5511:    }
1.15      www      5512:    my %returnhash=();
1.42      www      5513:    my $i=0;
1.800     albertel 5514:    foreach my $item (@$storearr) {
                   5515:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5516:       $i++;
1.191     harris41 5517:    }
1.15      www      5518:    return %returnhash;
1.27      www      5519: }
                   5520: 
                   5521: # --------------------------------------------------------------- del interface
                   5522: 
                   5523: sub del {
1.133     albertel 5524:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5525:    my $items='';
1.800     albertel 5526:    foreach my $item (@$storearr) {
                   5527:        $items.=&escape($item).'&';
1.191     harris41 5528:    }
1.984     neumanie 5529: 
1.27      www      5530:    $items=~s/\&$//;
1.620     albertel 5531:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5532:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5533:    my $uhome=&homeserver($uname,$udomain);
                   5534:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5535: }
                   5536: 
                   5537: # -------------------------------------------------------------- dump interface
                   5538: 
1.1180    droeschl 5539: sub unserialize {
                   5540:     my ($rep, $escapedkeys) = @_;
                   5541: 
                   5542:     return {} if $rep =~ /^error/;
                   5543: 
                   5544:     my %returnhash=();
                   5545: 	foreach my $item (split /\&/, $rep) {
                   5546: 	    my ($key, $value) = split(/=/, $item, 2);
                   5547: 	    $key = unescape($key) unless $escapedkeys;
                   5548: 	    next if $key =~ /^error: 2 /;
                   5549: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5550: 	}
                   5551:     #return %returnhash;
                   5552:     return \%returnhash;
                   5553: }        
                   5554: 
                   5555: # see Lond::dump_with_regexp
                   5556: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5557: sub dump {
1.1180    droeschl 5558:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5559:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5560:     if (!$uname) { $uname=$env{'user.name'}; }
                   5561:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5562: 
1.1180    droeschl 5563:     my $reply;
                   5564:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5565:         # user is hosted on this machine
                   5566:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5567:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5568:         return %{unserialize($reply, $escapedkeys)};
                   5569:     }
1.755     albertel 5570:     if ($regexp) {
                   5571: 	$regexp=&escape($regexp);
                   5572:     } else {
                   5573: 	$regexp='.';
                   5574:     }
1.1166    raeburn  5575:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5576:     my @pairs=split(/\&/,$rep);
                   5577:     my %returnhash=();
1.1098    foxr     5578:     if (!($rep =~ /^error/ )) {
                   5579: 	foreach my $item (@pairs) {
                   5580: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5581:         $key = unescape($key) unless $escapedkeys;
                   5582:         #$key = &unescape($key);
1.1098    foxr     5583: 	    next if ($key =~ /^error: 2 /);
                   5584: 	    $returnhash{$key}=&thaw_unescape($value);
                   5585: 	}
1.755     albertel 5586:     }
                   5587:     return %returnhash;
1.407     www      5588: }
                   5589: 
1.1098    foxr     5590: 
1.717     albertel 5591: # --------------------------------------------------------- dumpstore interface
                   5592: 
                   5593: sub dumpstore {
                   5594:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5595:    # same as dump but keys must be escaped. They may contain colon separated
                   5596:    # lists of values that may themself contain colons (e.g. symbs).
                   5597:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5598: }
                   5599: 
1.407     www      5600: # -------------------------------------------------------------- keys interface
                   5601: 
                   5602: sub getkeys {
                   5603:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5604:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5605:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5606:    my $uhome=&homeserver($uname,$udomain);
                   5607:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5608:    my @keyarray=();
1.800     albertel 5609:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5610:       next if ($key =~ /^error: 2 /);
1.800     albertel 5611:       push(@keyarray,&unescape($key));
1.407     www      5612:    }
                   5613:    return @keyarray;
1.318     matthew  5614: }
                   5615: 
1.319     matthew  5616: # --------------------------------------------------------------- currentdump
                   5617: sub currentdump {
1.328     matthew  5618:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5619:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5620:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5621:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5622:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5623:    my $rep;
                   5624: 
                   5625:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5626:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5627:                    $courseid)));
                   5628:    } else {
                   5629:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5630:    }
                   5631: 
1.318     matthew  5632:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5633:    #
1.318     matthew  5634:    my %returnhash=();
1.319     matthew  5635:    #
                   5636:    if ($rep eq "unknown_cmd") { 
                   5637:        # an old lond will not know currentdump
                   5638:        # Do a dump and make it look like a currentdump
1.822     albertel 5639:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5640:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5641:        my %hash = @tmp;
                   5642:        @tmp=();
1.424     matthew  5643:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5644:    } else {
                   5645:        my @pairs=split(/\&/,$rep);
1.800     albertel 5646:        foreach my $pair (@pairs) {
                   5647:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5648:            my ($symb,$param) = split(/:/,$key);
                   5649:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5650:                                                         &thaw_unescape($value);
1.319     matthew  5651:        }
1.191     harris41 5652:    }
1.12      www      5653:    return %returnhash;
1.424     matthew  5654: }
                   5655: 
                   5656: sub convert_dump_to_currentdump{
                   5657:     my %hash = %{shift()};
                   5658:     my %returnhash;
                   5659:     # Code ripped from lond, essentially.  The only difference
                   5660:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5661:     # we might run in to problems with parameter names =~ /^v\./
                   5662:     while (my ($key,$value) = each(%hash)) {
                   5663:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5664: 	$symb  = &unescape($symb);
                   5665: 	$param = &unescape($param);
1.424     matthew  5666:         next if ($v eq 'version' || $symb eq 'keys');
                   5667:         next if (exists($returnhash{$symb}) &&
                   5668:                  exists($returnhash{$symb}->{$param}) &&
                   5669:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5670:         $returnhash{$symb}->{$param}=$value;
                   5671:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5672:     }
                   5673:     #
                   5674:     # Remove all of the keys in the hashes which keep track of
                   5675:     # the version of the parameter.
                   5676:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5677:         # use a foreach because we are going to delete from the hash.
                   5678:         foreach my $key (keys(%$param_hash)) {
                   5679:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5680:         }
                   5681:     }
                   5682:     return \%returnhash;
1.12      www      5683: }
                   5684: 
1.627     albertel 5685: # ------------------------------------------------------ critical inc interface
                   5686: 
                   5687: sub cinc {
                   5688:     return &inc(@_,'critical');
                   5689: }
                   5690: 
1.449     matthew  5691: # --------------------------------------------------------------- inc interface
                   5692: 
                   5693: sub inc {
1.627     albertel 5694:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5695:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5696:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5697:     my $uhome=&homeserver($uname,$udomain);
                   5698:     my $items='';
                   5699:     if (! ref($store)) {
                   5700:         # got a single value, so use that instead
                   5701:         $items = &escape($store).'=&';
                   5702:     } elsif (ref($store) eq 'SCALAR') {
                   5703:         $items = &escape($$store).'=&';        
                   5704:     } elsif (ref($store) eq 'ARRAY') {
                   5705:         $items = join('=&',map {&escape($_);} @{$store});
                   5706:     } elsif (ref($store) eq 'HASH') {
                   5707:         while (my($key,$value) = each(%{$store})) {
                   5708:             $items.= &escape($key).'='.&escape($value).'&';
                   5709:         }
                   5710:     }
                   5711:     $items=~s/\&$//;
1.627     albertel 5712:     if ($critical) {
                   5713: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5714:     } else {
                   5715: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5716:     }
1.449     matthew  5717: }
                   5718: 
1.12      www      5719: # --------------------------------------------------------------- put interface
                   5720: 
                   5721: sub put {
1.134     albertel 5722:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5723:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5724:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5725:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5726:    my $items='';
1.800     albertel 5727:    foreach my $item (keys(%$storehash)) {
                   5728:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5729:    }
1.12      www      5730:    $items=~s/\&$//;
1.134     albertel 5731:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5732: }
                   5733: 
1.631     albertel 5734: # ------------------------------------------------------------ newput interface
                   5735: 
                   5736: sub newput {
                   5737:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5738:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5739:    if (!$uname) { $uname=$env{'user.name'}; }
                   5740:    my $uhome=&homeserver($uname,$udomain);
                   5741:    my $items='';
                   5742:    foreach my $key (keys(%$storehash)) {
                   5743:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5744:    }
                   5745:    $items=~s/\&$//;
                   5746:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5747: }
                   5748: 
                   5749: # ---------------------------------------------------------  putstore interface
                   5750: 
1.524     raeburn  5751: sub putstore {
1.715     albertel 5752:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5753:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5754:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5755:    my $uhome=&homeserver($uname,$udomain);
                   5756:    my $items='';
1.715     albertel 5757:    foreach my $key (keys(%$storehash)) {
                   5758:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5759:    }
1.715     albertel 5760:    $items=~s/\&$//;
1.716     albertel 5761:    my $esc_symb=&escape($symb);
                   5762:    my $esc_v=&escape($version);
1.715     albertel 5763:    my $reply =
1.716     albertel 5764:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5765: 	      $uhome);
                   5766:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5767:        # gfall back to way things use to be done
1.715     albertel 5768:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5769: 			    $uname);
1.524     raeburn  5770:    }
1.715     albertel 5771:    return $reply;
                   5772: }
                   5773: 
                   5774: sub old_putstore {
1.716     albertel 5775:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5776:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5777:     if (!$uname) { $uname=$env{'user.name'}; }
                   5778:     my $uhome=&homeserver($uname,$udomain);
                   5779:     my %newstorehash;
1.800     albertel 5780:     foreach my $item (keys(%$storehash)) {
                   5781: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5782: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5783:     }
                   5784:     my $items='';
                   5785:     my %allitems = ();
1.800     albertel 5786:     foreach my $item (keys(%newstorehash)) {
                   5787: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5788: 	    my $key = $1.':keys:'.$2;
                   5789: 	    $allitems{$key} .= $3.':';
                   5790: 	}
1.800     albertel 5791: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5792:     }
1.800     albertel 5793:     foreach my $item (keys(%allitems)) {
                   5794: 	$allitems{$item} =~ s/\:$//;
                   5795: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5796:     }
                   5797:     $items=~s/\&$//;
                   5798:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5799: }
                   5800: 
1.47      www      5801: # ------------------------------------------------------ critical put interface
                   5802: 
                   5803: sub cput {
1.134     albertel 5804:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5805:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5806:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5807:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5808:    my $items='';
1.800     albertel 5809:    foreach my $item (keys(%$storehash)) {
                   5810:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5811:    }
1.47      www      5812:    $items=~s/\&$//;
1.134     albertel 5813:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5814: }
                   5815: 
                   5816: # -------------------------------------------------------------- eget interface
                   5817: 
                   5818: sub eget {
1.133     albertel 5819:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5820:    my $items='';
1.800     albertel 5821:    foreach my $item (@$storearr) {
                   5822:        $items.=&escape($item).'&';
1.191     harris41 5823:    }
1.12      www      5824:    $items=~s/\&$//;
1.620     albertel 5825:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5826:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5827:    my $uhome=&homeserver($uname,$udomain);
                   5828:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5829:    my @pairs=split(/\&/,$rep);
                   5830:    my %returnhash=();
1.42      www      5831:    my $i=0;
1.800     albertel 5832:    foreach my $item (@$storearr) {
                   5833:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5834:       $i++;
1.191     harris41 5835:    }
1.12      www      5836:    return %returnhash;
                   5837: }
                   5838: 
1.667     albertel 5839: # ------------------------------------------------------------ tmpput interface
                   5840: sub tmpput {
1.802     raeburn  5841:     my ($storehash,$server,$context)=@_;
1.667     albertel 5842:     my $items='';
1.800     albertel 5843:     foreach my $item (keys(%$storehash)) {
                   5844: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5845:     }
                   5846:     $items=~s/\&$//;
1.802     raeburn  5847:     if (defined($context)) {
                   5848:         $items .= ':'.&escape($context);
                   5849:     }
1.667     albertel 5850:     return &reply("tmpput:$items",$server);
                   5851: }
                   5852: 
                   5853: # ------------------------------------------------------------ tmpget interface
                   5854: sub tmpget {
1.688     albertel 5855:     my ($token,$server)=@_;
                   5856:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5857:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5858:     my %returnhash;
                   5859:     foreach my $item (split(/\&/,$rep)) {
                   5860: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5861:         next if ($key =~ /^error: 2 /);
1.667     albertel 5862: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5863:     }
                   5864:     return %returnhash;
                   5865: }
                   5866: 
1.1113    raeburn  5867: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5868: sub tmpdel {
                   5869:     my ($token,$server)=@_;
                   5870:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5871:     return &reply("tmpdel:$token",$server);
                   5872: }
                   5873: 
1.1198    raeburn  5874: # ------------------------------------------------------------ get_timebased_id 
                   5875: 
                   5876: sub get_timebased_id {
                   5877:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5878:         $maxtries) = @_;
                   5879:     my ($newid,$error,$dellock);
                   5880:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5881:         return ('','ok','invalid call to get suffix');
                   5882:     }
                   5883: 
                   5884: # set defaults for any optional args for which values were not supplied
                   5885:     if ($who eq '') {
                   5886:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5887:     }
                   5888:     if (!$locktries) {
                   5889:         $locktries = 3;
                   5890:     }
                   5891:     if (!$maxtries) {
                   5892:         $maxtries = 10;
                   5893:     }
                   5894:     
                   5895:     if (($cdom eq '') || ($cnum eq '')) {
                   5896:         if ($env{'request.course.id'}) {
                   5897:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5898:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5899:         }
                   5900:         if (($cdom eq '') || ($cnum eq '')) {
                   5901:             return ('','ok','call to get suffix not in course context');
                   5902:         }
                   5903:     }
                   5904: 
                   5905: # construct locking item
                   5906:     my $lockhash = {
                   5907:                       $prefix."\0".'locked_'.$keyid => $who,
                   5908:                    };
                   5909:     my $tries = 0;
                   5910: 
                   5911: # attempt to get lock on nohist_$namespace file
                   5912:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5913:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5914:         $tries ++;
                   5915:         sleep 1;
                   5916:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5917:     }
                   5918: 
                   5919: # attempt to get unique identifier, based on current timestamp
                   5920:     if ($gotlock eq 'ok') {
                   5921:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5922:         my $id = time;
                   5923:         $newid = $id;
                   5924:         my $idtries = 0;
                   5925:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5926:             if ($idtype eq 'concat') {
                   5927:                 $newid = $id.$idtries;
                   5928:             } else {
                   5929:                 $newid ++;
                   5930:             }
                   5931:             $idtries ++;
                   5932:         }
                   5933:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5934:             my %new_item =  (
                   5935:                               $prefix."\0".$newid => $who,
                   5936:                             );
                   5937:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5938:                                                  $cdom,$cnum);
                   5939:             if ($putresult ne 'ok') {
                   5940:                 undef($newid);
                   5941:                 $error = 'error saving new item: '.$putresult;
                   5942:             }
                   5943:         } else {
                   5944:              $error = ('error: no unique suffix available for the new item ');
                   5945:         }
                   5946: #  remove lock
                   5947:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5948:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5949:     } else {
                   5950:         $error = "error: could not obtain lockfile\n";
                   5951:         $dellock = 'ok';
                   5952:     }
                   5953:     return ($newid,$dellock,$error);
                   5954: }
                   5955: 
1.765     albertel 5956: # -------------------------------------------------- portfolio access checking
                   5957: 
                   5958: sub portfolio_access {
1.766     albertel 5959:     my ($requrl) = @_;
1.765     albertel 5960:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5961:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5962:     if ($result) {
                   5963:         my %setters;
                   5964:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5965:             my ($startblock,$endblock) =
                   5966:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5967:             if ($startblock && $endblock) {
                   5968:                 return 'B';
                   5969:             }
                   5970:         } else {
                   5971:             my ($startblock,$endblock) =
                   5972:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5973:             if ($startblock && $endblock) {
                   5974:                 return 'B';
                   5975:             }
                   5976:         }
                   5977:     }
1.765     albertel 5978:     if ($result eq 'ok') {
1.766     albertel 5979:        return 'F';
1.765     albertel 5980:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5981:        return 'A';
1.765     albertel 5982:     }
1.766     albertel 5983:     return '';
1.765     albertel 5984: }
                   5985: 
                   5986: sub get_portfolio_access {
1.767     albertel 5987:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5988: 
                   5989:     if (!ref($access_hash)) {
                   5990: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5991: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5992: 						   $file_name);
                   5993: 	$access_hash = $access_controls{$file_name};
                   5994:     }
                   5995: 
1.765     albertel 5996:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5997:     my $now = time;
                   5998:     if (ref($access_hash) eq 'HASH') {
                   5999:         foreach my $key (keys(%{$access_hash})) {
                   6000:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6001:             if ($start > $now) {
                   6002:                 next;
                   6003:             }
                   6004:             if ($end && $end<$now) {
                   6005:                 next;
                   6006:             }
                   6007:             if ($scope eq 'public') {
                   6008:                 $public = $key;
                   6009:                 last;
                   6010:             } elsif ($scope eq 'guest') {
                   6011:                 $guest = $key;
                   6012:             } elsif ($scope eq 'domains') {
                   6013:                 push(@domains,$key);
                   6014:             } elsif ($scope eq 'users') {
                   6015:                 push(@users,$key);
                   6016:             } elsif ($scope eq 'course') {
                   6017:                 push(@courses,$key);
                   6018:             } elsif ($scope eq 'group') {
                   6019:                 push(@groups,$key);
                   6020:             }
                   6021:         }
                   6022:         if ($public) {
                   6023:             return 'ok';
                   6024:         }
                   6025:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6026:             if ($guest) {
                   6027:                 return $guest;
                   6028:             }
                   6029:         } else {
                   6030:             if (@domains > 0) {
                   6031:                 foreach my $domkey (@domains) {
                   6032:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6033:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6034:                             return 'ok';
                   6035:                         }
                   6036:                     }
                   6037:                 }
                   6038:             }
                   6039:             if (@users > 0) {
                   6040:                 foreach my $userkey (@users) {
1.865     raeburn  6041:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6042:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6043:                             if (ref($item) eq 'HASH') {
                   6044:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6045:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6046:                                     return 'ok';
                   6047:                                 }
                   6048:                             }
                   6049:                         }
                   6050:                     } 
1.765     albertel 6051:                 }
                   6052:             }
                   6053:             my %roleshash;
                   6054:             my @courses_and_groups = @courses;
                   6055:             push(@courses_and_groups,@groups); 
                   6056:             if (@courses_and_groups > 0) {
                   6057:                 my (%allgroups,%allroles); 
                   6058:                 my ($start,$end,$role,$sec,$group);
                   6059:                 foreach my $envkey (%env) {
1.1060    raeburn  6060:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6061:                         my $cid = $2.'_'.$3; 
                   6062:                         if ($1 eq 'gr') {
                   6063:                             $group = $4;
                   6064:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6065:                         } else {
                   6066:                             if ($4 eq '') {
                   6067:                                 $sec = 'none';
                   6068:                             } else {
                   6069:                                 $sec = $4;
                   6070:                             }
                   6071:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6072:                         }
1.811     albertel 6073:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6074:                         my $cid = $2.'_'.$3;
                   6075:                         if ($4 eq '') {
                   6076:                             $sec = 'none';
                   6077:                         } else {
                   6078:                             $sec = $4;
                   6079:                         }
                   6080:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6081:                     }
                   6082:                 }
                   6083:                 if (keys(%allroles) == 0) {
                   6084:                     return;
                   6085:                 }
                   6086:                 foreach my $key (@courses_and_groups) {
                   6087:                     my %content = %{$$access_hash{$key}};
                   6088:                     my $cnum = $content{'number'};
                   6089:                     my $cdom = $content{'domain'};
                   6090:                     my $cid = $cdom.'_'.$cnum;
                   6091:                     if (!exists($allroles{$cid})) {
                   6092:                         next;
                   6093:                     }    
                   6094:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6095:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6096:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6097:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6098:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6099:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6100:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6101:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6102:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6103:                                         if (grep/^all$/,@sections) {
                   6104:                                             return 'ok';
                   6105:                                         } else {
                   6106:                                             if (grep/^$sec$/,@sections) {
                   6107:                                                 return 'ok';
                   6108:                                             }
                   6109:                                         }
                   6110:                                     }
                   6111:                                 }
                   6112:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6113:                                     if (grep/^none$/,@groups) {
                   6114:                                         return 'ok';
                   6115:                                     }
                   6116:                                 } else {
                   6117:                                     if (grep/^all$/,@groups) {
                   6118:                                         return 'ok';
                   6119:                                     } 
                   6120:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6121:                                         if (grep/^$group$/,@groups) {
                   6122:                                             return 'ok';
                   6123:                                         }
                   6124:                                     }
                   6125:                                 } 
                   6126:                             }
                   6127:                         }
                   6128:                     }
                   6129:                 }
                   6130:             }
                   6131:             if ($guest) {
                   6132:                 return $guest;
                   6133:             }
                   6134:         }
                   6135:     }
                   6136:     return;
                   6137: }
                   6138: 
                   6139: sub course_group_datechecker {
                   6140:     my ($dates,$now,$status) = @_;
                   6141:     my ($start,$end) = split(/\./,$dates);
                   6142:     if (!$start && !$end) {
                   6143:         return 'ok';
                   6144:     }
                   6145:     if (grep/^active$/,@{$status}) {
                   6146:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6147:             return 'ok';
                   6148:         }
                   6149:     }
                   6150:     if (grep/^previous$/,@{$status}) {
                   6151:         if ($end > $now ) {
                   6152:             return 'ok';
                   6153:         }
                   6154:     }
                   6155:     if (grep/^future$/,@{$status}) {
                   6156:         if ($start > $now) {
                   6157:             return 'ok';
                   6158:         }
                   6159:     }
                   6160:     return; 
                   6161: }
                   6162: 
                   6163: sub parse_portfolio_url {
                   6164:     my ($url) = @_;
                   6165: 
                   6166:     my ($type,$udom,$unum,$group,$file_name);
                   6167:     
1.823     albertel 6168:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6169: 	$type = 1;
                   6170:         $udom = $1;
                   6171:         $unum = $2;
                   6172:         $file_name = $3;
1.823     albertel 6173:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6174: 	$type = 2;
                   6175:         $udom = $1;
                   6176:         $unum = $2;
                   6177:         $group = $3;
                   6178:         $file_name = $3.'/'.$4;
                   6179:     }
                   6180:     if (wantarray) {
                   6181: 	return ($type,$udom,$unum,$file_name,$group);
                   6182:     }
                   6183:     return $type;
                   6184: }
                   6185: 
                   6186: sub is_portfolio_url {
                   6187:     my ($url) = @_;
                   6188:     return scalar(&parse_portfolio_url($url));
                   6189: }
                   6190: 
1.798     raeburn  6191: sub is_portfolio_file {
                   6192:     my ($file) = @_;
1.820     raeburn  6193:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6194:         return 1;
                   6195:     }
                   6196:     return;
                   6197: }
                   6198: 
1.976     raeburn  6199: sub usertools_access {
1.1084    raeburn  6200:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6201:     my ($access,%tools);
                   6202:     if ($context eq '') {
                   6203:         $context = 'tools';
                   6204:     }
                   6205:     if ($context eq 'requestcourses') {
                   6206:         %tools = (
                   6207:                       official   => 1,
                   6208:                       unofficial => 1,
1.1006    raeburn  6209:                       community  => 1,
1.985     raeburn  6210:                  );
1.1183    raeburn  6211:     } elsif ($context eq 'requestauthor') {
                   6212:         %tools = (
                   6213:                       requestauthor => 1,
                   6214:                  );
1.985     raeburn  6215:     } else {
                   6216:         %tools = (
                   6217:                       aboutme   => 1,
                   6218:                       blog      => 1,
1.1177    raeburn  6219:                       webdav    => 1,
1.985     raeburn  6220:                       portfolio => 1,
                   6221:                  );
                   6222:     }
1.976     raeburn  6223:     return if (!defined($tools{$tool}));
                   6224: 
1.1242    raeburn  6225:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6226:         $udom = $env{'user.domain'};
                   6227:         $uname = $env{'user.name'};
                   6228:     }
                   6229: 
1.978     raeburn  6230:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6231:         if ($action ne 'reload') {
1.985     raeburn  6232:             if ($context eq 'requestcourses') {
                   6233:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6234:             } elsif ($context eq 'requestauthor') {
                   6235:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6236:             } else {
                   6237:                 return $env{'environment.availabletools.'.$tool};
                   6238:             }
                   6239:         }
1.976     raeburn  6240:     }
                   6241: 
1.1183    raeburn  6242:     my ($toolstatus,$inststatus,$envkey);
                   6243:     if ($context eq 'requestauthor') {
                   6244:         $envkey = $context; 
                   6245:     } else {
                   6246:         $envkey = $context.'.'.$tool;
                   6247:     }
1.976     raeburn  6248: 
1.985     raeburn  6249:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6250:          ($action ne 'reload')) {
1.1183    raeburn  6251:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6252:         $inststatus = $env{'environment.inststatus'};
                   6253:     } else {
1.1084    raeburn  6254:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6255:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6256:             $inststatus = $userenvref->{'inststatus'};
                   6257:         } else {
1.1183    raeburn  6258:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6259:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6260:             $inststatus = $userenv{'inststatus'};
                   6261:         }
1.976     raeburn  6262:     }
                   6263: 
                   6264:     if ($toolstatus ne '') {
                   6265:         if ($toolstatus) {
                   6266:             $access = 1;
                   6267:         } else {
                   6268:             $access = 0;
                   6269:         }
                   6270:         return $access;
                   6271:     }
                   6272: 
1.1084    raeburn  6273:     my ($is_adv,%domdef);
                   6274:     if (ref($is_advref) eq 'HASH') {
                   6275:         $is_adv = $is_advref->{'is_adv'};
                   6276:     } else {
                   6277:         $is_adv = &is_advanced_user($udom,$uname);
                   6278:     }
                   6279:     if (ref($domdefref) eq 'HASH') {
                   6280:         %domdef = %{$domdefref};
                   6281:     } else {
                   6282:         %domdef = &get_domain_defaults($udom);
                   6283:     }
1.976     raeburn  6284:     if (ref($domdef{$tool}) eq 'HASH') {
                   6285:         if ($is_adv) {
                   6286:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6287:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6288:                     $access = 1;
                   6289:                 } else {
                   6290:                     $access = 0;
                   6291:                 }
                   6292:                 return $access;
                   6293:             }
                   6294:         }
                   6295:         if ($inststatus ne '') {
                   6296:             my ($hasaccess,$hasnoaccess);
                   6297:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6298:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6299:                     if ($domdef{$tool}{$affiliation}) {
                   6300:                         $hasaccess = 1;
                   6301:                     } else {
                   6302:                         $hasnoaccess = 1;
                   6303:                     }
                   6304:                 }
                   6305:             }
                   6306:             if ($hasaccess || $hasnoaccess) {
                   6307:                 if ($hasaccess) {
                   6308:                     $access = 1;
                   6309:                 } elsif ($hasnoaccess) {
                   6310:                     $access = 0; 
                   6311:                 }
                   6312:                 return $access;
                   6313:             }
                   6314:         } else {
                   6315:             if ($domdef{$tool}{'default'} ne '') {
                   6316:                 if ($domdef{$tool}{'default'}) {
                   6317:                     $access = 1;
                   6318:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6319:                     $access = 0;
                   6320:                 }
                   6321:                 return $access;
                   6322:             }
                   6323:         }
                   6324:     } else {
1.1177    raeburn  6325:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6326:             $access = 1;
                   6327:         } else {
                   6328:             $access = 0;
                   6329:         }
1.976     raeburn  6330:         return $access;
                   6331:     }
                   6332: }
                   6333: 
1.1050    raeburn  6334: sub is_course_owner {
                   6335:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6336:     if (($udom eq '') || ($uname eq '')) {
                   6337:         $udom = $env{'user.domain'};
                   6338:         $uname = $env{'user.name'};
                   6339:     }
                   6340:     unless (($udom eq '') || ($uname eq '')) {
                   6341:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6342:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6343:                 return 1;
                   6344:             } else {
                   6345:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6346:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6347:                     return 1;
                   6348:                 }
                   6349:             }
                   6350:         }
                   6351:     }
                   6352:     return;
                   6353: }
                   6354: 
1.976     raeburn  6355: sub is_advanced_user {
                   6356:     my ($udom,$uname) = @_;
1.1085    raeburn  6357:     if ($udom ne '' && $uname ne '') {
                   6358:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6359:             if (wantarray) {
                   6360:                 return ($env{'user.adv'},$env{'user.author'});
                   6361:             } else {
                   6362:                 return $env{'user.adv'};
                   6363:             }
1.1085    raeburn  6364:         }
                   6365:     }
1.976     raeburn  6366:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6367:     my %allroles;
1.1128    raeburn  6368:     my ($is_adv,$is_author);
1.976     raeburn  6369:     foreach my $role (keys(%roleshash)) {
                   6370:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6371:         my $area = '/'.$tdomain.'/'.$trest;
                   6372:         if ($sec ne '') {
                   6373:             $area .= '/'.$sec;
                   6374:         }
                   6375:         if (($area ne '') && ($trole ne '')) {
                   6376:             my $spec=$trole.'.'.$area;
                   6377:             if ($trole =~ /^cr\//) {
                   6378:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6379:             } elsif ($trole ne 'gr') {
                   6380:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6381:             }
1.1128    raeburn  6382:             if ($trole eq 'au') {
                   6383:                 $is_author = 1;
                   6384:             }
1.976     raeburn  6385:         }
                   6386:     }
                   6387:     foreach my $role (keys(%allroles)) {
                   6388:         last if ($is_adv);
                   6389:         foreach my $item (split(/:/,$allroles{$role})) {
                   6390:             if ($item ne '') {
                   6391:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6392:                 if ($privilege eq 'adv') {
                   6393:                     $is_adv = 1;
                   6394:                     last;
                   6395:                 }
                   6396:             }
                   6397:         }
                   6398:     }
1.1128    raeburn  6399:     if (wantarray) {
                   6400:         return ($is_adv,$is_author);
                   6401:     }
1.976     raeburn  6402:     return $is_adv;
                   6403: }
1.798     raeburn  6404: 
1.1035    raeburn  6405: sub check_can_request {
1.1036    raeburn  6406:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6407:     my $canreq = 0;
                   6408:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6409:     my @options = ('approval','validate','autolimit');
                   6410:     my $optregex = join('|',@options);
                   6411:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6412:         foreach my $type (@{$types}) {
                   6413:             if (&usertools_access($env{'user.name'},
                   6414:                                   $env{'user.domain'},
                   6415:                                   $type,undef,'requestcourses')) {
                   6416:                 $canreq ++;
1.1036    raeburn  6417:                 if (ref($request_domains) eq 'HASH') {
                   6418:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6419:                 }
1.1035    raeburn  6420:                 if ($dom eq $env{'user.domain'}) {
                   6421:                     $can_request->{$type} = 1;
                   6422:                 }
                   6423:             }
                   6424:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6425:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6426:                 if (@curr > 0) {
1.1036    raeburn  6427:                     foreach my $item (@curr) {
                   6428:                         if (ref($request_domains) eq 'HASH') {
                   6429:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6430:                             if ($otherdom ne '') {
                   6431:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6432:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6433:                                         push(@{$request_domains->{$type}},$otherdom);
                   6434:                                     }
                   6435:                                 } else {
                   6436:                                     push(@{$request_domains->{$type}},$otherdom);
                   6437:                                 }
                   6438:                             }
                   6439:                         }
                   6440:                     }
                   6441:                     unless($dom eq $env{'user.domain'}) {
                   6442:                         $canreq ++;
1.1035    raeburn  6443:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6444:                             $can_request->{$type} = 1;
                   6445:                         }
                   6446:                     }
                   6447:                 }
                   6448:             }
                   6449:         }
                   6450:     }
                   6451:     return $canreq;
                   6452: }
                   6453: 
1.341     www      6454: # ---------------------------------------------- Custom access rule evaluation
                   6455: 
                   6456: sub customaccess {
                   6457:     my ($priv,$uri)=@_;
1.807     albertel 6458:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6459:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6460:     $udom = &LONCAPA::clean_domain($udom);
                   6461:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6462:     my $access=0;
1.800     albertel 6463:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6464: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6465: 	if ($type eq 'user') {
                   6466: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6467: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6468: 		if ($tdom) {
                   6469: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6470: 		}
1.896     albertel 6471: 		if ($tuname) {
                   6472: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6473: 		}
                   6474: 		$access=($effect eq 'allow');
                   6475: 		last;
                   6476: 	    }
                   6477: 	} else {
                   6478: 	    if ($role) {
                   6479: 		if ($role ne $urole) { next; }
                   6480: 	    }
                   6481: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6482: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6483: 		if ($tdom) {
                   6484: 		    if ($tdom ne $udom) { next; }
                   6485: 		}
                   6486: 		if ($tcrs) {
                   6487: 		    if ($tcrs ne $ucrs) { next; }
                   6488: 		}
                   6489: 		if ($tsec) {
                   6490: 		    if ($tsec ne $usec) { next; }
                   6491: 		}
                   6492: 		$access=($effect eq 'allow');
                   6493: 		last;
                   6494: 	    }
                   6495: 	    if ($realm eq '' && $role eq '') {
                   6496: 		$access=($effect eq 'allow');
                   6497: 	    }
1.402     bowersj2 6498: 	}
1.341     www      6499:     }
                   6500:     return $access;
                   6501: }
                   6502: 
1.103     harris41 6503: # ------------------------------------------------- Check for a user privilege
1.12      www      6504: 
                   6505: sub allowed {
1.810     raeburn  6506:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6507:     my $ver_orguri=$uri;
1.439     www      6508:     $uri=&deversion($uri);
1.152     www      6509:     my $orguri=$uri;
1.52      www      6510:     $uri=&declutter($uri);
1.809     raeburn  6511: 
1.810     raeburn  6512:     if ($priv eq 'evb') {
                   6513: # Evade communication block restrictions for specified role in a course
                   6514:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6515:             return $1;
                   6516:         } else {
                   6517:             return;
                   6518:         }
                   6519:     }
                   6520: 
1.620     albertel 6521:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6522: # Free bre access to adm and meta resources
1.775     albertel 6523:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6524: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6525: 	&& ($priv eq 'bre')) {
1.14      www      6526: 	return 'F';
1.159     www      6527:     }
                   6528: 
1.545     banghart 6529: # Free bre access to user's own portfolio contents
1.714     raeburn  6530:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6531:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6532: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6533:         my %setters;
                   6534:         my ($startblock,$endblock) = 
                   6535:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6536:         if ($startblock && $endblock) {
                   6537:             return 'B';
                   6538:         } else {
                   6539:             return 'F';
                   6540:         }
1.545     banghart 6541:     }
                   6542: 
1.762     raeburn  6543: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6544:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6545:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6546:         if (exists($env{'request.course.id'})) {
                   6547:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6548:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6549:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6550:                 my $courseprivid=$env{'request.course.id'};
                   6551:                 $courseprivid=~s/\_/\//;
                   6552:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6553:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6554:                     return $1; 
1.762     raeburn  6555:                 } else {
                   6556:                     if ($env{'request.course.sec'}) {
                   6557:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6558:                     }
                   6559:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6560:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6561:                         return $2;
                   6562:                     }
1.714     raeburn  6563:                 }
                   6564:             }
                   6565:         }
                   6566:     }
                   6567: 
1.159     www      6568: # Free bre to public access
                   6569: 
                   6570:     if ($priv eq 'bre') {
1.238     www      6571:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6572: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6573:            return 'F'; 
                   6574:         }
1.238     www      6575:         if ($copyright eq 'priv') {
                   6576:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6577: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6578: 		return '';
                   6579:             }
                   6580:         }
                   6581:         if ($copyright eq 'domain') {
                   6582:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6583: 	    unless (($env{'user.domain'} eq $1) ||
                   6584:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6585: 		return '';
                   6586:             }
1.262     matthew  6587:         }
1.620     albertel 6588:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6589:             # Library role, so allow browsing of resources in this domain.
                   6590:             return 'F';
1.238     www      6591:         }
1.341     www      6592:         if ($copyright eq 'custom') {
                   6593: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6594:         }
1.14      www      6595:     }
1.264     matthew  6596:     # Domain coordinator is trying to create a course
1.620     albertel 6597:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6598:         # uri is the requested domain in this case.
                   6599:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6600:         # a role of dc for the domain in question.
1.620     albertel 6601:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6602:     }
1.29      www      6603: 
1.52      www      6604:     my $thisallowed='';
                   6605:     my $statecond=0;
                   6606:     my $courseprivid='';
                   6607: 
1.1039    raeburn  6608:     my $ownaccess;
1.1043    raeburn  6609:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6610:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6611:         if ($uri eq '') {
                   6612:             $ownaccess = 1;
                   6613:         } else {
                   6614:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6615:                 my $udom = $env{'user.domain'};
                   6616:                 my $uname = $env{'user.name'};
                   6617:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6618:                     $ownaccess = 1;
1.1040    raeburn  6619:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6620:                     unless ($uri =~ m{\.\./}) {
                   6621:                         $ownaccess = 1;
                   6622:                     }
                   6623:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6624:                     my $now = time;
                   6625:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6626:                         my $adom = $1;
                   6627:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6628:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6629:                                 my ($start,$end) = split('.',$env{$key});
                   6630:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6631:                                     $ownaccess = 1;
                   6632:                                     last;
                   6633:                                 }
                   6634:                             }
                   6635:                         }
                   6636:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6637:                         my $adom = $1;
                   6638:                         my $aname = $2;
1.1042    raeburn  6639:                         foreach my $role ('ca','aa') { 
                   6640:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6641:                                 my ($start,$end) =
                   6642:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6643:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6644:                                     $ownaccess = 1;
                   6645:                                     last;
                   6646:                                 }
1.1039    raeburn  6647:                             }
                   6648:                         }
                   6649:                     }
                   6650:                 }
                   6651:             }
                   6652:         }
                   6653:     }
                   6654: 
1.52      www      6655: # Course
                   6656: 
1.620     albertel 6657:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6658:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6659:             $thisallowed.=$1;
                   6660:         }
1.52      www      6661:     }
1.29      www      6662: 
1.52      www      6663: # Domain
                   6664: 
1.620     albertel 6665:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6666:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6667:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6668:             $thisallowed.=$1;
                   6669:         }
1.12      www      6670:     }
1.52      www      6671: 
1.1141    raeburn  6672: # User who is not author or co-author might still be able to edit
                   6673: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6674:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6675:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6676:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6677:             $thisallowed.=$1;
                   6678:         }
                   6679:     }
                   6680: 
1.52      www      6681: # Course: uri itself is a course
1.66      www      6682:     my $courseuri=$uri;
                   6683:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6684:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6685: 
1.620     albertel 6686:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6687:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6688:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6689:             $thisallowed.=$1;
                   6690:         }
1.12      www      6691:     }
1.29      www      6692: 
1.665     albertel 6693: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6694: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6695:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6696: 	$thisallowed='';
1.671     raeburn  6697:         my ($match)=&is_on_map($uri);
                   6698:         if ($match) {
                   6699:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6700:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6701:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6702:                 if (@blockers > 0) {
                   6703:                     $thisallowed = 'B';
                   6704:                 } else {
                   6705:                     $thisallowed.=$1;
                   6706:                 }
1.671     raeburn  6707:             }
                   6708:         } else {
1.705     albertel 6709:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6710:             if ($refuri) {
                   6711:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6712:                     $thisallowed='F';
1.671     raeburn  6713:                 } else {
                   6714:                     $refuri=&declutter($refuri);
                   6715:                     my ($match) = &is_on_map($refuri);
                   6716:                     if ($match) {
1.1162    raeburn  6717:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6718:                         if (@blockers > 0) {
                   6719:                             $thisallowed = 'B';
                   6720:                         } else {
                   6721:                             $thisallowed='F';
                   6722:                         }
1.671     raeburn  6723:                     }
1.669     raeburn  6724:                 }
1.671     raeburn  6725:             }
                   6726:         }
1.314     www      6727:     }
1.492     albertel 6728: 
1.766     albertel 6729:     if ($priv eq 'bre'
                   6730: 	&& $thisallowed ne 'F' 
                   6731: 	&& $thisallowed ne '2'
                   6732: 	&& &is_portfolio_url($uri)) {
                   6733: 	$thisallowed = &portfolio_access($uri);
                   6734:     }
                   6735:     
1.52      www      6736: # Full access at system, domain or course-wide level? Exit.
1.29      www      6737:     if ($thisallowed=~/F/) {
                   6738: 	return 'F';
                   6739:     }
                   6740: 
1.52      www      6741: # If this is generating or modifying users, exit with special codes
1.29      www      6742: 
1.643     www      6743:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6744: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6745: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6746: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6747: 	    unless ($auname) { return $thisallowed; }
                   6748: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6749: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6750: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6751: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6752: 	}
1.52      www      6753: 	return $thisallowed;
                   6754:     }
                   6755: #
1.103     harris41 6756: # Gathered so far: system, domain and course wide privileges
1.52      www      6757: #
                   6758: # Course: See if uri or referer is an individual resource that is part of 
                   6759: # the course
                   6760: 
1.620     albertel 6761:     if ($env{'request.course.id'}) {
1.232     www      6762: 
1.620     albertel 6763:        $courseprivid=$env{'request.course.id'};
                   6764:        if ($env{'request.course.sec'}) {
                   6765:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6766:        }
                   6767:        $courseprivid=~s/\_/\//;
                   6768:        my $checkreferer=1;
1.232     www      6769:        my ($match,$cond)=&is_on_map($uri);
                   6770:        if ($match) {
                   6771:            $statecond=$cond;
1.620     albertel 6772:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6773:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6774:                my $value = $1;
                   6775:                if ($priv eq 'bre') {
                   6776:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6777:                    if (@blockers > 0) {
                   6778:                        $thisallowed = 'B';
                   6779:                    } else {
                   6780:                        $thisallowed.=$value;
                   6781:                    }
                   6782:                } else {
                   6783:                    $thisallowed.=$value;
                   6784:                }
1.52      www      6785:                $checkreferer=0;
                   6786:            }
1.29      www      6787:        }
1.83      www      6788:        
1.148     www      6789:        if ($checkreferer) {
1.620     albertel 6790: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6791:             unless ($refuri) {
1.800     albertel 6792:                 foreach my $key (keys(%env)) {
                   6793: 		    if ($key=~/^httpref\..*\*/) {
                   6794: 			my $pattern=$key;
1.156     www      6795:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6796:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6797:                         $pattern=~s/\//\\\//g;
1.152     www      6798:                         if ($orguri=~/$pattern/) {
1.800     albertel 6799: 			    $refuri=$env{$key};
1.148     www      6800:                         }
                   6801:                     }
1.191     harris41 6802:                 }
1.148     www      6803:             }
1.232     www      6804: 
1.148     www      6805:          if ($refuri) { 
1.152     www      6806: 	  $refuri=&declutter($refuri);
1.232     www      6807:           my ($match,$cond)=&is_on_map($refuri);
                   6808:             if ($match) {
                   6809:               my $refstatecond=$cond;
1.620     albertel 6810:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6811:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6812:                   my $value = $1;
                   6813:                   if ($priv eq 'bre') {
                   6814:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6815:                       if (@blockers > 0) {
                   6816:                           $thisallowed = 'B';
                   6817:                       } else {
                   6818:                           $thisallowed.=$value;
                   6819:                       }
                   6820:                   } else {
                   6821:                       $thisallowed.=$value;
                   6822:                   }
1.53      www      6823:                   $uri=$refuri;
                   6824:                   $statecond=$refstatecond;
1.52      www      6825:               }
                   6826:           }
1.148     www      6827:         }
1.29      www      6828:        }
1.52      www      6829:    }
1.29      www      6830: 
1.52      www      6831: #
1.103     harris41 6832: # Gathered now: all privileges that could apply, and condition number
1.52      www      6833: # 
                   6834: #
                   6835: # Full or no access?
                   6836: #
1.29      www      6837: 
1.52      www      6838:     if ($thisallowed=~/F/) {
                   6839: 	return 'F';
                   6840:     }
1.29      www      6841: 
1.52      www      6842:     unless ($thisallowed) {
                   6843:         return '';
                   6844:     }
1.29      www      6845: 
1.52      www      6846: # Restrictions exist, deal with them
                   6847: #
                   6848: #   C:according to course preferences
                   6849: #   R:according to resource settings
                   6850: #   L:unless locked
                   6851: #   X:according to user session state
                   6852: #
                   6853: 
                   6854: # Possibly locked functionality, check all courses
1.54      www      6855: # Locks might take effect only after 10 minutes cache expiration for other
                   6856: # courses, and 2 minutes for current course
1.52      www      6857: 
                   6858:     my $envkey;
                   6859:     if ($thisallowed=~/L/) {
1.1000    raeburn  6860:         foreach $envkey (keys(%env)) {
1.54      www      6861:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6862:                my $courseid=$2;
                   6863:                my $roleid=$1.'.'.$2;
1.92      www      6864:                $courseid=~s/^\///;
1.54      www      6865:                my $expiretime=600;
1.620     albertel 6866:                if ($env{'request.role'} eq $roleid) {
1.54      www      6867: 		  $expiretime=120;
                   6868:                }
                   6869: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6870:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6871:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6872: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6873:                }
1.620     albertel 6874:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6875:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6876: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6877:                        &log($env{'user.domain'},$env{'user.name'},
                   6878:                             $env{'user.home'},
1.57      www      6879:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6880:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6881:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6882: 		       return '';
                   6883:                    }
                   6884:                }
1.620     albertel 6885:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6886:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6887: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6888:                        &log($env{'user.domain'},$env{'user.name'},
                   6889:                             $env{'user.home'},
1.57      www      6890:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6891:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6892:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6893: 		       return '';
                   6894:                    }
                   6895:                }
                   6896: 	   }
1.29      www      6897:        }
1.52      www      6898:     }
                   6899:    
                   6900: #
                   6901: # Rest of the restrictions depend on selected course
                   6902: #
                   6903: 
1.620     albertel 6904:     unless ($env{'request.course.id'}) {
1.766     albertel 6905: 	if ($thisallowed eq 'A') {
                   6906: 	    return 'A';
1.814     raeburn  6907:         } elsif ($thisallowed eq 'B') {
                   6908:             return 'B';
1.766     albertel 6909: 	} else {
                   6910: 	    return '1';
                   6911: 	}
1.52      www      6912:     }
1.29      www      6913: 
1.52      www      6914: #
                   6915: # Now user is definitely in a course
                   6916: #
1.53      www      6917: 
                   6918: 
                   6919: # Course preferences
                   6920: 
                   6921:    if ($thisallowed=~/C/) {
1.620     albertel 6922:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6923:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6924:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6925: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6926: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6927: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6928: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6929: 			$env{'request.course.id'});
                   6930: 	   }
1.237     www      6931:            return '';
                   6932:        }
                   6933: 
1.620     albertel 6934:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6935: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6936: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6937: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6938: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6939: 			$env{'request.course.id'});
                   6940: 	   }
1.54      www      6941:            return '';
                   6942:        }
1.53      www      6943:    }
                   6944: 
                   6945: # Resource preferences
                   6946: 
                   6947:    if ($thisallowed=~/R/) {
1.620     albertel 6948:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6949:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6950: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6951: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6952: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6953: 	   }
                   6954: 	   return '';
1.54      www      6955:        }
1.53      www      6956:    }
1.30      www      6957: 
1.246     www      6958: # Restricted by state or randomout?
1.30      www      6959: 
1.52      www      6960:    if ($thisallowed=~/X/) {
1.620     albertel 6961:       if ($env{'acc.randomout'}) {
1.579     albertel 6962: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6963:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6964:             return ''; 
                   6965:          }
1.247     www      6966:       }
                   6967:       if (&condval($statecond)) {
1.52      www      6968: 	 return '2';
                   6969:       } else {
                   6970:          return '';
                   6971:       }
                   6972:    }
1.30      www      6973: 
1.766     albertel 6974:     if ($thisallowed eq 'A') {
                   6975: 	return 'A';
1.814     raeburn  6976:     } elsif ($thisallowed eq 'B') {
                   6977:         return 'B';
1.766     albertel 6978:     }
1.52      www      6979:    return 'F';
1.232     www      6980: }
1.1162    raeburn  6981: 
1.1192    raeburn  6982: # ------------------------------------------- Check construction space access
                   6983: 
                   6984: sub constructaccess {
                   6985:     my ($url,$setpriv)=@_;
                   6986: 
                   6987: # We do not allow editing of previous versions of files
                   6988:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6989: 
                   6990: # Get username and domain from URL
                   6991:     my ($ownername,$ownerdomain,$ownerhome);
                   6992: 
                   6993:     ($ownerdomain,$ownername) =
                   6994:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6995: 
                   6996: # The URL does not really point to any authorspace, forget it
                   6997:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6998: 
                   6999: # Now we need to see if the user has access to the authorspace of
                   7000: # $ownername at $ownerdomain
                   7001: 
                   7002:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7003: # Real author for this?
                   7004:        $ownerhome = $env{'user.home'};
                   7005:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7006:           return ($ownername,$ownerdomain,$ownerhome);
                   7007:        }
                   7008:     } else {
                   7009: # Co-author for this?
                   7010:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7011:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7012:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7013:             return ($ownername,$ownerdomain,$ownerhome);
                   7014:         }
                   7015:     }
                   7016: 
                   7017: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7018: # we might as well leave
                   7019:    unless ($setpriv) { return ''; }
                   7020: 
                   7021: # Backdoor access?
                   7022:     my $allowed=&allowed('eco',$ownerdomain);
                   7023: # Nope
                   7024:     unless ($allowed) { return ''; }
                   7025: # Looks like we may have access, but could be locked by the owner of the construction space
                   7026:     if ($allowed eq 'U') {
                   7027:         my %blocked=&get('environment',['domcoord.author'],
                   7028:                          $ownerdomain,$ownername);
                   7029: # Is blocked by owner
                   7030:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7031:     }
                   7032:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7033: # Grant temporary access
                   7034:         my $then=$env{'user.login.time'};
1.1209    raeburn  7035:         my $update=$env{'user.update.time'};
1.1192    raeburn  7036:         if (!$update) { $update = $then; }
                   7037:         my $refresh=$env{'user.refresh.time'};
                   7038:         if (!$refresh) { $refresh = $update; }
                   7039:         my $now = time;
                   7040:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7041:                            $now,'ca','constructaccess');
                   7042:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7043:         return($ownername,$ownerdomain,$ownerhome);
                   7044:     }
                   7045: # No business here
                   7046:     return '';
                   7047: }
                   7048: 
1.1162    raeburn  7049: sub get_comm_blocks {
                   7050:     my ($cdom,$cnum) = @_;
                   7051:     if ($cdom eq '' || $cnum eq '') {
                   7052:         return unless ($env{'request.course.id'});
                   7053:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7054:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7055:     }
                   7056:     my %commblocks;
                   7057:     my $hashid=$cdom.'_'.$cnum;
                   7058:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7059:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7060:         %commblocks = %{$blocksref};
                   7061:     } else {
                   7062:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7063:         my $cachetime = 600;
                   7064:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7065:     }
                   7066:     return %commblocks;
                   7067: }
                   7068: 
                   7069: sub has_comm_blocking {
                   7070:     my ($priv,$symb,$uri,$blocks) = @_;
                   7071:     return unless ($env{'request.course.id'});
                   7072:     return unless ($priv eq 'bre');
                   7073:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7074:     my %commblocks;
                   7075:     if (ref($blocks) eq 'HASH') {
                   7076:         %commblocks = %{$blocks};
                   7077:     } else {
                   7078:         %commblocks = &get_comm_blocks();
                   7079:     }
                   7080:     return unless (keys(%commblocks) > 0);
                   7081:     if (!$symb) { $symb=&symbread($uri,1); }
                   7082:     my ($map,$resid,undef)=&decode_symb($symb);
                   7083:     my %tocheck = (
                   7084:                     maps      => $map,
                   7085:                     resources => $symb,
                   7086:                   );
                   7087:     my @blockers;
                   7088:     my $now = time;
1.1163    raeburn  7089:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7090:     foreach my $block (keys(%commblocks)) {
                   7091:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7092:             my ($start,$end) = ($1,$2);
                   7093:             if ($start <= $now && $end >= $now) {
                   7094:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7095:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7096:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7097:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7098:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7099:                                     push(@blockers,$block);
                   7100:                                 }
                   7101:                             }
                   7102:                         }
                   7103:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7104:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7105:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7106:                                     push(@blockers,$block);
                   7107:                                 }
                   7108:                             }
                   7109:                         }
                   7110:                     }
                   7111:                 }
                   7112:             }
                   7113:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7114:             my $item = $1;
1.1163    raeburn  7115:             my @to_test;
1.1162    raeburn  7116:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7117:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7118:                     my $check_interval;
                   7119:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7120:                         my @interval;
                   7121:                         my $type = 'map';
                   7122:                         if ($item eq 'course') {
                   7123:                             $type = 'course';
                   7124:                             @interval=&EXT("resource.0.interval");
                   7125:                         } else {
                   7126:                             if ($item =~ /___\d+___/) {
                   7127:                                 $type = 'resource';
                   7128:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7129:                                 if (ref($navmap)) {                        
                   7130:                                     my $res = $navmap->getBySymb($item); 
                   7131:                                     push(@to_test,$res);
                   7132:                                 }
1.1162    raeburn  7133:                             } else {
                   7134:                                 my $mapsymb = &symbread($item,1);
                   7135:                                 if ($mapsymb) {
                   7136:                                     if (ref($navmap)) {
                   7137:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7138:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7139:                                         foreach my $res (@to_test) {
1.1162    raeburn  7140:                                             my $symb = $res->symb();
                   7141:                                             next if ($symb eq $mapsymb);
                   7142:                                             if ($symb ne '') {
                   7143:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7144:                                                 last;
                   7145:                                             }
                   7146:                                         }
                   7147:                                     }
                   7148:                                 }
                   7149:                             }
                   7150:                         }
                   7151:                         if ($interval[0] =~ /\d+/) {
                   7152:                             my $first_access;
                   7153:                             if ($type eq 'resource') {
                   7154:                                 $first_access=&get_first_access($interval[1],$item);
                   7155:                             } elsif ($type eq 'map') {
                   7156:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7157:                             } else {
                   7158:                                 $first_access=&get_first_access($interval[1]);
                   7159:                             }
                   7160:                             if ($first_access) {
                   7161:                                 my $timesup = $first_access+$interval[0];
                   7162:                                 if ($timesup > $now) {
1.1163    raeburn  7163:                                     foreach my $res (@to_test) {
                   7164:                                         if ($res->is_problem()) {
                   7165:                                             if ($res->completable()) {
                   7166:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7167:                                                     push(@blockers,$block);
                   7168:                                                 }
                   7169:                                                 last;
                   7170:                                             }
                   7171:                                         }
1.1162    raeburn  7172:                                     }
                   7173:                                 }
                   7174:                             }
                   7175:                         }
                   7176:                     }
                   7177:                 }
                   7178:             }
                   7179:         }
                   7180:     }
                   7181:     return @blockers;
                   7182: }
                   7183: 
                   7184: sub check_docs_block {
                   7185:     my ($docsblock,$tocheck) =@_;
                   7186:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7187:         return;
                   7188:     }
                   7189:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7190:         if ($tocheck->{'maps'}) {
                   7191:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7192:                 return 1;
                   7193:             }
                   7194:         }
                   7195:     }
                   7196:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7197:         if ($tocheck->{'resources'}) {
                   7198:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7199:                 return 1;
                   7200:             }
                   7201:         }
                   7202:     }
                   7203:     return;
                   7204: }
                   7205: 
1.1133    foxr     7206: #
                   7207: #   Removes the versino from a URI and
                   7208: #   splits it in to its filename and path to the filename.
                   7209: #   Seems like File::Basename could have done this more clearly.
                   7210: #   Parameters:
                   7211: #      $uri   - input URI
                   7212: #   Returns:
                   7213: #     Two element list consisting of 
                   7214: #     $pathname  - the URI up to and excluding the trailing /
                   7215: #     $filename  - The part of the URI following the last /
                   7216: #  NOTE:
                   7217: #    Another realization of this is simply:
                   7218: #    use File::Basename;
                   7219: #    ...
                   7220: #    $uri = shift;
                   7221: #    $filename = basename($uri);
                   7222: #    $path     = dirname($uri);
                   7223: #    return ($filename, $path);
                   7224: #
                   7225: #     The implementation below is probably faster however.
                   7226: #
1.710     albertel 7227: sub split_uri_for_cond {
                   7228:     my $uri=&deversion(&declutter(shift));
                   7229:     my @uriparts=split(/\//,$uri);
                   7230:     my $filename=pop(@uriparts);
                   7231:     my $pathname=join('/',@uriparts);
                   7232:     return ($pathname,$filename);
                   7233: }
1.232     www      7234: # --------------------------------------------------- Is a resource on the map?
                   7235: 
                   7236: sub is_on_map {
1.710     albertel 7237:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7238:     #Trying to find the conditional for the file
1.620     albertel 7239:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7240: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7241:     if ($match) {
1.289     bowersj2 7242: 	return (1,$1);
                   7243:     } else {
1.434     www      7244: 	return (0,0);
1.289     bowersj2 7245:     }
1.12      www      7246: }
                   7247: 
1.427     www      7248: # --------------------------------------------------------- Get symb from alias
                   7249: 
                   7250: sub get_symb_from_alias {
                   7251:     my $symb=shift;
                   7252:     my ($map,$resid,$url)=&decode_symb($symb);
                   7253: # Already is a symb
                   7254:     if ($url) { return $symb; }
                   7255: # Must be an alias
                   7256:     my $aliassymb='';
                   7257:     my %bighash;
1.620     albertel 7258:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7259:                             &GDBM_READER(),0640)) {
                   7260:         my $rid=$bighash{'mapalias_'.$symb};
                   7261: 	if ($rid) {
                   7262: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7263: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7264: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7265: 	}
                   7266:         untie %bighash;
                   7267:     }
                   7268:     return $aliassymb;
                   7269: }
                   7270: 
1.12      www      7271: # ----------------------------------------------------------------- Define Role
                   7272: 
                   7273: sub definerole {
                   7274:   if (allowed('mcr','/')) {
                   7275:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7276:     foreach my $role (split(':',$sysrole)) {
                   7277: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7278:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7279:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7280: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7281:                return "refused:s:$crole&$cqual"; 
                   7282:             }
                   7283:         }
1.191     harris41 7284:     }
1.800     albertel 7285:     foreach my $role (split(':',$domrole)) {
                   7286: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7287:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7288:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7289: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7290:                return "refused:d:$crole&$cqual"; 
                   7291:             }
                   7292:         }
1.191     harris41 7293:     }
1.800     albertel 7294:     foreach my $role (split(':',$courole)) {
                   7295: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7296:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7297:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7298: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7299:                return "refused:c:$crole&$cqual"; 
                   7300:             }
                   7301:         }
1.191     harris41 7302:     }
1.620     albertel 7303:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7304:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7305: 	        "rolesdef_$rolename=".
                   7306:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7307:     return reply($command,$env{'user.home'});
1.12      www      7308:   } else {
                   7309:     return 'refused';
                   7310:   }
1.105     harris41 7311: }
                   7312: 
                   7313: # ---------------- Make a metadata query against the network of library servers
                   7314: 
                   7315: sub metadata_query {
1.1237    raeburn  7316:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7317:     my %rhash;
1.845     albertel 7318:     my %libserv = &all_library();
1.244     matthew  7319:     my @server_list = (defined($server_array) ? @$server_array
                   7320:                                               : keys(%libserv) );
                   7321:     for my $server (@server_list) {
1.1237    raeburn  7322:         my $domains = ''; 
                   7323:         if (ref($domains_hash) eq 'HASH') {
                   7324:             $domains = $domains_hash->{$server}; 
                   7325:         }
1.118     harris41 7326: 	unless ($custom or $customshow) {
1.1237    raeburn  7327: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7328: 	    $rhash{$server}=$reply;
                   7329: 	}
                   7330: 	else {
                   7331: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7332: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7333: 			     $server);
                   7334: 	    $rhash{$server}=$reply;
                   7335: 	}
1.112     harris41 7336:     }
1.118     harris41 7337:     return \%rhash;
1.240     www      7338: }
                   7339: 
                   7340: # ----------------------------------------- Send log queries and wait for reply
                   7341: 
                   7342: sub log_query {
                   7343:     my ($uname,$udom,$query,%filters)=@_;
                   7344:     my $uhome=&homeserver($uname,$udom);
                   7345:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7346:     my $uhost=&hostname($uhome);
1.800     albertel 7347:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7348:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7349:                        $uhome);
1.479     albertel 7350:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7351:     return get_query_reply($queryid);
                   7352: }
                   7353: 
1.818     raeburn  7354: # -------------------------- Update MySQL table for portfolio file
                   7355: 
                   7356: sub update_portfolio_table {
1.821     raeburn  7357:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7358:     if ($group ne '') {
                   7359:         $file_name =~s /^\Q$group\E//;
                   7360:     }
1.818     raeburn  7361:     my $homeserver = &homeserver($uname,$udom);
                   7362:     my $queryid=
1.821     raeburn  7363:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7364:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7365:     my $reply = &get_query_reply($queryid);
                   7366:     return $reply;
                   7367: }
                   7368: 
1.899     raeburn  7369: # -------------------------- Update MySQL allusers table
                   7370: 
                   7371: sub update_allusers_table {
                   7372:     my ($uname,$udom,$names) = @_;
                   7373:     my $homeserver = &homeserver($uname,$udom);
                   7374:     my $queryid=
                   7375:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7376:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7377:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7378:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7379:                'generation='.&escape($names->{'generation'}).'%%'.
                   7380:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7381:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7382:     return;
1.899     raeburn  7383: }
                   7384: 
1.508     raeburn  7385: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7386: 
                   7387: sub fetch_enrollment_query {
1.511     raeburn  7388:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7389:     my $homeserver;
1.547     raeburn  7390:     my $maxtries = 1;
1.508     raeburn  7391:     if ($context eq 'automated') {
                   7392:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7393:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7394:     } else {
                   7395:         $homeserver = &homeserver($cnum,$dom);
                   7396:     }
1.838     albertel 7397:     my $host=&hostname($homeserver);
1.506     raeburn  7398:     my $cmd = '';
1.1000    raeburn  7399:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7400:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7401:     }
                   7402:     $cmd =~ s/%%$//;
                   7403:     $cmd = &escape($cmd);
                   7404:     my $query = 'fetchenrollment';
1.620     albertel 7405:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7406:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7407:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7408:         return 'error: '.$queryid;
                   7409:     }
1.506     raeburn  7410:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7411:     my $tries = 1;
                   7412:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7413:         $reply = &get_query_reply($queryid);
                   7414:         $tries ++;
                   7415:     }
1.526     raeburn  7416:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7417:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7418:     } else {
1.901     albertel 7419:         my @responses = split(/:/,$reply);
1.515     raeburn  7420:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7421:             foreach my $line (@responses) {
                   7422:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7423:                 $$replyref{$key} = $value;
                   7424:             }
                   7425:         } else {
1.1117    foxr     7426:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7427:             foreach my $line (@responses) {
                   7428:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7429:                 $$replyref{$key} = $value;
                   7430:                 if ($value > 0) {
1.800     albertel 7431:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7432:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7433:                         my $destname = $pathname.'/'.$filename;
                   7434:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7435:                         if ($xml_classlist =~ /^error/) {
                   7436:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7437:                         } else {
1.506     raeburn  7438:                             if ( open(FILE,">$destname") ) {
                   7439:                                 print FILE &unescape($xml_classlist);
                   7440:                                 close(FILE);
1.526     raeburn  7441:                             } else {
                   7442:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7443:                             }
                   7444:                         }
                   7445:                     }
                   7446:                 }
                   7447:             }
                   7448:         }
                   7449:         return 'ok';
                   7450:     }
                   7451:     return 'error';
                   7452: }
                   7453: 
1.242     www      7454: sub get_query_reply {
                   7455:     my $queryid=shift;
1.1117    foxr     7456:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7457:     my $reply='';
                   7458:     for (1..100) {
                   7459: 	sleep 2;
                   7460:         if (-e $replyfile.'.end') {
1.448     albertel 7461: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7462: 		$reply = join('',<$fh>);
                   7463: 		close($fh);
1.240     www      7464: 	   } else { return 'error: reply_file_error'; }
1.242     www      7465:            return &unescape($reply);
                   7466: 	}
1.240     www      7467:     }
1.242     www      7468:     return 'timeout:'.$queryid;
1.240     www      7469: }
                   7470: 
                   7471: sub courselog_query {
1.241     www      7472: #
                   7473: # possible filters:
                   7474: # url: url or symb
                   7475: # username
                   7476: # domain
                   7477: # action: view, submit, grade
                   7478: # start: timestamp
                   7479: # end: timestamp
                   7480: #
1.240     www      7481:     my (%filters)=@_;
1.620     albertel 7482:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7483:     if ($filters{'url'}) {
                   7484: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7485:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7486:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7487:     }
1.620     albertel 7488:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7489:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7490:     return &log_query($cname,$cdom,'courselog',%filters);
                   7491: }
                   7492: 
                   7493: sub userlog_query {
1.858     raeburn  7494: #
                   7495: # possible filters:
                   7496: # action: log check role
                   7497: # start: timestamp
                   7498: # end: timestamp
                   7499: #
1.240     www      7500:     my ($uname,$udom,%filters)=@_;
                   7501:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7502: }
                   7503: 
1.506     raeburn  7504: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7505: 
                   7506: sub auto_run {
1.508     raeburn  7507:     my ($cnum,$cdom) = @_;
1.876     raeburn  7508:     my $response = 0;
                   7509:     my $settings;
                   7510:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7511:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7512:         $settings = $domconfig{'autoenroll'};
                   7513:         if ($settings->{'run'} eq '1') {
                   7514:             $response = 1;
                   7515:         }
                   7516:     } else {
1.934     raeburn  7517:         my $homeserver;
                   7518:         if (&is_course($cdom,$cnum)) {
                   7519:             $homeserver = &homeserver($cnum,$cdom);
                   7520:         } else {
                   7521:             $homeserver = &domain($cdom,'primary');
                   7522:         }
                   7523:         if ($homeserver ne 'no_host') {
                   7524:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7525:         }
1.876     raeburn  7526:     }
1.506     raeburn  7527:     return $response;
                   7528: }
1.776     albertel 7529: 
1.506     raeburn  7530: sub auto_get_sections {
1.508     raeburn  7531:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7532:     my $homeserver;
                   7533:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7534:         $homeserver = &homeserver($cnum,$cdom);
                   7535:     }
                   7536:     if (!defined($homeserver)) { 
                   7537:         if ($cdom =~ /^$match_domain$/) {
                   7538:             $homeserver = &domain($cdom,'primary');
                   7539:         }
                   7540:     }
                   7541:     my @secs;
                   7542:     if (defined($homeserver)) {
                   7543:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7544:         unless ($response eq 'refused') {
                   7545:             @secs = split(/:/,$response);
                   7546:         }
1.506     raeburn  7547:     }
                   7548:     return @secs;
                   7549: }
1.776     albertel 7550: 
1.506     raeburn  7551: sub auto_new_course {
1.1099    raeburn  7552:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7553:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7554:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7555:     return $response;
                   7556: }
1.776     albertel 7557: 
1.506     raeburn  7558: sub auto_validate_courseID {
1.508     raeburn  7559:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7560:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7561:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7562:     return $response;
                   7563: }
1.776     albertel 7564: 
1.1007    raeburn  7565: sub auto_validate_instcode {
1.1020    raeburn  7566:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7567:     my ($homeserver,$response);
                   7568:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7569:         $homeserver = &homeserver($cnum,$cdom);
                   7570:     }
                   7571:     if (!defined($homeserver)) {
                   7572:         if ($cdom =~ /^$match_domain$/) {
                   7573:             $homeserver = &domain($cdom,'primary');
                   7574:         }
                   7575:     }
1.1065    raeburn  7576:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7577:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7578:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7579:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7580: }
                   7581: 
1.506     raeburn  7582: sub auto_create_password {
1.873     raeburn  7583:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7584:     my ($homeserver,$response);
1.506     raeburn  7585:     my $create_passwd = 0;
                   7586:     my $authchk = '';
1.873     raeburn  7587:     if ($udom =~ /^$match_domain$/) {
                   7588:         $homeserver = &domain($udom,'primary');
                   7589:     }
                   7590:     if ($homeserver eq '') {
                   7591:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7592:             $homeserver = &homeserver($cnum,$cdom);
                   7593:         }
                   7594:     }
                   7595:     if ($homeserver eq '') {
                   7596:         $authchk = 'nodomain';
1.506     raeburn  7597:     } else {
1.873     raeburn  7598:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7599:         if ($response eq 'refused') {
                   7600:             $authchk = 'refused';
                   7601:         } else {
1.901     albertel 7602:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7603:         }
1.506     raeburn  7604:     }
                   7605:     return ($authparam,$create_passwd,$authchk);
                   7606: }
                   7607: 
1.706     raeburn  7608: sub auto_photo_permission {
                   7609:     my ($cnum,$cdom,$students) = @_;
                   7610:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7611:     my ($outcome,$perm_reqd,$conditions) = 
                   7612: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7613:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7614: 	return (undef,undef);
                   7615:     }
1.706     raeburn  7616:     return ($outcome,$perm_reqd,$conditions);
                   7617: }
                   7618: 
                   7619: sub auto_checkphotos {
                   7620:     my ($uname,$udom,$pid) = @_;
                   7621:     my $homeserver = &homeserver($uname,$udom);
                   7622:     my ($result,$resulttype);
                   7623:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7624: 				   &escape($uname).':'.&escape($pid),
                   7625: 				   $homeserver));
1.709     albertel 7626:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7627: 	return (undef,undef);
                   7628:     }
1.706     raeburn  7629:     if ($outcome) {
                   7630:         ($result,$resulttype) = split(/:/,$outcome);
                   7631:     } 
                   7632:     return ($result,$resulttype);
                   7633: }
                   7634: 
                   7635: sub auto_photochoice {
                   7636:     my ($cnum,$cdom) = @_;
                   7637:     my $homeserver = &homeserver($cnum,$cdom);
                   7638:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7639: 						       &escape($cdom),
                   7640: 						       $homeserver)));
1.709     albertel 7641:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7642: 	return (undef,undef);
                   7643:     }
1.706     raeburn  7644:     return ($update,$comment);
                   7645: }
                   7646: 
                   7647: sub auto_photoupdate {
                   7648:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7649:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7650:     my $host=&hostname($homeserver);
1.706     raeburn  7651:     my $cmd = '';
                   7652:     my $maxtries = 1;
1.800     albertel 7653:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7654:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7655:     }
                   7656:     $cmd =~ s/%%$//;
                   7657:     $cmd = &escape($cmd);
                   7658:     my $query = 'institutionalphotos';
                   7659:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7660:     unless ($queryid=~/^\Q$host\E\_/) {
                   7661:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7662:         return 'error: '.$queryid;
                   7663:     }
                   7664:     my $reply = &get_query_reply($queryid);
                   7665:     my $tries = 1;
                   7666:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7667:         $reply = &get_query_reply($queryid);
                   7668:         $tries ++;
                   7669:     }
                   7670:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7671:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7672:     } else {
                   7673:         my @responses = split(/:/,$reply);
                   7674:         my $outcome = shift(@responses); 
                   7675:         foreach my $item (@responses) {
                   7676:             my ($key,$value) = split(/=/,$item);
                   7677:             $$photo{$key} = $value;
                   7678:         }
                   7679:         return $outcome;
                   7680:     }
                   7681:     return 'error';
                   7682: }
                   7683: 
1.521     raeburn  7684: sub auto_instcode_format {
1.793     albertel 7685:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7686: 	$cat_order) = @_;
1.521     raeburn  7687:     my $courses = '';
1.772     raeburn  7688:     my @homeservers;
1.521     raeburn  7689:     if ($caller eq 'global') {
1.841     albertel 7690: 	my %servers = &get_servers($codedom,'library');
                   7691: 	foreach my $tryserver (keys(%servers)) {
                   7692: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7693: 		push(@homeservers,$tryserver);
                   7694: 	    }
1.584     raeburn  7695:         }
1.1022    raeburn  7696:     } elsif ($caller eq 'requests') {
                   7697:         if ($codedom =~ /^$match_domain$/) {
                   7698:             my $chome = &domain($codedom,'primary');
                   7699:             unless ($chome eq 'no_host') {
                   7700:                 push(@homeservers,$chome);
                   7701:             }
                   7702:         }
1.521     raeburn  7703:     } else {
1.772     raeburn  7704:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7705:     }
1.793     albertel 7706:     foreach my $code (keys(%{$instcodes})) {
                   7707:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7708:     }
                   7709:     chop($courses);
1.772     raeburn  7710:     my $ok_response = 0;
                   7711:     my $response;
                   7712:     while (@homeservers > 0 && $ok_response == 0) {
                   7713:         my $server = shift(@homeservers); 
                   7714:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7715:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7716:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7717: 		split(/:/,$response);
1.772     raeburn  7718:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7719:             push(@{$codetitles},&str2array($codetitles_str));
                   7720:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7721:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7722:             $ok_response = 1;
                   7723:         }
                   7724:     }
                   7725:     if ($ok_response) {
1.521     raeburn  7726:         return 'ok';
1.772     raeburn  7727:     } else {
                   7728:         return $response;
1.521     raeburn  7729:     }
                   7730: }
                   7731: 
1.792     raeburn  7732: sub auto_instcode_defaults {
                   7733:     my ($domain,$returnhash,$code_order) = @_;
                   7734:     my @homeservers;
1.841     albertel 7735: 
                   7736:     my %servers = &get_servers($domain,'library');
                   7737:     foreach my $tryserver (keys(%servers)) {
                   7738: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7739: 	    push(@homeservers,$tryserver);
                   7740: 	}
1.792     raeburn  7741:     }
1.841     albertel 7742: 
1.792     raeburn  7743:     my $response;
1.841     albertel 7744:     foreach my $server (@homeservers) {
1.792     raeburn  7745:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7746:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7747: 	
                   7748: 	foreach my $pair (split(/\&/,$response)) {
                   7749: 	    my ($name,$value)=split(/\=/,$pair);
                   7750: 	    if ($name eq 'code_order') {
                   7751: 		@{$code_order} = split(/\&/,&unescape($value));
                   7752: 	    } else {
                   7753: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7754: 	    }
                   7755: 	}
                   7756: 	return 'ok';
1.792     raeburn  7757:     }
1.841     albertel 7758: 
                   7759:     return $response;
1.1003    raeburn  7760: }
                   7761: 
                   7762: sub auto_possible_instcodes {
1.1007    raeburn  7763:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7764:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7765:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7766:         return;
                   7767:     }
1.1003    raeburn  7768:     my (@homeservers,$uhome);
                   7769:     if (defined(&domain($domain,'primary'))) {
                   7770:         $uhome=&domain($domain,'primary');
                   7771:         push(@homeservers,&domain($domain,'primary'));
                   7772:     } else {
                   7773:         my %servers = &get_servers($domain,'library');
                   7774:         foreach my $tryserver (keys(%servers)) {
                   7775:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7776:                 push(@homeservers,$tryserver);
                   7777:             }
                   7778:         }
                   7779:     }
                   7780:     my $response;
                   7781:     foreach my $server (@homeservers) {
                   7782:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7783:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7784:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7785:             split(':',$response);
                   7786:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7787:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7788:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7789:             my ($name,$value)=split('=',$item);
                   7790:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7791:         }
                   7792:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7793:             my ($name,$value)=split('=',$item);
                   7794:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7795:         }
                   7796:         return 'ok';
                   7797:     }
                   7798:     return $response;
                   7799: }
1.792     raeburn  7800: 
1.1010    raeburn  7801: sub auto_courserequest_checks {
                   7802:     my ($dom) = @_;
1.1020    raeburn  7803:     my ($homeserver,%validations);
                   7804:     if ($dom =~ /^$match_domain$/) {
                   7805:         $homeserver = &domain($dom,'primary');
                   7806:     }
                   7807:     unless ($homeserver eq 'no_host') {
                   7808:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7809:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7810:             my @items = split(/&/,$response);
                   7811:             foreach my $item (@items) {
                   7812:                 my ($key,$value) = split('=',$item);
                   7813:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7814:             }
                   7815:         }
                   7816:     }
1.1010    raeburn  7817:     return %validations; 
                   7818: }
                   7819: 
1.1020    raeburn  7820: sub auto_courserequest_validation {
                   7821:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7822:     my ($homeserver,$response);
                   7823:     if ($dom =~ /^$match_domain$/) {
                   7824:         $homeserver = &domain($dom,'primary');
                   7825:     }
                   7826:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7827:           
1.1020    raeburn  7828:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7829:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7830:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7831:                                     $homeserver));
                   7832:     }
                   7833:     return $response;
                   7834: }
                   7835: 
1.777     albertel 7836: sub auto_validate_class_sec {
1.918     raeburn  7837:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7838:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7839:     my $ownerlist;
                   7840:     if (ref($owners) eq 'ARRAY') {
                   7841:         $ownerlist = join(',',@{$owners});
                   7842:     } else {
                   7843:         $ownerlist = $owners;
                   7844:     }
1.773     raeburn  7845:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7846:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7847:     return $response;
                   7848: }
                   7849: 
1.679     raeburn  7850: # ------------------------------------------------------- Course Group routines
                   7851: 
                   7852: sub get_coursegroups {
1.809     raeburn  7853:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7854:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7855: }
                   7856: 
1.679     raeburn  7857: sub modify_coursegroup {
                   7858:     my ($cdom,$cnum,$groupsettings) = @_;
                   7859:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7860: }
                   7861: 
1.809     raeburn  7862: sub toggle_coursegroup_status {
                   7863:     my ($cdom,$cnum,$group,$action) = @_;
                   7864:     my ($from_namespace,$to_namespace);
                   7865:     if ($action eq 'delete') {
                   7866:         $from_namespace = 'coursegroups';
                   7867:         $to_namespace = 'deleted_groups';
                   7868:     } else {
                   7869:         $from_namespace = 'deleted_groups';
                   7870:         $to_namespace = 'coursegroups';
                   7871:     }
                   7872:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7873:     if (my $tmp = &error(%curr_group)) {
                   7874:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7875:         return ('read error',$tmp);
                   7876:     } else {
                   7877:         my %savedsettings = %curr_group; 
1.809     raeburn  7878:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7879:         my $deloutcome;
                   7880:         if ($result eq 'ok') {
1.809     raeburn  7881:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7882:         } else {
                   7883:             return ('write error',$result);
                   7884:         }
                   7885:         if ($deloutcome eq 'ok') {
                   7886:             return 'ok';
                   7887:         } else {
                   7888:             return ('delete error',$deloutcome);
                   7889:         }
                   7890:     }
                   7891: }
                   7892: 
1.679     raeburn  7893: sub modify_group_roles {
1.957     raeburn  7894:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7895:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7896:     my $role = 'gr/'.&escape($userprivs);
                   7897:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7898:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7899:     if ($result eq 'ok') {
                   7900:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7901:     }
1.679     raeburn  7902:     return $result;
                   7903: }
                   7904: 
                   7905: sub modify_coursegroup_membership {
                   7906:     my ($cdom,$cnum,$membership) = @_;
                   7907:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7908:     return $result;
                   7909: }
                   7910: 
1.682     raeburn  7911: sub get_active_groups {
                   7912:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7913:     my $now = time;
                   7914:     my %groups = ();
                   7915:     foreach my $key (keys(%env)) {
1.811     albertel 7916:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7917:             my ($start,$end) = split(/\./,$env{$key});
                   7918:             if (($end!=0) && ($end<$now)) { next; }
                   7919:             if (($start!=0) && ($start>$now)) { next; }
                   7920:             if ($1 eq $cdom && $2 eq $cnum) {
                   7921:                 $groups{$3} = $env{$key} ;
                   7922:             }
                   7923:         }
                   7924:     }
                   7925:     return %groups;
                   7926: }
                   7927: 
1.683     raeburn  7928: sub get_group_membership {
                   7929:     my ($cdom,$cnum,$group) = @_;
                   7930:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7931: }
                   7932: 
                   7933: sub get_users_groups {
                   7934:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7935:     my @usersgroups;
1.683     raeburn  7936:     my $cachetime=1800;
                   7937: 
                   7938:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7939:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7940:     if (defined($cached)) {
1.734     albertel 7941:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7942:     } else {  
                   7943:         $grouplist = '';
1.816     raeburn  7944:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7945:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7946:         my $access_end = $env{'course.'.$courseid.
                   7947:                               '.default_enrollment_end_date'};
                   7948:         my $now = time;
                   7949:         foreach my $key (keys(%roleshash)) {
                   7950:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7951:                 my $group = $1;
                   7952:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7953:                     my $start = $2;
                   7954:                     my $end = $1;
                   7955:                     if ($start == -1) { next; } # deleted from group
                   7956:                     if (($start!=0) && ($start>$now)) { next; }
                   7957:                     if (($end!=0) && ($end<$now)) {
                   7958:                         if ($access_end && $access_end < $now) {
                   7959:                             if ($access_end - $end < 86400) {
                   7960:                                 push(@usersgroups,$group);
1.733     raeburn  7961:                             }
                   7962:                         }
1.817     raeburn  7963:                         next;
1.733     raeburn  7964:                     }
1.817     raeburn  7965:                     push(@usersgroups,$group);
1.683     raeburn  7966:                 }
                   7967:             }
                   7968:         }
1.817     raeburn  7969:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7970:         $grouplist = join(':',@usersgroups);
                   7971:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7972:     }
1.733     raeburn  7973:     return @usersgroups;
1.683     raeburn  7974: }
                   7975: 
                   7976: sub devalidate_getgroups_cache {
                   7977:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7978:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7979: 
1.683     raeburn  7980:     my $hashid="$udom:$uname:$courseid";
                   7981:     &devalidate_cache_new('getgroups',$hashid);
                   7982: }
                   7983: 
1.12      www      7984: # ------------------------------------------------------------------ Plain Text
                   7985: 
                   7986: sub plaintext {
1.988     raeburn  7987:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7988:     if ($short =~ m{^cr/}) {
1.758     albertel 7989: 	return (split('/',$short))[-1];
                   7990:     }
1.742     raeburn  7991:     if (!defined($cid)) {
                   7992:         $cid = $env{'request.course.id'};
                   7993:     }
                   7994:     my %rolenames = (
1.1008    raeburn  7995:                       Course    => 'std',
                   7996:                       Community => 'alt1',
1.742     raeburn  7997:                     );
1.1037    raeburn  7998:     if ($cid ne '') {
                   7999:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8000:             unless ($forcedefault) {
                   8001:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8002:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8003:                 return &Apache::lonlocal::mt($roletext);
                   8004:             }
                   8005:         }
                   8006:     }
                   8007:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8008:         (defined($rolenames{$type})) && 
                   8009:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8010:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8011:     } elsif ($cid ne '') {
                   8012:         my $crstype = $env{'course.'.$cid.'.type'};
                   8013:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8014:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8015:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8016:         }
1.742     raeburn  8017:     }
1.1037    raeburn  8018:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8019: }
                   8020: 
                   8021: # ----------------------------------------------------------------- Assign Role
                   8022: 
                   8023: sub assignrole {
1.957     raeburn  8024:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8025:         $context)=@_;
1.21      www      8026:     my $mrole;
                   8027:     if ($role =~ /^cr\//) {
1.393     www      8028:         my $cwosec=$url;
1.811     albertel 8029:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8030: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8031:            my $refused = 1;
                   8032:            if ($context eq 'requestcourses') {
                   8033:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8034:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8035:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8036:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8037:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8038:                            if ($crsenv{'internal.courseowner'} eq
                   8039:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8040:                                $refused = '';
                   8041:                            }
                   8042:                        }
                   8043:                    }
                   8044:                }
                   8045:            }
                   8046:            if ($refused) {
                   8047:                &logthis('Refused custom assignrole: '.
                   8048:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8049:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8050:                return 'refused';
                   8051:            }
1.104     www      8052:         }
1.21      www      8053:         $mrole='cr';
1.678     raeburn  8054:     } elsif ($role =~ /^gr\//) {
                   8055:         my $cwogrp=$url;
1.811     albertel 8056:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8057:         unless (&allowed('mdg',$cwogrp)) {
                   8058:             &logthis('Refused group assignrole: '.
                   8059:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8060:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8061:             return 'refused';
                   8062:         }
                   8063:         $mrole='gr';
1.21      www      8064:     } else {
1.82      www      8065:         my $cwosec=$url;
1.811     albertel 8066:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8067:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8068:             my $refused;
                   8069:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8070:                 if (!(&allowed('c'.$role,$url))) {
                   8071:                     $refused = 1;
                   8072:                 }
                   8073:             } else {
                   8074:                 $refused = 1;
                   8075:             }
1.947     raeburn  8076:             if ($refused) {
1.1045    raeburn  8077:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8078:                 if (!$selfenroll && $context eq 'course') {
                   8079:                     my %crsenv;
                   8080:                     if ($role eq 'cc' || $role eq 'co') {
                   8081:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8082:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8083:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8084:                                 if ($crsenv{'internal.courseowner'} eq 
                   8085:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8086:                                     $refused = '';
                   8087:                                 }
                   8088:                             }
                   8089:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8090:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8091:                                 if ($crsenv{'internal.courseowner'} eq 
                   8092:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8093:                                     $refused = '';
                   8094:                                 }
                   8095:                             }
                   8096:                         }
                   8097:                     }
                   8098:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8099:                     $refused = '';
1.1017    raeburn  8100:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8101:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8102:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8103:                         my $wrongcc;
                   8104:                         if ($cnum =~ /^$match_community$/) {
                   8105:                             $wrongcc = 1 if ($role eq 'cc');
                   8106:                         } else {
                   8107:                             $wrongcc = 1 if ($role eq 'co');
                   8108:                         }
                   8109:                         unless ($wrongcc) {
                   8110:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8111:                             if ($crsenv{'internal.courseowner'} eq 
                   8112:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8113:                                 $refused = '';
                   8114:                             }
1.1017    raeburn  8115:                         }
                   8116:                     }
1.1183    raeburn  8117:                 } elsif ($context eq 'requestauthor') {
                   8118:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8119:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8120:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8121:                             $refused = '';
                   8122:                         } else {
                   8123:                             my %domdefaults = &get_domain_defaults($udom);
                   8124:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8125:                                 my $checkbystatus;
                   8126:                                 if ($env{'user.adv'}) { 
                   8127:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8128:                                     if ($disposition eq 'automatic') {
                   8129:                                         $refused = '';
                   8130:                                     } elsif ($disposition eq '') {
                   8131:                                         $checkbystatus = 1;
                   8132:                                     } 
                   8133:                                 } else {
                   8134:                                     $checkbystatus = 1;
                   8135:                                 }
                   8136:                                 if ($checkbystatus) {
                   8137:                                     if ($env{'environment.inststatus'}) {
                   8138:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8139:                                         foreach my $type (@inststatuses) {
                   8140:                                             if (($type ne '') &&
                   8141:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8142:                                                 $refused = '';
                   8143:                                             }
                   8144:                                         }
                   8145:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8146:                                         $refused = '';
                   8147:                                     }
                   8148:                                 }
                   8149:                             }
                   8150:                         }
                   8151:                     }
1.1017    raeburn  8152:                 }
                   8153:                 if ($refused) {
1.947     raeburn  8154:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8155:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8156: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8157:                     return 'refused';
                   8158:                 }
1.932     raeburn  8159:             }
1.1131    raeburn  8160:         } elsif ($role eq 'au') {
                   8161:             if ($url ne '/'.$udom.'/') {
                   8162:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8163:                          ' to assign author role for '.$uname.':'.$udom.
                   8164:                          ' in domain: '.$url.' refused (wrong domain).');
                   8165:                 return 'refused';
                   8166:             }
1.104     www      8167:         }
1.21      www      8168:         $mrole=$role;
                   8169:     }
1.620     albertel 8170:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8171:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8172:     if ($end) { $command.='_'.$end; }
1.21      www      8173:     if ($start) {
                   8174: 	if ($end) { 
1.81      www      8175:            $command.='_'.$start; 
1.21      www      8176:         } else {
1.81      www      8177:            $command.='_0_'.$start;
1.21      www      8178:         }
                   8179:     }
1.739     raeburn  8180:     my $origstart = $start;
                   8181:     my $origend = $end;
1.957     raeburn  8182:     my $delflag;
1.357     www      8183: # actually delete
                   8184:     if ($deleteflag) {
1.373     www      8185: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8186: # modify command to delete the role
1.620     albertel 8187:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8188:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8189: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8190: # set start and finish to negative values for userrolelog
                   8191:            $start=-1;
                   8192:            $end=-1;
1.957     raeburn  8193:            $delflag = 1;
1.357     www      8194:         }
                   8195:     }
                   8196: # send command
1.349     www      8197:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8198: # log new user role if status is ok
1.349     www      8199:     if ($answer eq 'ok') {
1.663     raeburn  8200: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8201:         if (($role eq 'cc') || ($role eq 'in') ||
                   8202:             ($role eq 'ep') || ($role eq 'ad') ||
                   8203:             ($role eq 'ta') || ($role eq 'st') ||
                   8204:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8205:             ($role eq 'co')) {
1.1200    raeburn  8206: # for course roles, perform group memberships changes triggered by role change.
                   8207:             unless ($role =~ /^gr/) {
                   8208:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8209:                                                  $origstart,$selfenroll,$context);
                   8210:             }
1.1184    raeburn  8211:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8212:                            $selfenroll,$context);
                   8213:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8214:                  ($role eq 'au') || ($role eq 'dc')) {
                   8215:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8216:                            $context);
                   8217:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8218:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8219:                              $context); 
                   8220:         }
1.1053    raeburn  8221:         if ($role eq 'cc') {
                   8222:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8223:         }
1.349     www      8224:     }
                   8225:     return $answer;
1.169     harris41 8226: }
                   8227: 
1.1053    raeburn  8228: sub autoupdate_coowners {
                   8229:     my ($url,$end,$start,$uname,$udom) = @_;
                   8230:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8231:     if (($cdom ne '') && ($cnum ne '')) {
                   8232:         my $now = time;
                   8233:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8234:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8235:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8236:             my $instcode = $coursehash{'internal.coursecode'};
                   8237:             if ($instcode ne '') {
1.1056    raeburn  8238:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8239:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8240:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8241:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8242:                         if ($result eq 'valid') {
                   8243:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8244:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8245:                                     push(@newcoowners,$coowner);
                   8246:                                 }
                   8247:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8248:                                     push(@newcoowners,$uname.':'.$udom);
                   8249:                                 }
                   8250:                                 @newcoowners = sort(@newcoowners);
                   8251:                             } else {
                   8252:                                 push(@newcoowners,$uname.':'.$udom);
                   8253:                             }
                   8254:                         } else {
                   8255:                             if ($coursehash{'internal.co-owners'}) {
                   8256:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8257:                                     unless ($coowner eq $uname.':'.$udom) {
                   8258:                                         push(@newcoowners,$coowner);
                   8259:                                     }
                   8260:                                 }
                   8261:                                 unless (@newcoowners > 0) {
                   8262:                                     $delcoowners = 1;
                   8263:                                     $coowners = '';
                   8264:                                 }
                   8265:                             }
                   8266:                         }
                   8267:                         if (@newcoowners || $delcoowners) {
                   8268:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8269:                                             $delcoowners,@newcoowners);
                   8270:                         }
                   8271:                     }
                   8272:                 }
                   8273:             }
                   8274:         }
                   8275:     }
                   8276: }
                   8277: 
                   8278: sub store_coowners {
                   8279:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8280:     my $cid = $cdom.'_'.$cnum;
                   8281:     my ($coowners,$delresult,$putresult);
                   8282:     if (@newcoowners) {
                   8283:         $coowners = join(',',@newcoowners);
                   8284:         my %coownershash = (
                   8285:                             'internal.co-owners' => $coowners,
                   8286:                            );
                   8287:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8288:         if ($putresult eq 'ok') {
                   8289:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8290:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8291:             }
                   8292:         }
                   8293:     }
                   8294:     if ($delcoowners) {
                   8295:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8296:         if ($delresult eq 'ok') {
                   8297:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8298:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8299:             }
                   8300:         }
                   8301:     }
                   8302:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8303:         my %crsinfo =
                   8304:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8305:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8306:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8307:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8308:         }
                   8309:     }
                   8310: }
                   8311: 
1.169     harris41 8312: # -------------------------------------------------- Modify user authentication
1.197     www      8313: # Overrides without validation
                   8314: 
1.169     harris41 8315: sub modifyuserauth {
                   8316:     my ($udom,$uname,$umode,$upass)=@_;
                   8317:     my $uhome=&homeserver($uname,$udom);
1.197     www      8318:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8319:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8320:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8321:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8322:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8323: 		     &escape($upass),$uhome);
1.620     albertel 8324:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8325:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8326:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8327:     &log($udom,,$uname,$uhome,
1.620     albertel 8328:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8329:                                      $env{'user.name'}.', '.$umode.
1.197     www      8330:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8331:     unless ($reply eq 'ok') {
1.197     www      8332:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8333: 	return 'error: '.$reply;
                   8334:     }   
1.170     harris41 8335:     return 'ok';
1.80      www      8336: }
                   8337: 
1.81      www      8338: # --------------------------------------------------------------- Modify a user
1.80      www      8339: 
1.81      www      8340: sub modifyuser {
1.206     matthew  8341:     my ($udom,    $uname, $uid,
                   8342:         $umode,   $upass, $first,
                   8343:         $middle,  $last,  $gene,
1.1058    raeburn  8344:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8345:     $udom= &LONCAPA::clean_domain($udom);
                   8346:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8347:     my $showcandelete = 'none';
                   8348:     if (ref($candelete) eq 'ARRAY') {
                   8349:         if (@{$candelete} > 0) {
                   8350:             $showcandelete = join(', ',@{$candelete});
                   8351:         }
                   8352:     }
1.81      www      8353:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8354:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8355: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8356:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8357:                                      ' desiredhome not specified'). 
1.620     albertel 8358:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8359:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8360:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8361:     my $newuser;
                   8362:     if ($uhome eq 'no_host') {
                   8363:         $newuser = 1;
                   8364:     }
1.80      www      8365: # ----------------------------------------------------------------- Create User
1.406     albertel 8366:     if (($uhome eq 'no_host') && 
                   8367: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8368:         my $unhome='';
1.844     albertel 8369:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8370:             $unhome = $desiredhome;
1.620     albertel 8371: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8372: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8373:         } else { # load balancing routine for determining $unhome
1.81      www      8374:             my $loadm=10000000;
1.841     albertel 8375: 	    my %servers = &get_servers($udom,'library');
                   8376: 	    foreach my $tryserver (keys(%servers)) {
                   8377: 		my $answer=reply('load',$tryserver);
                   8378: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8379: 		    $loadm=$answer;
                   8380: 		    $unhome=$tryserver;
                   8381: 		}
1.80      www      8382: 	    }
                   8383:         }
                   8384:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8385: 	    return 'error: unable to find a home server for '.$uname.
                   8386:                    ' in domain '.$udom;
1.80      www      8387:         }
                   8388:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8389:                          &escape($upass),$unhome);
                   8390: 	unless ($reply eq 'ok') {
                   8391:             return 'error: '.$reply;
                   8392:         }   
1.230     stredwic 8393:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8394:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8395: 	    return 'error: unable verify users home machine.';
1.80      www      8396:         }
1.209     matthew  8397:     }   # End of creation of new user
1.80      www      8398: # ---------------------------------------------------------------------- Add ID
                   8399:     if ($uid) {
                   8400:        $uid=~tr/A-Z/a-z/;
                   8401:        my %uidhash=&idrget($udom,$uname);
1.196     www      8402:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8403:          && (!$forceid)) {
1.80      www      8404: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8405: 	      return 'error: user id "'.$uid.'" does not match '.
                   8406:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8407:           }
                   8408:        } else {
                   8409: 	  &idput($udom,($uname => $uid));
                   8410:        }
                   8411:     }
                   8412: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8413:     my @tmp=&get('environment',
1.899     raeburn  8414: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8415:                     'permanentemail','inststatus'],
1.134     albertel 8416: 		   $udom,$uname);
1.1075    raeburn  8417:     my (%names,%oldnames);
1.313     matthew  8418:     if ($tmp[0] =~ m/^error:.*/) { 
                   8419:         %names=(); 
                   8420:     } else {
                   8421:         %names = @tmp;
1.1075    raeburn  8422:         %oldnames = %names;
1.313     matthew  8423:     }
1.388     www      8424: #
1.1058    raeburn  8425: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8426: # of users did not contain them), do not overwrite existing values
                   8427: # unless field is in $candelete array ref.  
                   8428: #
                   8429: 
                   8430:     my @fields = ('firstname','middlename','lastname','generation',
                   8431:                   'permanentemail','id');
                   8432:     my %newvalues;
                   8433:     if (ref($candelete) eq 'ARRAY') {
                   8434:         foreach my $field (@fields) {
                   8435:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8436:                 if ($field eq 'firstname') {
                   8437:                     $names{$field} = $first;
                   8438:                 } elsif ($field eq 'middlename') {
                   8439:                     $names{$field} = $middle;
                   8440:                 } elsif ($field eq 'lastname') {
                   8441:                     $names{$field} = $last;
                   8442:                 } elsif ($field eq 'generation') { 
                   8443:                     $names{$field} = $gene;
                   8444:                 } elsif ($field eq 'permanentemail') {
                   8445:                     $names{$field} = $email;
                   8446:                 } elsif ($field eq 'id') {
                   8447:                     $names{$field}  = $uid;
                   8448:                 }
                   8449:             }
                   8450:         }
                   8451:     }
1.388     www      8452:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8453:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8454:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8455:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8456:     if ($email) {
                   8457:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8458:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8459:     }
1.899     raeburn  8460:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8461:     if (defined($inststatus)) {
                   8462:         $names{'inststatus'} = '';
                   8463:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8464:         if (ref($usertypes) eq 'HASH') {
                   8465:             my @okstatuses; 
                   8466:             foreach my $item (split(/:/,$inststatus)) {
                   8467:                 if (defined($usertypes->{$item})) {
                   8468:                     push(@okstatuses,$item);  
                   8469:                 }
                   8470:             }
                   8471:             if (@okstatuses) {
                   8472:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8473:             }
                   8474:         }
                   8475:     }
1.1075    raeburn  8476:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8477:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8478:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8479:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8480:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8481:     } else {
                   8482:         $logmsg .= ' during self creation';
                   8483:     }
1.1075    raeburn  8484:     my $changed;
                   8485:     if ($newuser) {
                   8486:         $changed = 1;
                   8487:     } else {
                   8488:         foreach my $field (@fields) {
                   8489:             if ($names{$field} ne $oldnames{$field}) {
                   8490:                 $changed = 1;
                   8491:                 last;
                   8492:             }
                   8493:         }
                   8494:     }
                   8495:     unless ($changed) {
                   8496:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8497:         &logthis($logmsg);
                   8498:         return 'ok';
                   8499:     }
                   8500:     my $reply = &put('environment', \%names, $udom,$uname);
                   8501:     if ($reply ne 'ok') { 
                   8502:         return 'error: '.$reply;
                   8503:     }
1.1087    raeburn  8504:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8505:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8506:     }
1.1075    raeburn  8507:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8508:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8509:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8510:     &logthis($logmsg);
1.134     albertel 8511:     return 'ok';
1.80      www      8512: }
                   8513: 
1.81      www      8514: # -------------------------------------------------------------- Modify student
1.80      www      8515: 
1.81      www      8516: sub modifystudent {
                   8517:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8518:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8519:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8520:     if (!$cid) {
1.620     albertel 8521: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8522: 	    return 'not_in_class';
                   8523: 	}
1.80      www      8524:     }
                   8525: # --------------------------------------------------------------- Make the user
1.81      www      8526:     my $reply=&modifyuser
1.209     matthew  8527: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8528:          $desiredhome,$email,$inststatus);
1.80      www      8529:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8530:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8531:     # student's environment
1.297     matthew  8532:     $uid = undef if (!$forceid);
1.455     albertel 8533:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8534:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8535:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8536:     return $reply;
                   8537: }
                   8538: 
                   8539: sub modify_student_enrollment {
1.1216    raeburn  8540:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8541:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8542:     my ($cdom,$cnum,$chome);
                   8543:     if (!$cid) {
1.620     albertel 8544: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8545: 	    return 'not_in_class';
                   8546: 	}
1.620     albertel 8547: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8548: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8549:     } else {
                   8550: 	($cdom,$cnum)=split(/_/,$cid);
                   8551:     }
1.620     albertel 8552:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8553:     if (!$chome) {
1.457     raeburn  8554: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8555:     }
1.455     albertel 8556:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8557:     # Make sure the user exists
1.81      www      8558:     my $uhome=&homeserver($uname,$udom);
                   8559:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8560: 	return 'error: no such user';
                   8561:     }
1.297     matthew  8562:     # Get student data if we were not given enough information
                   8563:     if (!defined($first)  || $first  eq '' || 
                   8564:         !defined($last)   || $last   eq '' || 
                   8565:         !defined($uid)    || $uid    eq '' || 
                   8566:         !defined($middle) || $middle eq '' || 
                   8567:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8568:         # They did not supply us with enough data to enroll the student, so
                   8569:         # we need to pick up more information.
1.297     matthew  8570:         my %tmp = &get('environment',
1.294     matthew  8571:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8572:                        ,$udom,$uname);
                   8573: 
1.800     albertel 8574:         #foreach my $key (keys(%tmp)) {
                   8575:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8576:         #}
1.294     matthew  8577:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8578:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8579:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8580:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8581:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8582:     }
1.556     albertel 8583:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8584:     my $user = "$uname:$udom";
                   8585:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8586:     my $reply=cput('classlist',
1.1148    raeburn  8587: 		   {$user => 
1.1216    raeburn  8588: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8589: 		   $cdom,$cnum);
1.1148    raeburn  8590:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8591:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8592:     } else { 
1.81      www      8593: 	return 'error: '.$reply;
                   8594:     }
1.297     matthew  8595:     # Add student role to user
1.83      www      8596:     my $uurl='/'.$cid;
1.81      www      8597:     $uurl=~s/\_/\//g;
                   8598:     if ($usec) {
                   8599: 	$uurl.='/'.$usec;
                   8600:     }
1.1148    raeburn  8601:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8602:                              $selfenroll,$context);
                   8603:     if ($result ne 'ok') {
                   8604:         if ($old_entry{$user} ne '') {
                   8605:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8606:         } else {
                   8607:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8608:         }
                   8609:     }
                   8610:     return $result; 
1.21      www      8611: }
                   8612: 
1.556     albertel 8613: sub format_name {
                   8614:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8615:     my $name;
                   8616:     if ($first ne 'lastname') {
                   8617: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8618:     } else {
                   8619: 	if ($lastname=~/\S/) {
                   8620: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8621: 	    $name=~s/\s+,/,/;
                   8622: 	} else {
                   8623: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8624: 	}
                   8625:     }
                   8626:     $name=~s/^\s+//;
                   8627:     $name=~s/\s+$//;
                   8628:     $name=~s/\s+/ /g;
                   8629:     return $name;
                   8630: }
                   8631: 
1.84      www      8632: # ------------------------------------------------- Write to course preferences
                   8633: 
                   8634: sub writecoursepref {
                   8635:     my ($courseid,%prefs)=@_;
                   8636:     $courseid=~s/^\///;
                   8637:     $courseid=~s/\_/\//g;
                   8638:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8639:     my $chome=homeserver($cnum,$cdomain);
                   8640:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8641: 	return 'error: no such course';
                   8642:     }
                   8643:     my $cstring='';
1.800     albertel 8644:     foreach my $pref (keys(%prefs)) {
                   8645: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8646:     }
1.84      www      8647:     $cstring=~s/\&$//;
                   8648:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8649: }
                   8650: 
                   8651: # ---------------------------------------------------------- Make/modify course
                   8652: 
                   8653: sub createcourse {
1.741     raeburn  8654:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8655:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8656:     $url=&declutter($url);
                   8657:     my $cid='';
1.1028    raeburn  8658:     if ($context eq 'requestcourses') {
                   8659:         my $can_create = 0;
                   8660:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8661:         if ($udom eq $ownerdom) {
                   8662:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8663:                                   $context)) {
                   8664:                 $can_create = 1;
                   8665:             }
                   8666:         } else {
                   8667:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8668:                                            $category);
                   8669:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8670:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8671:                 if (@curr > 0) {
                   8672:                     my @options = qw(approval validate autolimit);
                   8673:                     my $optregex = join('|',@options);
                   8674:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8675:                         $can_create = 1;
                   8676:                     }
                   8677:                 }
                   8678:             }
                   8679:         }
                   8680:         if ($can_create) {
                   8681:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8682:                 unless (&allowed('ccc',$udom)) {
                   8683:                     return 'refused'; 
                   8684:                 }
1.1017    raeburn  8685:             }
                   8686:         } else {
                   8687:             return 'refused';
                   8688:         }
1.1028    raeburn  8689:     } elsif (!&allowed('ccc',$udom)) {
                   8690:         return 'refused';
1.84      www      8691:     }
1.1011    raeburn  8692: # --------------------------------------------------------------- Get Unique ID
                   8693:     my $uname;
                   8694:     if ($cnum =~ /^$match_courseid$/) {
                   8695:         my $chome=&homeserver($cnum,$udom,'true');
                   8696:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8697:             $uname = $cnum;
                   8698:         } else {
1.1038    raeburn  8699:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8700:         }
                   8701:     } else {
1.1038    raeburn  8702:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8703:     }
                   8704:     return $uname if ($uname =~ /^error/);
                   8705: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8706:     if (!defined($course_server)) {
                   8707:         if (defined(&domain($udom,'primary'))) {
                   8708:             $course_server = &domain($udom,'primary');
                   8709:         } else {
                   8710:             $course_server = $env{'user.home'}; 
                   8711:         }
                   8712:     }
                   8713:     my %host_servers =
                   8714:         &Apache::lonnet::get_servers($udom,'library');
                   8715:     unless ($host_servers{$course_server}) {
                   8716:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8717:     }
1.84      www      8718: # ------------------------------------------------------------- Make the course
                   8719:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8720:                       $course_server);
1.84      www      8721:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8722:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8723:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8724: 	return 'error: no such course';
                   8725:     }
1.271     www      8726: # ----------------------------------------------------------------- Course made
1.516     raeburn  8727: # log existence
1.1029    raeburn  8728:     my $now = time;
1.918     raeburn  8729:     my $newcourse = {
                   8730:                     $udom.'_'.$uname => {
1.921     raeburn  8731:                                      description => $description,
                   8732:                                      inst_code   => $inst_code,
                   8733:                                      owner       => $course_owner,
                   8734:                                      type        => $crstype,
1.1029    raeburn  8735:                                      creator     => $env{'user.name'}.':'.
                   8736:                                                     $env{'user.domain'},
                   8737:                                      created     => $now,
                   8738:                                      context     => $context,
1.918     raeburn  8739:                                                 },
                   8740:                     };
1.921     raeburn  8741:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8742: # set toplevel url
1.271     www      8743:     my $topurl=$url;
                   8744:     unless ($nonstandard) {
                   8745: # ------------------------------------------ For standard courses, make top url
                   8746:         my $mapurl=&clutter($url);
1.278     www      8747:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8748:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8749: <map>
                   8750: <resource id="1" type="start"></resource>
                   8751: <resource id="2" src="$mapurl"></resource>
                   8752: <resource id="3" type="finish"></resource>
                   8753: <link index="1" from="1" to="2"></link>
                   8754: <link index="2" from="2" to="3"></link>
                   8755: </map>
                   8756: ENDINITMAP
                   8757:         $topurl=&declutter(
1.638     albertel 8758:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8759:                           );
                   8760:     }
                   8761: # ----------------------------------------------------------- Write preferences
1.84      www      8762:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8763:                      ('description'              => $description,
                   8764:                       'url'                      => $topurl,
                   8765:                       'internal.creator'         => $env{'user.name'}.':'.
                   8766:                                                     $env{'user.domain'},
                   8767:                       'internal.created'         => $now,
                   8768:                       'internal.creationcontext' => $context)
                   8769:                     );
1.84      www      8770:     return '/'.$udom.'/'.$uname;
                   8771: }
                   8772: 
1.1011    raeburn  8773: # ------------------------------------------------------------------- Create ID
                   8774: sub generate_coursenum {
1.1038    raeburn  8775:     my ($udom,$crstype) = @_;
1.1011    raeburn  8776:     my $domdesc = &domain($udom);
                   8777:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8778:     my $first;
                   8779:     if ($crstype eq 'Community') {
                   8780:         $first = '0';
                   8781:     } else {
                   8782:         $first = int(1+rand(9)); 
                   8783:     } 
                   8784:     my $uname=$first.
1.1011    raeburn  8785:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8786:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8787:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8788: # ----------------------------------------------- Make sure that does not exist
                   8789:     my $uhome=&homeserver($uname,$udom,'true');
                   8790:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8791:         if ($crstype eq 'Community') {
                   8792:             $first = '0';
                   8793:         } else {
                   8794:             $first = int(1+rand(9));
                   8795:         }
                   8796:         $uname=$first.
1.1011    raeburn  8797:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8798:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8799:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8800:         $uhome=&homeserver($uname,$udom,'true');
                   8801:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8802:             return 'error: unable to generate unique course-ID';
                   8803:         }
                   8804:     }
                   8805:     return $uname;
                   8806: }
                   8807: 
1.813     albertel 8808: sub is_course {
1.1167    droeschl 8809:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8810:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8811: 
                   8812:     return unless $cdom and $cnum;
                   8813: 
                   8814:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8815:         '.');
                   8816: 
1.1219    raeburn  8817:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8818:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8819: }
                   8820: 
1.1015    raeburn  8821: sub store_userdata {
                   8822:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8823:     my $result;
1.1016    raeburn  8824:     if ($datakey ne '') {
1.1013    raeburn  8825:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8826:             if ($udom eq '' || $uname eq '') {
                   8827:                 $udom = $env{'user.domain'};
                   8828:                 $uname = $env{'user.name'};
                   8829:             }
                   8830:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8831:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8832:                 $result = 'error: no_host';
                   8833:             } else {
                   8834:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8835:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8836: 
                   8837:                 my $namevalue='';
                   8838:                 foreach my $key (keys(%{$storehash})) {
                   8839:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8840:                 }
                   8841:                 $namevalue=~s/\&$//;
1.1224    raeburn  8842:                 unless ($namespace eq 'courserequests') {
                   8843:                     $datakey = &escape($datakey);
                   8844:                 }
1.1105    raeburn  8845:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8846:                                   $namevalue,$uhome);
1.1013    raeburn  8847:             }
                   8848:         } else {
                   8849:             $result = 'error: data to store was not a hash reference'; 
                   8850:         }
                   8851:     } else {
                   8852:         $result= 'error: invalid requestkey'; 
                   8853:     }
                   8854:     return $result;
                   8855: }
                   8856: 
1.21      www      8857: # ---------------------------------------------------------- Assign Custom Role
                   8858: 
                   8859: sub assigncustomrole {
1.957     raeburn  8860:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8861:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8862:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8863: }
                   8864: 
                   8865: # ----------------------------------------------------------------- Revoke Role
                   8866: 
                   8867: sub revokerole {
1.957     raeburn  8868:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8869:     my $now=time;
1.965     raeburn  8870:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8871: }
                   8872: 
                   8873: # ---------------------------------------------------------- Revoke Custom Role
                   8874: 
                   8875: sub revokecustomrole {
1.957     raeburn  8876:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8877:     my $now=time;
1.357     www      8878:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8879:            $deleteflag,$selfenroll,$context);
1.17      www      8880: }
                   8881: 
1.533     banghart 8882: # ------------------------------------------------------------ Disk usage
1.535     albertel 8883: sub diskusage {
1.955     raeburn  8884:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8885:     $directorypath =~ s/\/$//;
                   8886:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8887:                        .&escape($getpropath).':'.&escape($uname).':'
                   8888:                        .&escape($udom),homeserver($uname,$udom));
                   8889:     if ($listing eq 'unknown_cmd') {
                   8890:         if ($getpropath) {
                   8891:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8892:         }
                   8893:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8894:     }
1.514     albertel 8895:     return $listing;
1.512     banghart 8896: }
                   8897: 
1.566     banghart 8898: sub is_locked {
1.1096    raeburn  8899:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8900:     my @check;
                   8901:     my $is_locked;
1.1093    raeburn  8902:     push (@check,$file_name);
1.613     albertel 8903:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8904: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8905:     my ($tmp)=keys(%locked);
                   8906:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8907:     
1.566     banghart 8908:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8909:         $is_locked = 'false';
                   8910:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8911:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8912:                $is_locked = 'true';
1.1096    raeburn  8913:                if (ref($which) eq 'ARRAY') {
                   8914:                    push(@{$which},$entry);
                   8915:                } else {
                   8916:                    last;
                   8917:                }
1.745     raeburn  8918:            }
                   8919:        }
1.566     banghart 8920:     } else {
                   8921:         $is_locked = 'false';
                   8922:     }
1.1093    raeburn  8923:     return $is_locked;
1.566     banghart 8924: }
                   8925: 
1.759     albertel 8926: sub declutter_portfile {
                   8927:     my ($file) = @_;
1.833     albertel 8928:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8929:     return $file;
                   8930: }
                   8931: 
1.559     banghart 8932: # ------------------------------------------------------------- Mark as Read Only
                   8933: 
                   8934: sub mark_as_readonly {
                   8935:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8936:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8937:     my ($tmp)=keys(%current_permissions);
                   8938:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8939:     foreach my $file (@{$files}) {
1.759     albertel 8940: 	$file = &declutter_portfile($file);
1.561     banghart 8941:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8942:     }
1.613     albertel 8943:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8944:     return;
                   8945: }
                   8946: 
1.572     banghart 8947: # ------------------------------------------------------------Save Selected Files
                   8948: 
                   8949: sub save_selected_files {
                   8950:     my ($user, $path, @files) = @_;
                   8951:     my $filename = $user."savedfiles";
1.573     banghart 8952:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8953:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8954:     foreach my $file (@files) {
1.620     albertel 8955:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8956:     }
                   8957:     foreach my $file (@other_files) {
1.574     banghart 8958:         print (OUT $file."\n");
1.572     banghart 8959:     }
1.574     banghart 8960:     close (OUT);
1.572     banghart 8961:     return 'ok';
                   8962: }
                   8963: 
1.574     banghart 8964: sub clear_selected_files {
                   8965:     my ($user) = @_;
                   8966:     my $filename = $user."savedfiles";
1.1117    foxr     8967:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8968:     print (OUT undef);
                   8969:     close (OUT);
                   8970:     return ("ok");    
                   8971: }
                   8972: 
1.572     banghart 8973: sub files_in_path {
                   8974:     my ($user, $path) = @_;
                   8975:     my $filename = $user."savedfiles";
                   8976:     my %return_files;
1.1117    foxr     8977:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8978:     while (my $line_in = <IN>) {
1.574     banghart 8979:         chomp ($line_in);
                   8980:         my @paths_and_file = split (m!/!, $line_in);
                   8981:         my $file_part = pop (@paths_and_file);
                   8982:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8983:         $path_part.='/';
                   8984:         my $path_and_file = $path_part.$file_part;
                   8985:         if ($path_part eq $path) {
                   8986:             $return_files{$file_part}= 'selected';
                   8987:         }
                   8988:     }
1.574     banghart 8989:     close (IN);
                   8990:     return (\%return_files);
1.572     banghart 8991: }
                   8992: 
                   8993: # called in portfolio select mode, to show files selected NOT in current directory
                   8994: sub files_not_in_path {
                   8995:     my ($user, $path) = @_;
                   8996:     my $filename = $user."savedfiles";
                   8997:     my @return_files;
                   8998:     my $path_part;
1.1117    foxr     8999:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9000:     while (my $line = <IN>) {
1.572     banghart 9001:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9002:         my @paths_and_file = split(m|/|, $line);
                   9003:         my $file_part = pop(@paths_and_file);
                   9004:         chomp($file_part);
                   9005:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9006:         $path_part .= '/';
                   9007:         my $path_and_file = $path_part.$file_part;
                   9008:         if ($path_part ne $path) {
1.800     albertel 9009:             push(@return_files, ($path_and_file));
1.572     banghart 9010:         }
                   9011:     }
1.800     albertel 9012:     close(OUT);
1.574     banghart 9013:     return (@return_files);
1.572     banghart 9014: }
                   9015: 
1.745     raeburn  9016: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9017: 
1.745     raeburn  9018: sub get_portfile_permissions {
                   9019:     my ($domain,$user) = @_;
1.613     albertel 9020:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9021:     my ($tmp)=keys(%current_permissions);
                   9022:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9023:     return \%current_permissions;
                   9024: }
                   9025: 
                   9026: #---------------------------------------------Get portfolio file access controls
                   9027: 
1.749     raeburn  9028: sub get_access_controls {
1.745     raeburn  9029:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9030:     my %access;
                   9031:     my $real_file = $file;
                   9032:     $file =~ s/\.meta$//;
1.745     raeburn  9033:     if (defined($file)) {
1.749     raeburn  9034:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9035:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9036:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9037:             }
                   9038:         }
1.745     raeburn  9039:     } else {
1.749     raeburn  9040:         foreach my $key (keys(%{$current_permissions})) {
                   9041:             if ($key =~ /\0accesscontrol$/) {
                   9042:                 if (defined($group)) {
                   9043:                     if ($key !~ m-^\Q$group\E/-) {
                   9044:                         next;
                   9045:                     }
                   9046:                 }
                   9047:                 my ($fullpath) = split(/\0/,$key);
                   9048:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9049:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9050:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9051:                     }
                   9052:                 }
                   9053:             }
                   9054:         }
                   9055:     }
                   9056:     return %access;
                   9057: }
                   9058: 
                   9059: sub modify_access_controls {
                   9060:     my ($file_name,$changes,$domain,$user)=@_;
                   9061:     my ($outcome,$deloutcome);
                   9062:     my %store_permissions;
                   9063:     my %new_values;
                   9064:     my %new_control;
                   9065:     my %translation;
                   9066:     my @deletions = ();
                   9067:     my $now = time;
                   9068:     if (exists($$changes{'activate'})) {
                   9069:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9070:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9071:             my $numnew = scalar(@newitems);
                   9072:             for (my $i=0; $i<$numnew; $i++) {
                   9073:                 my $newkey = $newitems[$i];
                   9074:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9075:                 if ($newkey =~ /^\d+:/) { 
                   9076:                     $newkey =~ s/^(\d+)/$newid/;
                   9077:                     $translation{$1} = $newid;
                   9078:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9079:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9080:                     $translation{$1} = $newid;
                   9081:                 }
1.749     raeburn  9082:                 $new_values{$file_name."\0".$newkey} = 
                   9083:                                           $$changes{'activate'}{$newitems[$i]};
                   9084:                 $new_control{$newkey} = $now;
                   9085:             }
                   9086:         }
                   9087:     }
                   9088:     my %todelete;
                   9089:     my %changed_items;
                   9090:     foreach my $action ('delete','update') {
                   9091:         if (exists($$changes{$action})) {
                   9092:             if (ref($$changes{$action}) eq 'HASH') {
                   9093:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9094:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9095:                     if ($action eq 'delete') { 
                   9096:                         $todelete{$itemnum} = 1;
                   9097:                     } else {
                   9098:                         $changed_items{$itemnum} = $key;
                   9099:                     }
                   9100:                 }
1.745     raeburn  9101:             }
                   9102:         }
1.749     raeburn  9103:     }
                   9104:     # get lock on access controls for file.
                   9105:     my $lockhash = {
                   9106:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9107:                                                        ':'.$env{'user.domain'},
                   9108:                    }; 
                   9109:     my $tries = 0;
                   9110:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9111:    
                   9112:     while (($gotlock ne 'ok') && $tries <3) {
                   9113:         $tries ++;
                   9114:         sleep 1;
                   9115:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9116:     }
                   9117:     if ($gotlock eq 'ok') {
                   9118:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9119:         my ($tmp)=keys(%curr_permissions);
                   9120:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9121:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9122:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9123:             if (ref($curr_controls) eq 'HASH') {
                   9124:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9125:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9126:                     if (defined($todelete{$itemnum})) {
                   9127:                         push(@deletions,$file_name."\0".$control_item);
                   9128:                     } else {
                   9129:                         if (defined($changed_items{$itemnum})) {
                   9130:                             $new_control{$changed_items{$itemnum}} = $now;
                   9131:                             push(@deletions,$file_name."\0".$control_item);
                   9132:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9133:                         } else {
                   9134:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9135:                         }
                   9136:                     }
1.745     raeburn  9137:                 }
                   9138:             }
                   9139:         }
1.970     raeburn  9140:         my ($group);
                   9141:         if (&is_course($domain,$user)) {
                   9142:             ($group,my $file) = split(/\//,$file_name,2);
                   9143:         }
1.749     raeburn  9144:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9145:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9146:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9147:         #  remove lock
                   9148:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9149:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9150:         my $sqlresult =
1.970     raeburn  9151:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9152:                                     $group);
1.749     raeburn  9153:     } else {
                   9154:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9155:     }
1.749     raeburn  9156:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9157: }
                   9158: 
1.827     raeburn  9159: sub make_public_indefinitely {
                   9160:     my ($requrl) = @_;
                   9161:     my $now = time;
                   9162:     my $action = 'activate';
                   9163:     my $aclnum = 0;
                   9164:     if (&is_portfolio_url($requrl)) {
                   9165:         my (undef,$udom,$unum,$file_name,$group) =
                   9166:             &parse_portfolio_url($requrl);
                   9167:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9168:         my %access_controls = &get_access_controls($current_perms,
                   9169:                                                    $group,$file_name);
                   9170:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9171:             my ($num,$scope,$end,$start) = 
                   9172:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9173:             if ($scope eq 'public') {
                   9174:                 if ($start <= $now && $end == 0) {
                   9175:                     $action = 'none';
                   9176:                 } else {
                   9177:                     $action = 'update';
                   9178:                     $aclnum = $num;
                   9179:                 }
                   9180:                 last;
                   9181:             }
                   9182:         }
                   9183:         if ($action eq 'none') {
                   9184:              return 'ok';
                   9185:         } else {
                   9186:             my %changes;
                   9187:             my $newend = 0;
                   9188:             my $newstart = $now;
                   9189:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9190:             $changes{$action}{$newkey} = {
                   9191:                 type => 'public',
                   9192:                 time => {
                   9193:                     start => $newstart,
                   9194:                     end   => $newend,
                   9195:                 },
                   9196:             };
                   9197:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9198:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9199:             return $outcome;
                   9200:         }
                   9201:     } else {
                   9202:         return 'invalid';
                   9203:     }
                   9204: }
                   9205: 
1.745     raeburn  9206: #------------------------------------------------------Get Marked as Read Only
                   9207: 
                   9208: sub get_marked_as_readonly {
                   9209:     my ($domain,$user,$what,$group) = @_;
                   9210:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9211:     my @readonly_files;
1.629     banghart 9212:     my $cmp1=$what;
                   9213:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9214:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9215:         if (defined($group)) {
                   9216:             if ($file_name !~ m-^\Q$group\E/-) {
                   9217:                 next;
                   9218:             }
                   9219:         }
1.561     banghart 9220:         if (ref($value) eq "ARRAY"){
                   9221:             foreach my $stored_what (@{$value}) {
1.629     banghart 9222:                 my $cmp2=$stored_what;
1.759     albertel 9223:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9224:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9225:                 }
1.629     banghart 9226:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9227:                     push(@readonly_files, $file_name);
1.745     raeburn  9228:                     last;
1.563     banghart 9229:                 } elsif (!defined($what)) {
                   9230:                     push(@readonly_files, $file_name);
1.745     raeburn  9231:                     last;
1.561     banghart 9232:                 }
                   9233:             }
1.745     raeburn  9234:         }
1.561     banghart 9235:     }
                   9236:     return @readonly_files;
                   9237: }
1.577     banghart 9238: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9239: 
1.577     banghart 9240: sub get_marked_as_readonly_hash {
1.745     raeburn  9241:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9242:     my %readonly_files;
1.745     raeburn  9243:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9244:         if (defined($group)) {
                   9245:             if ($file_name !~ m-^\Q$group\E/-) {
                   9246:                 next;
                   9247:             }
                   9248:         }
1.577     banghart 9249:         if (ref($value) eq "ARRAY"){
                   9250:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9251:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9252:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9253:                         if ($lock_descriptor eq 'graded') {
                   9254:                             $readonly_files{$file_name} = 'graded';
                   9255:                         } elsif ($lock_descriptor eq 'handback') {
                   9256:                             $readonly_files{$file_name} = 'handback';
                   9257:                         } else {
                   9258:                             if (!exists($readonly_files{$file_name})) {
                   9259:                                 $readonly_files{$file_name} = 'locked';
                   9260:                             }
                   9261:                         }
1.745     raeburn  9262:                     }
1.750     banghart 9263:                 } 
1.577     banghart 9264:             }
                   9265:         } 
                   9266:     }
                   9267:     return %readonly_files;
                   9268: }
1.559     banghart 9269: # ------------------------------------------------------------ Unmark as Read Only
                   9270: 
                   9271: sub unmark_as_readonly {
1.629     banghart 9272:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9273:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9274:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9275:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9276:     my $symb_crs = $what;
                   9277:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9278:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9279:     my ($tmp)=keys(%current_permissions);
                   9280:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9281:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9282:     foreach my $file (@readonly_files) {
1.759     albertel 9283: 	my $clean_file = &declutter_portfile($file);
                   9284: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9285: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9286:         my @new_locks;
                   9287:         my @del_keys;
                   9288:         if (ref($current_locks) eq "ARRAY"){
                   9289:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9290:                 my $compare=$locker;
1.749     raeburn  9291:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9292:                     $compare=join('',@{$locker});
1.746     raeburn  9293:                     if ($compare ne $symb_crs) {
                   9294:                         push(@new_locks, $locker);
                   9295:                     }
1.563     banghart 9296:                 }
                   9297:             }
1.650     albertel 9298:             if (scalar(@new_locks) > 0) {
1.563     banghart 9299:                 $current_permissions{$file} = \@new_locks;
                   9300:             } else {
                   9301:                 push(@del_keys, $file);
1.613     albertel 9302:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9303:                 delete($current_permissions{$file});
1.563     banghart 9304:             }
                   9305:         }
1.561     banghart 9306:     }
1.613     albertel 9307:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9308:     return;
                   9309: }
1.512     banghart 9310: 
1.17      www      9311: # ------------------------------------------------------------ Directory lister
                   9312: 
                   9313: sub dirlist {
1.955     raeburn  9314:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9315:     $uri=~s/^\///;
                   9316:     $uri=~s/\/$//;
1.253     stredwic 9317:     my ($udom, $uname);
1.955     raeburn  9318:     if ($getuserdir) {
1.253     stredwic 9319:         $udom = $userdomain;
                   9320:         $uname = $username;
1.955     raeburn  9321:     } else {
                   9322:         (undef,$udom,$uname)=split(/\//,$uri);
                   9323:         if(defined($userdomain)) {
                   9324:             $udom = $userdomain;
                   9325:         }
                   9326:         if(defined($username)) {
                   9327:             $uname = $username;
                   9328:         }
1.253     stredwic 9329:     }
1.955     raeburn  9330:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9331: 
1.955     raeburn  9332:     $dirRoot = $perlvar{'lonDocRoot'};
                   9333:     if (defined($getpropath)) {
                   9334:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9335:         $dirRoot =~ s/\/$//;
1.955     raeburn  9336:     } elsif (defined($getuserdir)) {
                   9337:         my $subdir=$uname.'__';
                   9338:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9339:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9340:                    ."/$udom/$subdir/$uname";
                   9341:     } elsif (defined($alternateRoot)) {
                   9342:         $dirRoot = $alternateRoot;
1.751     banghart 9343:     }
1.253     stredwic 9344: 
                   9345:     if($udom) {
                   9346:         if($uname) {
1.1135    raeburn  9347:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9348:             if ($uhome eq 'no_host') {
                   9349:                 return ([],'no_host');
                   9350:             }
1.955     raeburn  9351:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9352:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9353:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9354:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9355:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9356:             } else {
                   9357:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9358:             }
1.605     matthew  9359:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9360:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9361:                 @listing_results = split(/:/,$listing);
                   9362:             } else {
                   9363:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9364:             }
1.1135    raeburn  9365:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9366:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9367:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9368:                 return ([],$listing);
                   9369:             } else {
                   9370:                 return (\@listing_results);
1.1135    raeburn  9371:             }
1.955     raeburn  9372:         } elsif(!$alternateRoot) {
1.1136    raeburn  9373:             my (%allusers,%listerror);
1.841     albertel 9374: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9375:  	    foreach my $tryserver (keys(%servers)) {
                   9376:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9377:                                   &escape($udom),$tryserver);
                   9378:                 if ($listing eq 'unknown_cmd') {
                   9379: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9380: 				      $udom, $tryserver);
                   9381:                 } else {
                   9382:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9383:                 }
1.841     albertel 9384: 		if ($listing eq 'unknown_cmd') {
                   9385: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9386: 				      $udom, $tryserver);
                   9387: 		    @listing_results = split(/:/,$listing);
                   9388: 		} else {
                   9389: 		    @listing_results =
                   9390: 			map { &unescape($_); } split(/:/,$listing);
                   9391: 		}
1.1136    raeburn  9392:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9393:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9394:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9395:                     $listerror{$tryserver} = $listing;
                   9396:                 } else {
1.841     albertel 9397: 		    foreach my $line (@listing_results) {
                   9398: 			my ($entry) = split(/&/,$line,2);
                   9399: 			$allusers{$entry} = 1;
                   9400: 		    }
                   9401: 		}
1.253     stredwic 9402:             }
1.1136    raeburn  9403:             my @alluserslist=();
1.800     albertel 9404:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9405:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9406:             }
1.1136    raeburn  9407:             return (\@alluserslist);
1.253     stredwic 9408:         } else {
1.1136    raeburn  9409:             return ([],'missing username');
1.253     stredwic 9410:         }
1.955     raeburn  9411:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9412:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9413:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9414:         return (\@all_domains);
1.955     raeburn  9415:     } else {
1.1136    raeburn  9416:         return ([],'missing domain');
1.275     stredwic 9417:     }
                   9418: }
                   9419: 
                   9420: # --------------------------------------------- GetFileTimestamp
                   9421: # This function utilizes dirlist and returns the date stamp for
                   9422: # when it was last modified.  It will also return an error of -1
                   9423: # if an error occurs
                   9424: 
                   9425: sub GetFileTimestamp {
1.955     raeburn  9426:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9427:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9428:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9429:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9430:                                     undef,$getuserdir);
                   9431:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9432:         return -1;
                   9433:     }
                   9434:     if (ref($fileref) eq 'ARRAY') {
                   9435:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9436:         # @stats contains first the filename, then the stat output
                   9437:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9438:     } else {
                   9439:         return -1;
1.253     stredwic 9440:     }
1.26      www      9441: }
                   9442: 
1.712     albertel 9443: sub stat_file {
                   9444:     my ($uri) = @_;
1.787     albertel 9445:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9446: 
1.955     raeburn  9447:     my ($udom,$uname,$file);
1.712     albertel 9448:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9449: 	($udom,$uname,$file) =
1.811     albertel 9450: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9451: 	$file = 'userfiles/'.$file;
                   9452:     }
                   9453:     if ($uri =~ m-^/res/-) {
                   9454: 	($udom,$uname) = 
1.807     albertel 9455: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9456: 	$file = $uri;
                   9457:     }
                   9458: 
                   9459:     if (!$udom || !$uname || !$file) {
                   9460: 	# unable to handle the uri
                   9461: 	return ();
                   9462:     }
1.956     raeburn  9463:     my $getpropath;
                   9464:     if ($file =~ /^userfiles\//) {
                   9465:         $getpropath = 1;
                   9466:     }
1.1136    raeburn  9467:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9468:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9469:         return ();
                   9470:     } else {
                   9471:         if (ref($listref) eq 'ARRAY') {
                   9472:             my @stats = split('&',$listref->[0]);
                   9473: 	    shift(@stats); #filename is first
                   9474: 	    return @stats;
                   9475:         }
1.712     albertel 9476:     }
                   9477:     return ();
                   9478: }
                   9479: 
1.26      www      9480: # -------------------------------------------------------- Value of a Condition
                   9481: 
1.713     albertel 9482: # gets the value of a specific preevaluated condition
                   9483: #    stored in the string  $env{user.state.<cid>}
                   9484: # or looks up a condition reference in the bighash and if if hasn't
                   9485: # already been evaluated recurses into docondval to get the value of
                   9486: # the condition, then memoizing it to 
                   9487: #   $env{user.state.<cid>.<condition>}
1.40      www      9488: sub directcondval {
                   9489:     my $number=shift;
1.620     albertel 9490:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9491: 	&Apache::lonuserstate::evalstate();
                   9492:     }
1.713     albertel 9493:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9494: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9495:     } elsif ($number =~ /^_/) {
                   9496: 	my $sub_condition;
                   9497: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9498: 		&GDBM_READER(),0640)) {
                   9499: 	    $sub_condition=$bighash{'conditions'.$number};
                   9500: 	    untie(%bighash);
                   9501: 	}
                   9502: 	my $value = &docondval($sub_condition);
1.949     raeburn  9503: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9504: 	return $value;
                   9505:     }
1.620     albertel 9506:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9507:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9508:     } else {
                   9509:        return 2;
                   9510:     }
                   9511: }
                   9512: 
1.713     albertel 9513: # get the collection of conditions for this resource
1.26      www      9514: sub condval {
                   9515:     my $condidx=shift;
1.54      www      9516:     my $allpathcond='';
1.713     albertel 9517:     foreach my $cond (split(/\|/,$condidx)) {
                   9518: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9519: 	    $allpathcond.=
                   9520: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9521: 	}
1.191     harris41 9522:     }
1.54      www      9523:     $allpathcond=~s/\|$//;
1.713     albertel 9524:     return &docondval($allpathcond);
                   9525: }
                   9526: 
                   9527: #evaluates an expression of conditions
                   9528: sub docondval {
                   9529:     my ($allpathcond) = @_;
                   9530:     my $result=0;
                   9531:     if ($env{'request.course.id'}
                   9532: 	&& defined($allpathcond)) {
                   9533: 	my $operand='|';
                   9534: 	my @stack;
                   9535: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9536: 	    if ($chunk eq '(') {
                   9537: 		push @stack,($operand,$result);
                   9538: 	    } elsif ($chunk eq ')') {
                   9539: 		my $before=pop @stack;
                   9540: 		if (pop @stack eq '&') {
                   9541: 		    $result=$result>$before?$before:$result;
                   9542: 		} else {
                   9543: 		    $result=$result>$before?$result:$before;
                   9544: 		}
                   9545: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9546: 		$operand=$chunk;
                   9547: 	    } else {
                   9548: 		my $new=directcondval($chunk);
                   9549: 		if ($operand eq '&') {
                   9550: 		    $result=$result>$new?$new:$result;
                   9551: 		} else {
                   9552: 		    $result=$result>$new?$result:$new;
                   9553: 		}
                   9554: 	    }
                   9555: 	}
1.26      www      9556:     }
                   9557:     return $result;
1.421     albertel 9558: }
                   9559: 
                   9560: # ---------------------------------------------------- Devalidate courseresdata
                   9561: 
                   9562: sub devalidatecourseresdata {
                   9563:     my ($coursenum,$coursedomain)=@_;
                   9564:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9565:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9566: }
                   9567: 
1.763     www      9568: 
1.200     www      9569: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9570: #
                   9571: #  Parameters:
                   9572: #      $coursenum    - Number of the course.
                   9573: #      $coursedomain - Domain at which the course was created.
                   9574: #  Returns:
                   9575: #     A hash of the course parameters along (I think) with timestamps
                   9576: #     and version info.
1.877     foxr     9577: 
1.624     albertel 9578: sub get_courseresdata {
                   9579:     my ($coursenum,$coursedomain)=@_;
1.200     www      9580:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9581:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9582:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9583:     my %dumpreply;
1.417     albertel 9584:     unless (defined($cached)) {
1.624     albertel 9585: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9586: 	$result=\%dumpreply;
1.251     albertel 9587: 	my ($tmp) = keys(%dumpreply);
                   9588: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9589: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9590: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9591: 	    return $tmp;
1.416     albertel 9592: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9593: 	    $result=undef;
1.599     albertel 9594: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9595: 	}
                   9596:     }
1.624     albertel 9597:     return $result;
                   9598: }
                   9599: 
1.633     albertel 9600: sub devalidateuserresdata {
                   9601:     my ($uname,$udom)=@_;
                   9602:     my $hashid="$udom:$uname";
                   9603:     &devalidate_cache_new('userres',$hashid);
                   9604: }
                   9605: 
1.624     albertel 9606: sub get_userresdata {
                   9607:     my ($uname,$udom)=@_;
                   9608:     #most student don\'t have any data set, check if there is some data
                   9609:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9610: 
                   9611:     my $hashid="$udom:$uname";
                   9612:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9613:     if (!defined($cached)) {
                   9614: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9615: 	$result=\%resourcedata;
                   9616: 	&do_cache_new('userres',$hashid,$result,600);
                   9617:     }
                   9618:     my ($tmp)=keys(%$result);
                   9619:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9620: 	return $result;
                   9621:     }
                   9622:     #error 2 occurs when the .db doesn't exist
                   9623:     if ($tmp!~/error: 2 /) {
1.672     albertel 9624: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9625: 		 " Trying to get resource data for ".
                   9626: 		 $uname." at ".$udom.": ".
                   9627: 		 $tmp."</font>");
                   9628:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9629: 	#&EXT_cache_set($udom,$uname);
                   9630: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9631: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9632:     }
                   9633:     return $tmp;
                   9634: }
1.879     foxr     9635: #----------------------------------------------- resdata - return resource data
                   9636: #  Purpose:
                   9637: #    Return resource data for either users or for a course.
                   9638: #  Parameters:
                   9639: #     $name      - Course/user name.
                   9640: #     $domain    - Name of the domain the user/course is registered on.
                   9641: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9642: #     @which     - Array of names of resources desired.
                   9643: #  Returns:
                   9644: #     The value of the first reasource in @which that is found in the
                   9645: #     resource hash.
                   9646: #  Exceptional Conditions:
                   9647: #     If the $type passed in is not valid (not the string 'course' or 
                   9648: #     'user', an undefined  reference is returned.
                   9649: #     If none of the resources are found, an undef is returned
1.624     albertel 9650: sub resdata {
                   9651:     my ($name,$domain,$type,@which)=@_;
                   9652:     my $result;
                   9653:     if ($type eq 'course') {
                   9654: 	$result=&get_courseresdata($name,$domain);
                   9655:     } elsif ($type eq 'user') {
                   9656: 	$result=&get_userresdata($name,$domain);
                   9657:     }
                   9658:     if (!ref($result)) { return $result; }    
1.251     albertel 9659:     foreach my $item (@which) {
1.927     albertel 9660: 	if (defined($result->{$item->[0]})) {
                   9661: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9662: 	}
1.250     albertel 9663:     }
1.291     albertel 9664:     return undef;
1.200     www      9665: }
                   9666: 
1.1236    raeburn  9667: sub get_numsuppfiles {
                   9668:     my ($cnum,$cdom,$ignorecache)=@_;
                   9669:     my $hashid=$cnum.':'.$cdom;
                   9670:     my ($suppcount,$cached);
                   9671:     unless ($ignorecache) {
                   9672:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9673:     }
                   9674:     unless (defined($cached)) {
                   9675:         my $chome=&homeserver($cnum,$cdom);
                   9676:         unless ($chome eq 'no_host') {
                   9677:             ($suppcount,my $errors) = (0,0);
                   9678:             my $suppmap = 'supplemental.sequence';
                   9679:             ($suppcount,$errors) = 
                   9680:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9681:         }
                   9682:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9683:     }
                   9684:     return $suppcount;
                   9685: }
                   9686: 
1.379     matthew  9687: #
                   9688: # EXT resource caching routines
                   9689: #
                   9690: 
                   9691: sub clear_EXT_cache_status {
1.383     albertel 9692:     &delenv('cache.EXT.');
1.379     matthew  9693: }
                   9694: 
                   9695: sub EXT_cache_status {
                   9696:     my ($target_domain,$target_user) = @_;
1.383     albertel 9697:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9698:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9699:         # We know already the user has no data
                   9700:         return 1;
                   9701:     } else {
                   9702:         return 0;
                   9703:     }
                   9704: }
                   9705: 
                   9706: sub EXT_cache_set {
                   9707:     my ($target_domain,$target_user) = @_;
1.383     albertel 9708:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9709:     #&appenv({$cachename => time});
1.379     matthew  9710: }
                   9711: 
1.28      www      9712: # --------------------------------------------------------- Value of a Variable
1.58      www      9713: sub EXT {
1.715     albertel 9714: 
1.1228    raeburn  9715:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9716:     unless ($varname) { return ''; }
1.218     albertel 9717:     #get real user name/domain, courseid and symb
                   9718:     my $courseid;
1.359     albertel 9719:     my $publicuser;
1.427     www      9720:     if ($symbparm) {
                   9721: 	$symbparm=&get_symb_from_alias($symbparm);
                   9722:     }
1.218     albertel 9723:     if (!($uname && $udom)) {
1.790     albertel 9724:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9725:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9726:     } else {
1.620     albertel 9727: 	$courseid=$env{'request.course.id'};
1.218     albertel 9728:     }
1.48      www      9729:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9730:     my $rest;
1.320     albertel 9731:     if (defined($therest[0])) {
1.48      www      9732:        $rest=join('.',@therest);
                   9733:     } else {
                   9734:        $rest='';
                   9735:     }
1.320     albertel 9736: 
1.57      www      9737:     my $qualifierrest=$qualifier;
                   9738:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9739:     my $spacequalifierrest=$space;
                   9740:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9741:     if ($realm eq 'user') {
1.48      www      9742: # --------------------------------------------------------------- user.resource
                   9743: 	if ($space eq 'resource') {
1.651     albertel 9744: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9745: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9746: 		 &&
1.744     albertel 9747: 		 ($symbparm eq &symbread()) ) {	
                   9748: 		# if we are in the middle of processing the resource the
                   9749: 		# get the value we are planning on committing
                   9750:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9751:                     return $Apache::lonhomework::results{$qualifierrest};
                   9752:                 } else {
                   9753:                     return $Apache::lonhomework::history{$qualifierrest};
                   9754:                 }
1.335     albertel 9755: 	    } else {
1.359     albertel 9756: 		my %restored;
1.620     albertel 9757: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9758: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9759: 		} else {
                   9760: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9761: 		}
1.335     albertel 9762: 		return $restored{$qualifierrest};
                   9763: 	    }
1.48      www      9764: # ----------------------------------------------------------------- user.access
                   9765:         } elsif ($space eq 'access') {
1.218     albertel 9766: 	    # FIXME - not supporting calls for a specific user
1.48      www      9767:             return &allowed($qualifier,$rest);
                   9768: # ------------------------------------------ user.preferences, user.environment
                   9769:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9770: 	    if (($uname eq $env{'user.name'}) &&
                   9771: 		($udom eq $env{'user.domain'})) {
                   9772: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9773: 	    } else {
1.359     albertel 9774: 		my %returnhash;
                   9775: 		if (!$publicuser) {
                   9776: 		    %returnhash=&userenvironment($udom,$uname,
                   9777: 						 $qualifierrest);
                   9778: 		}
1.218     albertel 9779: 		return $returnhash{$qualifierrest};
                   9780: 	    }
1.48      www      9781: # ----------------------------------------------------------------- user.course
                   9782:         } elsif ($space eq 'course') {
1.218     albertel 9783: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9784:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9785: # ------------------------------------------------------------------- user.role
                   9786:         } elsif ($space eq 'role') {
1.218     albertel 9787: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9788:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9789:             if ($qualifier eq 'value') {
                   9790: 		return $role;
                   9791:             } elsif ($qualifier eq 'extent') {
                   9792:                 return $where;
                   9793:             }
                   9794: # ----------------------------------------------------------------- user.domain
                   9795:         } elsif ($space eq 'domain') {
1.218     albertel 9796:             return $udom;
1.48      www      9797: # ------------------------------------------------------------------- user.name
                   9798:         } elsif ($space eq 'name') {
1.218     albertel 9799:             return $uname;
1.48      www      9800: # ---------------------------------------------------- Any other user namespace
1.29      www      9801:         } else {
1.359     albertel 9802: 	    my %reply;
                   9803: 	    if (!$publicuser) {
                   9804: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9805: 	    }
                   9806: 	    return $reply{$qualifierrest};
1.48      www      9807:         }
1.236     www      9808:     } elsif ($realm eq 'query') {
                   9809: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9810:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9811: 						[$spacequalifierrest]);
1.620     albertel 9812: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9813:    } elsif ($realm eq 'request') {
1.48      www      9814: # ------------------------------------------------------------- request.browser
                   9815:         if ($space eq 'browser') {
1.1145    bisitz   9816:             return $env{'browser.'.$qualifier};
1.57      www      9817: # ------------------------------------------------------------ request.filename
                   9818:         } else {
1.620     albertel 9819:             return $env{'request.'.$spacequalifierrest};
1.29      www      9820:         }
1.28      www      9821:     } elsif ($realm eq 'course') {
1.48      www      9822: # ---------------------------------------------------------- course.description
1.620     albertel 9823:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9824:     } elsif ($realm eq 'resource') {
1.165     www      9825: 
1.620     albertel 9826: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9827: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9828: 	}
1.693     albertel 9829: 
1.1232    raeburn  9830:         if ($qualifier eq '') {
                   9831: 	    if ($space eq 'title') {
                   9832: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9833: 	        return &gettitle($symbparm);
                   9834: 	    }
1.693     albertel 9835: 	
1.1232    raeburn  9836: 	    if ($space eq 'map') {
                   9837: 	        my ($map) = &decode_symb($symbparm);
                   9838: 	        return &symbread($map);
                   9839: 	    }
                   9840:             if ($space eq 'maptitle') {
                   9841:                 my ($map) = &decode_symb($symbparm);
                   9842:                 return &gettitle($map);
                   9843:             }
                   9844: 	    if ($space eq 'filename') {
                   9845: 	        if ($symbparm) {
                   9846: 		    return &clutter((&decode_symb($symbparm))[2]);
                   9847: 	        }
                   9848: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9849: 	    }
1.1232    raeburn  9850: 
1.1233    raeburn  9851:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   9852:                 if ($space eq 'visibleparts') {
                   9853:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9854:                     my $item;
                   9855:                     if (ref($navmap)) {
                   9856:                         my $res = $navmap->getBySymb($symbparm);
                   9857:                         my $parts = $res->parts();
                   9858:                         if (ref($parts) eq 'ARRAY') {
                   9859:                             $item = join(',',@{$parts});
                   9860:                         }
                   9861:                         undef($navmap);
1.1232    raeburn  9862:                     }
1.1233    raeburn  9863:                     return $item;
1.1232    raeburn  9864:                 }
                   9865:             }
                   9866:         }
1.693     albertel 9867: 
                   9868: 	my ($section, $group, @groups);
1.593     albertel 9869: 	my ($courselevelm,$courselevel);
1.1228    raeburn  9870:         if (($courseid eq '') && ($cid)) {
                   9871:             $courseid = $cid;
                   9872:         }
                   9873: 	if (($symbparm && $courseid) && 
                   9874: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      9875: 
1.218     albertel 9876: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9877: 
1.60      www      9878: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9879: 	    my $symbp=$symbparm;
1.735     albertel 9880: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9881: 
                   9882: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9883: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9884: 
1.620     albertel 9885: 	    if (($env{'user.name'} eq $uname) &&
                   9886: 		($env{'user.domain'} eq $udom)) {
                   9887: 		$section=$env{'request.course.sec'};
1.733     raeburn  9888:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9889:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9890: 	    } else {
1.539     albertel 9891: 		if (! defined($usection)) {
1.551     albertel 9892: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9893: 		} else {
                   9894: 		    $section = $usection;
                   9895: 		}
1.733     raeburn  9896:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9897: 	    }
                   9898: 
                   9899: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9900: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9901: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9902: 
1.593     albertel 9903: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9904: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9905: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9906: 
1.60      www      9907: # ----------------------------------------------------------- first, check user
1.624     albertel 9908: 
                   9909: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9910: 				       ([$courselevelr,'resource'],
                   9911: 					[$courselevelm,'map'     ],
                   9912: 					[$courselevel, 'course'  ]));
1.931     albertel 9913: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9914: 
1.594     albertel 9915: # ------------------------------------------------ second, check some of course
1.684     raeburn  9916:             my $coursereply;
1.691     raeburn  9917:             if (@groups > 0) {
                   9918:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9919:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9920:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9921:             }
1.96      www      9922: 
1.684     raeburn  9923: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9924: 				  $env{'course.'.$courseid.'.domain'},
                   9925: 				  'course',
                   9926: 				  ([$seclevelr,   'resource'],
                   9927: 				   [$seclevelm,   'map'     ],
                   9928: 				   [$seclevel,    'course'  ],
                   9929: 				   [$courselevelr,'resource']));
                   9930: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9931: 
1.60      www      9932: # ------------------------------------------------------ third, check map parms
1.218     albertel 9933: 	    my %parmhash=();
                   9934: 	    my $thisparm='';
                   9935: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9936: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9937: 		    &GDBM_READER(),0640)) {
1.218     albertel 9938: 		$thisparm=$parmhash{$symbparm};
                   9939: 		untie(%parmhash);
                   9940: 	    }
1.927     albertel 9941: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9942: 	}
1.594     albertel 9943: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9944: 
1.218     albertel 9945: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9946: 	my $filename;
                   9947: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9948: 	if ($symbparm) {
1.409     www      9949: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9950: 	} else {
1.620     albertel 9951: 	    $filename=$env{'request.filename'};
1.282     albertel 9952: 	}
                   9953: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9954: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9955: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9956: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9957: 
1.927     albertel 9958: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9959: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9960: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9961: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9962: 				     $env{'course.'.$courseid.'.domain'},
                   9963: 				     'course',
1.927     albertel 9964: 				     ([$courselevelm,'map'   ],
                   9965: 				      [$courselevel, 'course']));
                   9966: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9967: 	}
1.145     www      9968: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9969: 	unless ($space eq '0') {
1.336     albertel 9970: 	    my @parts=split(/_/,$space);
                   9971: 	    my $id=pop(@parts);
                   9972: 	    my $part=join('_',@parts);
                   9973: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9974: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9975: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9976: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9977: 	}
1.395     albertel 9978: 	if ($recurse) { return undef; }
                   9979: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9980: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9981: # ---------------------------------------------------- Any other user namespace
                   9982:     } elsif ($realm eq 'environment') {
                   9983: # ----------------------------------------------------------------- environment
1.620     albertel 9984: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9985: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9986: 	} else {
1.770     albertel 9987: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9988: 		return '';
                   9989: 	    }
1.219     albertel 9990: 	    my %returnhash=&userenvironment($udom,$uname,
                   9991: 					    $spacequalifierrest);
                   9992: 	    return $returnhash{$spacequalifierrest};
                   9993: 	}
1.28      www      9994:     } elsif ($realm eq 'system') {
1.48      www      9995: # ----------------------------------------------------------------- system.time
                   9996: 	if ($space eq 'time') {
                   9997: 	    return time;
                   9998:         }
1.696     albertel 9999:     } elsif ($realm eq 'server') {
                   10000: # ----------------------------------------------------------------- system.time
                   10001: 	if ($space eq 'name') {
                   10002: 	    return $ENV{'SERVER_NAME'};
                   10003:         }
1.28      www      10004:     }
1.48      www      10005:     return '';
1.61      www      10006: }
                   10007: 
1.927     albertel 10008: sub get_reply {
                   10009:     my ($reply_value) = @_;
1.940     raeburn  10010:     if (ref($reply_value) eq 'ARRAY') {
                   10011:         if (wantarray) {
                   10012: 	    return @$reply_value;
                   10013:         }
                   10014:         return $reply_value->[0];
                   10015:     } else {
                   10016:         return $reply_value;
1.927     albertel 10017:     }
                   10018: }
                   10019: 
1.691     raeburn  10020: sub check_group_parms {
                   10021:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10022:     my @groupitems = ();
                   10023:     my $resultitem;
1.927     albertel 10024:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10025:     foreach my $group (@{$groups}) {
                   10026:         foreach my $level (@levels) {
1.927     albertel 10027:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10028:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10029:         }
                   10030:     }
                   10031:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10032:                             $env{'course.'.$courseid.'.domain'},
                   10033:                                      'course',@groupitems);
                   10034:     return $coursereply;
                   10035: }
                   10036: 
                   10037: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10038:     my ($courseid,@groups) = @_;
                   10039:     @groups = sort(@groups);
1.691     raeburn  10040:     return @groups;
                   10041: }
                   10042: 
1.395     albertel 10043: sub packages_tab_default {
                   10044:     my ($uri,$varname)=@_;
                   10045:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10046: 
                   10047:     my (@extension,@specifics,$do_default);
                   10048:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10049: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10050: 	if ($pack_type eq 'default') {
                   10051: 	    $do_default=1;
                   10052: 	} elsif ($pack_type eq 'extension') {
                   10053: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10054: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10055: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10056: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10057: 	}
                   10058:     }
                   10059:     # first look for a package that matches the requested part id
                   10060:     foreach my $package (@specifics) {
                   10061: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10062: 	next if ($pack_part ne $part);
                   10063: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10064: 	    return $packagetab{"$pack_type&$name&default"};
                   10065: 	}
                   10066:     }
                   10067:     # look for any possible matching non extension_ package
                   10068:     foreach my $package (@specifics) {
                   10069: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10070: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10071: 	    return $packagetab{"$pack_type&$name&default"};
                   10072: 	}
1.585     albertel 10073: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10074: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10075: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10076: 	}
                   10077:     }
1.738     albertel 10078:     # look for any posible extension_ match
                   10079:     foreach my $package (@extension) {
                   10080: 	my ($package,$pack_type)=@{$package};
                   10081: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10082: 	    return $packagetab{"$pack_type&$name&default"};
                   10083: 	}
                   10084: 	if (defined($packagetab{$package."&$name&default"})) {
                   10085: 	    return $packagetab{$package."&$name&default"};
                   10086: 	}
                   10087:     }
                   10088:     # look for a global default setting
                   10089:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10090: 	return $packagetab{"default&$name&default"};
                   10091:     }
1.395     albertel 10092:     return undef;
                   10093: }
                   10094: 
1.334     albertel 10095: sub add_prefix_and_part {
                   10096:     my ($prefix,$part)=@_;
                   10097:     my $keyroot;
                   10098:     if (defined($prefix) && $prefix !~ /^__/) {
                   10099: 	# prefix that has a part already
                   10100: 	$keyroot=$prefix;
                   10101:     } elsif (defined($prefix)) {
                   10102: 	# prefix that is missing a part
                   10103: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10104:     } else {
                   10105: 	# no prefix at all
                   10106: 	if (defined($part)) { $keyroot='_'.$part; }
                   10107:     }
                   10108:     return $keyroot;
                   10109: }
                   10110: 
1.71      www      10111: # ---------------------------------------------------------------- Get metadata
                   10112: 
1.599     albertel 10113: my %metaentry;
1.1070    www      10114: my %importedpartids;
1.71      www      10115: sub metadata {
1.176     www      10116:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10117:     $uri=&declutter($uri);
1.288     albertel 10118:     # if it is a non metadata possible uri return quickly
1.529     albertel 10119:     if (($uri eq '') || 
                   10120: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10121: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10122:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10123: 	return undef;
                   10124:     }
1.1140    www      10125:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10126: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10127: 	return undef;
1.288     albertel 10128:     }
1.73      www      10129:     my $filename=$uri;
                   10130:     $uri=~s/\.meta$//;
1.172     www      10131: #
                   10132: # Is the metadata already cached?
1.177     www      10133: # Look at timestamp of caching
1.172     www      10134: # Everything is cached by the main uri, libraries are never directly cached
                   10135: #
1.428     albertel 10136:     if (!defined($liburi)) {
1.599     albertel 10137: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10138: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10139:     }
                   10140:     {
1.1069    www      10141: # Imported parts would go here
1.1070    www      10142:         my %importedids=();
                   10143:         my @origfileimportpartids=();
1.1069    www      10144:         my $importedparts=0;
1.172     www      10145: #
                   10146: # Is this a recursive call for a library?
                   10147: #
1.599     albertel 10148: #	if (! exists($metacache{$uri})) {
                   10149: #	    $metacache{$uri}={};
                   10150: #	}
1.924     albertel 10151: 	my $cachetime = 60*60;
1.171     www      10152:         if ($liburi) {
                   10153: 	    $liburi=&declutter($liburi);
                   10154:             $filename=$liburi;
1.401     bowersj2 10155:         } else {
1.599     albertel 10156: 	    &devalidate_cache_new('meta',$uri);
                   10157: 	    undef(%metaentry);
1.401     bowersj2 10158: 	}
1.140     www      10159:         my %metathesekeys=();
1.73      www      10160:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10161: 	my $metastring;
1.1140    www      10162: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10163: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10164: 	    $metastring = 
1.929     albertel 10165: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10166: 					  ('grade_target' => 'meta'));
                   10167: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10168: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10169:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10170: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10171: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10172: 	    $metastring=&getfile($file);
1.489     albertel 10173: 	}
1.208     albertel 10174:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10175:         my $token;
1.140     www      10176:         undef %metathesekeys;
1.71      www      10177:         while ($token=$parser->get_token) {
1.339     albertel 10178: 	    if ($token->[0] eq 'S') {
                   10179: 		if (defined($token->[2]->{'package'})) {
1.172     www      10180: #
                   10181: # This is a package - get package info
                   10182: #
1.339     albertel 10183: 		    my $package=$token->[2]->{'package'};
                   10184: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10185: 		    if (defined($token->[2]->{'id'})) { 
                   10186: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10187: 		    }
1.599     albertel 10188: 		    if ($metaentry{':packages'}) {
                   10189: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10190: 		    } else {
1.599     albertel 10191: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10192: 		    }
1.736     albertel 10193: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10194: 			my $part=$keyroot;
                   10195: 			$part=~s/^\_//;
1.736     albertel 10196: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10197: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10198: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10199: 			    # ignore package.tab specified default values
                   10200:                             # here &package_tab_default() will fetch those
                   10201: 			    if ($subp eq 'default') { next; }
1.736     albertel 10202: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10203: 			    my $unikey;
                   10204: 			    if ($pack =~ /_0$/) {
                   10205: 				$unikey='parameter_0_'.$name;
                   10206: 				$part=0;
                   10207: 			    } else {
                   10208: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10209: 			    }
1.339     albertel 10210: 			    if ($subp eq 'display') {
                   10211: 				$value.=' [Part: '.$part.']';
                   10212: 			    }
1.599     albertel 10213: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10214: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10215: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10216: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10217: 			    }
1.599     albertel 10218: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10219: 				$metaentry{':'.$unikey}=
                   10220: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10221: 			    }
1.339     albertel 10222: 			}
                   10223: 		    }
                   10224: 		} else {
1.172     www      10225: #
                   10226: # This is not a package - some other kind of start tag
1.339     albertel 10227: #
                   10228: 		    my $entry=$token->[1];
1.1068    www      10229: 		    my $unikey='';
1.175     www      10230: 
1.339     albertel 10231: 		    if ($entry eq 'import') {
1.175     www      10232: #
                   10233: # Importing a library here
1.339     albertel 10234: #
1.1067    www      10235:                         my $location=$parser->get_text('/import');
                   10236:                         my $dir=$filename;
                   10237:                         $dir=~s|[^/]*$||;
                   10238:                         $location=&filelocation($dir,$location);
1.1069    www      10239:                        
1.1068    www      10240:                         my $importmode=$token->[2]->{'importmode'};
                   10241:                         if ($importmode eq 'problem') {
1.1069    www      10242: # Import as problem/response
1.1068    www      10243:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10244:                         } elsif ($importmode eq 'part') {
                   10245: # Import as part(s)
1.1069    www      10246:                            $importedparts=1;
                   10247: # We need to get the original file and the imported file to get the part order correct
                   10248: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10249: # Load and inspect original file
1.1070    www      10250:                            if ($#origfileimportpartids<0) {
                   10251:                               undef(%importedpartids);
                   10252:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10253:                               my $origfile=&getfile($origfilelocation);
                   10254:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10255:                            }
                   10256: 
1.1069    www      10257: # Load and inspect imported file
                   10258:                            my $impfile=&getfile($location);
                   10259:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10260:                            if ($#impfilepartids>=0) {
                   10261: # This problem had parts
1.1070    www      10262:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10263:                            } else {
                   10264: # Importing by turning a single problem into a problem part
                   10265: # It gets the import-tags ID as part-ID
                   10266:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10267:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10268:                            }
1.1068    www      10269:                         } else {
                   10270: # Normal import
                   10271:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10272:                            if (defined($token->[2]->{'id'})) {
                   10273:                               $unikey.='_'.$token->[2]->{'id'};
                   10274:                            }
1.1067    www      10275:                         }
                   10276: 
1.339     albertel 10277: 			if ($depthcount<20) {
1.736     albertel 10278: 			    my $metadata = 
                   10279: 				&metadata($uri,'keys', $location,$unikey,
                   10280: 					  $depthcount+1);
                   10281: 			    foreach my $meta (split(',',$metadata)) {
                   10282: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10283: 				$metathesekeys{$meta}=1;
1.339     albertel 10284: 			    }
1.1068    www      10285: 			
                   10286:                         }
1.1067    www      10287: 		    } else {
                   10288: #
                   10289: # Not importing, some other kind of non-package, non-library start tag
                   10290: # 
                   10291:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10292:                         if (defined($token->[2]->{'id'})) {
                   10293:                             $unikey.='_'.$token->[2]->{'id'};
                   10294:                         }
1.339     albertel 10295: 			if (defined($token->[2]->{'name'})) { 
                   10296: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10297: 			}
                   10298: 			$metathesekeys{$unikey}=1;
1.736     albertel 10299: 			foreach my $param (@{$token->[3]}) {
                   10300: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10301: 				$token->[2]->{$param};
1.339     albertel 10302: 			}
                   10303: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10304: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10305: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10306: 		 # only ws inside the tag, and not in default, so use default
                   10307: 		 # as value
1.599     albertel 10308: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10309: 			} elsif ( $internaltext =~ /\S/ ) {
                   10310: 		  # something interesting inside the tag
                   10311: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10312: 			} else {
1.908     albertel 10313: 		  # no interesting values, don't set a default
1.339     albertel 10314: 			}
1.172     www      10315: # end of not-a-package not-a-library import
1.339     albertel 10316: 		    }
1.172     www      10317: # end of not-a-package start tag
1.339     albertel 10318: 		}
1.172     www      10319: # the next is the end of "start tag"
1.339     albertel 10320: 	    }
                   10321: 	}
1.483     albertel 10322: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10323: 	$extension = lc($extension);
                   10324: 	if ($extension eq 'htm') { $extension='html'; }
                   10325: 
1.737     albertel 10326: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10327: 	    #no specific packages #how's our extension
                   10328: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10329: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10330: 					 \%metathesekeys);
                   10331: 	}
1.883     albertel 10332: 
                   10333: 	if (!exists($metaentry{':packages'})
                   10334: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10335: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10336: 		#no specific packages well let's get default then
                   10337: 		if ($key!~/^default&/) { next; }
1.488     albertel 10338: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10339: 					     \%metathesekeys);
                   10340: 	    }
                   10341: 	}
1.338     www      10342: # are there custom rights to evaluate
1.599     albertel 10343: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10344: 
1.338     www      10345:     #
                   10346:     # Importing a rights file here
1.339     albertel 10347:     #
                   10348: 	    unless ($depthcount) {
1.599     albertel 10349: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10350: 		my $dir=$filename;
                   10351: 		$dir=~s|[^/]*$||;
                   10352: 		$location=&filelocation($dir,$location);
1.736     albertel 10353: 		my $rights_metadata =
                   10354: 		    &metadata($uri,'keys',$location,'_rights',
                   10355: 			      $depthcount+1);
                   10356: 		foreach my $rights (split(',',$rights_metadata)) {
                   10357: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10358: 		    $metathesekeys{$rights}=1;
1.339     albertel 10359: 		}
                   10360: 	    }
                   10361: 	}
1.737     albertel 10362: 	# uniqifiy package listing
                   10363: 	my %seen;
                   10364: 	my @uniq_packages =
                   10365: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10366: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10367: 
1.1070    www      10368:         if ($importedparts) {
                   10369: # We had imported parts and need to rebuild partorder
                   10370:            $metaentry{':partorder'}='';
                   10371:            $metathesekeys{'partorder'}=1;
                   10372:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10373:                if ($origfileimportpartids[$index] eq 'part') {
                   10374: # original part, part of the problem
                   10375:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10376:                } else {
                   10377: # we have imported parts at this position
                   10378:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10379:                }
                   10380:            }
                   10381:            $metaentry{':partorder'}=~s/^\,//;
                   10382:         }
                   10383: 
1.737     albertel 10384: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10385: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10386: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10387: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10388: # this is the end of "was not already recently cached
1.71      www      10389:     }
1.599     albertel 10390:     return $metaentry{':'.$what};
1.261     albertel 10391: }
                   10392: 
1.488     albertel 10393: sub metadata_create_package_def {
1.483     albertel 10394:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10395:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10396:     if ($subp eq 'default') { next; }
                   10397:     
1.599     albertel 10398:     if (defined($metaentry{':packages'})) {
                   10399: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10400:     } else {
1.599     albertel 10401: 	$metaentry{':packages'}=$package;
1.483     albertel 10402:     }
                   10403:     my $value=$packagetab{$key};
                   10404:     my $unikey;
                   10405:     $unikey='parameter_0_'.$name;
1.599     albertel 10406:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10407:     $$metathesekeys{$unikey}=1;
1.599     albertel 10408:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10409: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10410:     }
1.599     albertel 10411:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10412: 	$metaentry{':'.$unikey}=
                   10413: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10414:     }
                   10415: }
                   10416: 
1.261     albertel 10417: sub metadata_generate_part0 {
                   10418:     my ($metadata,$metacache,$uri) = @_;
                   10419:     my %allnames;
1.737     albertel 10420:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10421: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10422: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10423: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10424: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10425: 	    $allnames{$name}=$part;
                   10426: 	  }
                   10427: 	}
                   10428:     }
                   10429:     foreach my $name (keys(%allnames)) {
                   10430:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10431:       my $key=":parameter_0_$name";
1.261     albertel 10432:       $$metacache{"$key.part"}='0';
                   10433:       $$metacache{"$key.name"}=$name;
1.428     albertel 10434:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10435: 					   $allnames{$name}.'_'.$name.
                   10436: 					   '.type'};
1.428     albertel 10437:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10438: 			     '.display'};
1.644     www      10439:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10440:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10441:       $$metacache{"$key.display"}=$olddis;
                   10442:     }
1.71      www      10443: }
                   10444: 
1.764     albertel 10445: # ------------------------------------------------------ Devalidate title cache
                   10446: 
                   10447: sub devalidate_title_cache {
                   10448:     my ($url)=@_;
                   10449:     if (!$env{'request.course.id'}) { return; }
                   10450:     my $symb=&symbread($url);
                   10451:     if (!$symb) { return; }
                   10452:     my $key=$env{'request.course.id'}."\0".$symb;
                   10453:     &devalidate_cache_new('title',$key);
                   10454: }
                   10455: 
1.1014    droeschl 10456: # ------------------------------------------------- Get the title of a course
                   10457: 
                   10458: sub current_course_title {
                   10459:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10460: }
1.301     www      10461: # ------------------------------------------------- Get the title of a resource
                   10462: 
                   10463: sub gettitle {
                   10464:     my $urlsymb=shift;
                   10465:     my $symb=&symbread($urlsymb);
1.534     albertel 10466:     if ($symb) {
1.620     albertel 10467: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10468: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10469: 	if (defined($cached)) { 
                   10470: 	    return $result;
                   10471: 	}
1.534     albertel 10472: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10473: 	my $title='';
1.907     albertel 10474: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10475: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10476: 	} else {
                   10477: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10478: 		    &GDBM_READER(),0640)) {
                   10479: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10480: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10481: 		untie(%bighash);
                   10482: 	    }
1.534     albertel 10483: 	}
                   10484: 	$title=~s/\&colon\;/\:/gs;
                   10485: 	if ($title) {
1.1159    www      10486: # Remember both $symb and $title for dynamic metadata
                   10487:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10488:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10489: # Cache this title and then return it
1.599     albertel 10490: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10491: 	}
                   10492: 	$urlsymb=$url;
                   10493:     }
                   10494:     my $title=&metadata($urlsymb,'title');
                   10495:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10496:     return $title;
1.301     www      10497: }
1.613     albertel 10498: 
1.614     albertel 10499: sub get_slot {
                   10500:     my ($which,$cnum,$cdom)=@_;
                   10501:     if (!$cnum || !$cdom) {
1.790     albertel 10502: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10503: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10504: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10505:     }
1.703     albertel 10506:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10507:     my %slotinfo;
                   10508:     if (exists($remembered{$key})) {
                   10509: 	$slotinfo{$which} = $remembered{$key};
                   10510:     } else {
                   10511: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10512: 	&Apache::lonhomework::showhash(%slotinfo);
                   10513: 	my ($tmp)=keys(%slotinfo);
                   10514: 	if ($tmp=~/^error:/) { return (); }
                   10515: 	$remembered{$key} = $slotinfo{$which};
                   10516:     }
1.616     albertel 10517:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10518: 	return %{$slotinfo{$which}};
                   10519:     }
                   10520:     return $slotinfo{$which};
1.614     albertel 10521: }
1.1150    raeburn  10522: 
                   10523: sub get_reservable_slots {
                   10524:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10525:     my $now = time;
                   10526:     my $reservable_info;
                   10527:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10528:     if (exists($remembered{$key})) {
                   10529:         $reservable_info = $remembered{$key};
                   10530:     } else {
                   10531:         my %resv;
                   10532:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10533:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10534:         $reservable_info = \%resv;
                   10535:         $remembered{$key} = $reservable_info;
                   10536:     }
                   10537:     return $reservable_info;
                   10538: }
                   10539: 
                   10540: sub get_course_slots {
                   10541:     my ($cnum,$cdom) = @_;
                   10542:     my $hashid=$cnum.':'.$cdom;
                   10543:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10544:     if (defined($cached)) {
                   10545:         if (ref($result) eq 'HASH') {
                   10546:             return %{$result};
                   10547:         }
                   10548:     } else {
                   10549:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10550:         my ($tmp) = keys(%slots);
                   10551:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10552:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10553:             return %slots;
                   10554:         }
                   10555:     }
                   10556:     return;
                   10557: }
                   10558: 
                   10559: sub devalidate_slots_cache {
                   10560:     my ($cnum,$cdom)=@_;
                   10561:     my $hashid=$cnum.':'.$cdom;
                   10562:     &devalidate_cache_new('allslots',$hashid);
                   10563: }
                   10564: 
1.1181    raeburn  10565: sub get_coursechange {
                   10566:     my ($cdom,$cnum) = @_;
                   10567:     if ($cdom eq '' || $cnum eq '') {
                   10568:         return unless ($env{'request.course.id'});
                   10569:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10570:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10571:     }
                   10572:     my $hashid=$cdom.'_'.$cnum;
                   10573:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10574:     if ((defined($cached)) && ($change ne '')) {
                   10575:         return $change;
                   10576:     } else {
                   10577:         my %crshash;
                   10578:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10579:         if ($crshash{'internal.contentchange'} eq '') {
                   10580:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10581:             if ($change eq '') {
                   10582:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10583:                 $change = $crshash{'internal.created'};
                   10584:             }
                   10585:         } else {
                   10586:             $change = $crshash{'internal.contentchange'};
                   10587:         }
                   10588:         my $cachetime = 600;
                   10589:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10590:     }
                   10591:     return $change;
                   10592: }
                   10593: 
                   10594: sub devalidate_coursechange_cache {
                   10595:     my ($cnum,$cdom)=@_;
                   10596:     my $hashid=$cnum.':'.$cdom;
                   10597:     &devalidate_cache_new('crschange',$hashid);
                   10598: }
                   10599: 
1.31      www      10600: # ------------------------------------------------- Update symbolic store links
                   10601: 
                   10602: sub symblist {
                   10603:     my ($mapname,%newhash)=@_;
1.438     www      10604:     $mapname=&deversion(&declutter($mapname));
1.31      www      10605:     my %hash;
1.620     albertel 10606:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10607:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10608:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10609: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10610: 		next if ($url eq 'last_known'
                   10611: 			 && $env{'form.no_update_last_known'});
                   10612: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10613: 						    $newhash{$url}->[1],
                   10614: 						    $newhash{$url}->[0]);
1.191     harris41 10615:             }
1.31      www      10616:             if (untie(%hash)) {
                   10617: 		return 'ok';
                   10618:             }
                   10619:         }
                   10620:     }
                   10621:     return 'error';
1.212     www      10622: }
                   10623: 
                   10624: # --------------------------------------------------------------- Verify a symb
                   10625: 
                   10626: sub symbverify {
1.1190    raeburn  10627:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10628:     my $thisfn=$thisurl;
1.439     www      10629:     $thisfn=&declutter($thisfn);
1.215     www      10630: # direct jump to resource in page or to a sequence - will construct own symbs
                   10631:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10632: # check URL part
1.409     www      10633:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10634: 
1.431     www      10635:     unless ($url eq $thisfn) { return 0; }
1.213     www      10636: 
1.216     www      10637:     $symb=&symbclean($symb);
1.510     www      10638:     $thisurl=&deversion($thisurl);
1.439     www      10639:     $thisfn=&deversion($thisfn);
1.213     www      10640: 
                   10641:     my %bighash;
                   10642:     my $okay=0;
1.431     www      10643: 
1.620     albertel 10644:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10645:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10646:         my $noclutter;
1.1032    raeburn  10647:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10648:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10649:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10650:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10651:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10652:                 $noclutter = 1;
                   10653:             }
                   10654:         }
                   10655:         my $ids;
                   10656:         if ($noclutter) {
                   10657:             $ids=$bighash{'ids_'.$thisurl};
                   10658:         } else {
                   10659:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10660:         }
1.1102    raeburn  10661:         unless ($ids) {
                   10662:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10663:             $ids=$bighash{$idkey};
1.216     www      10664:         }
                   10665:         if ($ids) {
                   10666: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10667:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10668:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10669:             }
1.800     albertel 10670: 	    foreach my $id (split(/\,/,$ids)) {
                   10671: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10672:                if (
                   10673:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10674:    eq $symb) {
                   10675:                    if (ref($encstate)) {
                   10676:                        $$encstate = $bighash{'encrypted_'.$id};
                   10677:                    }
1.620     albertel 10678: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10679: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10680:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10681: 		       $okay=1;
1.1202    raeburn  10682:                        last;
1.582     albertel 10683: 		   }
                   10684: 	       }
1.216     www      10685: 	   }
                   10686:         }
1.213     www      10687: 	untie(%bighash);
                   10688:     }
                   10689:     return $okay;
1.31      www      10690: }
                   10691: 
1.210     www      10692: # --------------------------------------------------------------- Clean-up symb
                   10693: 
                   10694: sub symbclean {
                   10695:     my $symb=shift;
1.568     albertel 10696:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10697: # remove version from map
                   10698:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10699: 
1.210     www      10700: # remove version from URL
                   10701:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10702: 
1.507     www      10703: # remove wrapper
                   10704: 
1.510     www      10705:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10706:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10707:     return $symb;
1.409     www      10708: }
                   10709: 
                   10710: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10711: 
                   10712: sub encode_symb {
                   10713:     my ($map,$resid,$url)=@_;
                   10714:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10715: }
1.409     www      10716: 
                   10717: sub decode_symb {
1.568     albertel 10718:     my $symb=shift;
                   10719:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10720:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10721:     return (&fixversion($map),$resid,&fixversion($url));
                   10722: }
                   10723: 
                   10724: sub fixversion {
                   10725:     my $fn=shift;
1.609     banghart 10726:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10727:     my %bighash;
                   10728:     my $uri=&clutter($fn);
1.620     albertel 10729:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10730: # is this cached?
1.599     albertel 10731:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10732:     if (defined($cached)) { return $result; }
                   10733: # unfortunately not cached, or expired
1.620     albertel 10734:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10735: 	    &GDBM_READER(),0640)) {
                   10736:  	if ($bighash{'version_'.$uri}) {
                   10737:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10738:  	    unless (($version eq 'mostrecent') || 
                   10739: 		    ($version==&getversion($uri))) {
1.440     www      10740:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10741:  	    }
                   10742:  	}
                   10743:  	untie %bighash;
1.413     www      10744:     }
1.599     albertel 10745:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10746: }
                   10747: 
                   10748: sub deversion {
                   10749:     my $url=shift;
                   10750:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10751:     return $url;
1.210     www      10752: }
                   10753: 
1.31      www      10754: # ------------------------------------------------------ Return symb list entry
                   10755: 
                   10756: sub symbread {
1.249     www      10757:     my ($thisfn,$donotrecurse)=@_;
1.1206    raeburn  10758:     my $cache_str;
                   10759:     if ($thisfn ne '') {
                   10760:         $cache_str='request.symbread.cached.'.$thisfn;
                   10761:         if ($env{$cache_str} ne '') {
1.1179    raeburn  10762:             return $env{$cache_str};
                   10763:         }
1.1206    raeburn  10764:     } else {
1.242     www      10765: # no filename provided? try from environment
1.620     albertel 10766:         if ($env{'request.symb'}) {
                   10767: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10768: 	}
1.620     albertel 10769: 	$thisfn=$env{'request.filename'};
1.44      www      10770:     }
1.569     albertel 10771:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10772: # is that filename actually a symb? Verify, clean, and return
                   10773:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10774: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10775: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10776: 	}
1.242     www      10777:     }
1.44      www      10778:     $thisfn=declutter($thisfn);
1.31      www      10779:     my %hash;
1.37      www      10780:     my %bighash;
                   10781:     my $syval='';
1.620     albertel 10782:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10783:         my $targetfn = $thisfn;
1.609     banghart 10784:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10785:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10786:         }
1.687     albertel 10787: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10788: 	    $targetfn=$1;
                   10789: 	}
1.620     albertel 10790:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10791:                       &GDBM_READER(),0640)) {
1.481     raeburn  10792: 	    $syval=$hash{$targetfn};
1.37      www      10793:             untie(%hash);
                   10794:         }
                   10795: # ---------------------------------------------------------- There was an entry
                   10796:         if ($syval) {
1.601     albertel 10797: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10798: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10799: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10800: 		    #return $env{$cache_str}='';
1.601     albertel 10801: 		#}    
                   10802: 		#$syval.=$1;
                   10803: 	    #}
1.37      www      10804:         } else {
                   10805: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10806:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10807:                             &GDBM_READER(),0640)) {
1.37      www      10808: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10809:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10810:               unless ($ids) { 
                   10811:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10812:               }
                   10813:               unless ($ids) {
                   10814: # alias?
                   10815: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10816:               }
1.37      www      10817:               if ($ids) {
                   10818: # ------------------------------------------------------------------- Has ID(s)
                   10819:                  my @possibilities=split(/\,/,$ids);
1.39      www      10820:                  if ($#possibilities==0) {
                   10821: # ----------------------------------------------- There is only one possibility
1.37      www      10822: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10823: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10824: 						    $resid,$thisfn);
1.249     www      10825:                  } elsif (!$donotrecurse) {
1.39      www      10826: # ------------------------------------------ There is more than one possibility
                   10827:                      my $realpossible=0;
1.800     albertel 10828:                      foreach my $id (@possibilities) {
                   10829: 			 my $file=$bighash{'src_'.$id};
1.39      www      10830:                          if (&allowed('bre',$file)) {
1.800     albertel 10831:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10832:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10833: 				$realpossible++;
1.626     albertel 10834:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10835: 						    $resid,$thisfn);
1.39      www      10836:                             }
                   10837: 			 }
1.191     harris41 10838:                      }
1.39      www      10839: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10840:                  } else {
                   10841:                      $syval='';
1.37      www      10842:                  }
                   10843: 	      }
                   10844:               untie(%bighash)
1.481     raeburn  10845:            }
1.31      www      10846:         }
1.62      www      10847:         if ($syval) {
1.620     albertel 10848: 	    return $env{$cache_str}=$syval;
1.62      www      10849:         }
1.31      www      10850:     }
1.949     raeburn  10851:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10852:     return $env{$cache_str}='';
1.31      www      10853: }
                   10854: 
                   10855: # ---------------------------------------------------------- Return random seed
                   10856: 
1.32      www      10857: sub numval {
                   10858:     my $txt=shift;
                   10859:     $txt=~tr/A-J/0-9/;
                   10860:     $txt=~tr/a-j/0-9/;
                   10861:     $txt=~tr/K-T/0-9/;
                   10862:     $txt=~tr/k-t/0-9/;
                   10863:     $txt=~tr/U-Z/0-5/;
                   10864:     $txt=~tr/u-z/0-5/;
                   10865:     $txt=~s/\D//g;
1.564     albertel 10866:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10867:     return int($txt);
1.368     albertel 10868: }
                   10869: 
1.484     albertel 10870: sub numval2 {
                   10871:     my $txt=shift;
                   10872:     $txt=~tr/A-J/0-9/;
                   10873:     $txt=~tr/a-j/0-9/;
                   10874:     $txt=~tr/K-T/0-9/;
                   10875:     $txt=~tr/k-t/0-9/;
                   10876:     $txt=~tr/U-Z/0-5/;
                   10877:     $txt=~tr/u-z/0-5/;
                   10878:     $txt=~s/\D//g;
                   10879:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10880:     my $total;
                   10881:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10882:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10883:     return int($total);
                   10884: }
                   10885: 
1.575     albertel 10886: sub numval3 {
                   10887:     use integer;
                   10888:     my $txt=shift;
                   10889:     $txt=~tr/A-J/0-9/;
                   10890:     $txt=~tr/a-j/0-9/;
                   10891:     $txt=~tr/K-T/0-9/;
                   10892:     $txt=~tr/k-t/0-9/;
                   10893:     $txt=~tr/U-Z/0-5/;
                   10894:     $txt=~tr/u-z/0-5/;
                   10895:     $txt=~s/\D//g;
                   10896:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10897:     my $total;
                   10898:     foreach my $val (@txts) { $total+=$val; }
                   10899:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10900:     return $total;
                   10901: }
                   10902: 
1.675     albertel 10903: sub digest {
                   10904:     my ($data)=@_;
                   10905:     my $digest=&Digest::MD5::md5($data);
                   10906:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10907:     my ($e,$f);
                   10908:     {
                   10909:         use integer;
                   10910:         $e=($a+$b);
                   10911:         $f=($c+$d);
                   10912:         if ($_64bit) {
                   10913:             $e=(($e<<32)>>32);
                   10914:             $f=(($f<<32)>>32);
                   10915:         }
                   10916:     }
                   10917:     if (wantarray) {
                   10918: 	return ($e,$f);
                   10919:     } else {
                   10920: 	my $g;
                   10921: 	{
                   10922: 	    use integer;
                   10923: 	    $g=($e+$f);
                   10924: 	    if ($_64bit) {
                   10925: 		$g=(($g<<32)>>32);
                   10926: 	    }
                   10927: 	}
                   10928: 	return $g;
                   10929:     }
                   10930: }
                   10931: 
1.368     albertel 10932: sub latest_rnd_algorithm_id {
1.675     albertel 10933:     return '64bit5';
1.366     albertel 10934: }
1.32      www      10935: 
1.503     albertel 10936: sub get_rand_alg {
                   10937:     my ($courseid)=@_;
1.790     albertel 10938:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10939:     if ($courseid) {
1.620     albertel 10940: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10941:     }
                   10942:     return &latest_rnd_algorithm_id();
                   10943: }
                   10944: 
1.562     albertel 10945: sub validCODE {
                   10946:     my ($CODE)=@_;
                   10947:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10948:     return 0;
                   10949: }
                   10950: 
1.491     albertel 10951: sub getCODE {
1.620     albertel 10952:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10953:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10954: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10955: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10956: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10957:     }
                   10958:     return undef;
                   10959: }
1.1133    foxr     10960: #
                   10961: #  Determines the random seed for a specific context:
                   10962: #
                   10963: # parameters:
                   10964: #   symb      - in course context the symb for the seed.
                   10965: #   course_id - The course id of the form domain_coursenum.
                   10966: #   domain    - Domain for the user.
                   10967: #   course    - Course for the user.
                   10968: #   cenv      - environment of the course.
                   10969: #
                   10970: # NOTE:
                   10971: #   All parameters are picked out of the environment if missing
                   10972: #   or not defined.
                   10973: #   If a symb cannot be determined the current time is used instead.
                   10974: #
                   10975: #  For a given well defined symb, courside, domain, username,
                   10976: #  and course environment, the seed is reproducible.
                   10977: #
1.31      www      10978: sub rndseed {
1.1133    foxr     10979:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10980:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10981:     if (!defined($symb)) {
1.366     albertel 10982: 	unless ($symb=$wsymb) { return time; }
                   10983:     }
1.1146    foxr     10984:     if (!defined $courseid) { 
                   10985: 	$courseid=$wcourseid; 
                   10986:     }
                   10987:     if (!defined $domain) { $domain=$wdomain; }
                   10988:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10989: 
                   10990:     my $which;
                   10991:     if (defined($cenv->{'rndseed'})) {
                   10992: 	$which = $cenv->{'rndseed'};
                   10993:     } else {
                   10994: 	$which =&get_rand_alg($courseid);
                   10995:     }
1.491     albertel 10996:     if (defined(&getCODE())) {
1.1133    foxr     10997: 
1.675     albertel 10998: 	if ($which eq '64bit5') {
                   10999: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11000: 	} elsif ($which eq '64bit4') {
1.575     albertel 11001: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11002: 	} else {
                   11003: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11004: 	}
1.675     albertel 11005:     } elsif ($which eq '64bit5') {
                   11006: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11007:     } elsif ($which eq '64bit4') {
                   11008: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11009:     } elsif ($which eq '64bit3') {
                   11010: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11011:     } elsif ($which eq '64bit2') {
                   11012: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11013:     } elsif ($which eq '64bit') {
                   11014: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11015:     }
                   11016:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11017: }
                   11018: 
                   11019: sub rndseed_32bit {
                   11020:     my ($symb,$courseid,$domain,$username)=@_;
                   11021:     {
                   11022: 	use integer;
                   11023: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11024: 	my $symbseed=numval($symb) << 22;
                   11025: 	my $namechck=unpack("%32C*",$username) << 17;
                   11026: 	my $nameseed=numval($username) << 12;
                   11027: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11028: 	my $courseseed=unpack("%32C*",$courseid);
                   11029: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11030: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11031: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11032: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11033: 	return $num;
                   11034:     }
                   11035: }
                   11036: 
                   11037: sub rndseed_64bit {
                   11038:     my ($symb,$courseid,$domain,$username)=@_;
                   11039:     {
                   11040: 	use integer;
                   11041: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11042: 	my $symbseed=numval($symb) << 10;
                   11043: 	my $namechck=unpack("%32S*",$username);
                   11044: 	
                   11045: 	my $nameseed=numval($username) << 21;
                   11046: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11047: 	my $courseseed=unpack("%32S*",$courseid);
                   11048: 	
                   11049: 	my $num1=$symbchck+$symbseed+$namechck;
                   11050: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11051: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11052: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11053: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11054: 	return "$num1,$num2";
1.155     albertel 11055:     }
1.366     albertel 11056: }
                   11057: 
1.443     albertel 11058: sub rndseed_64bit2 {
                   11059:     my ($symb,$courseid,$domain,$username)=@_;
                   11060:     {
                   11061: 	use integer;
                   11062: 	# strings need to be an even # of cahracters long, it it is odd the
                   11063:         # last characters gets thrown away
                   11064: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11065: 	my $symbseed=numval($symb) << 10;
                   11066: 	my $namechck=unpack("%32S*",$username.' ');
                   11067: 	
                   11068: 	my $nameseed=numval($username) << 21;
1.501     albertel 11069: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11070: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11071: 	
                   11072: 	my $num1=$symbchck+$symbseed+$namechck;
                   11073: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11074: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11075: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11076: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11077: 	return "$num1,$num2";
                   11078:     }
                   11079: }
                   11080: 
                   11081: sub rndseed_64bit3 {
                   11082:     my ($symb,$courseid,$domain,$username)=@_;
                   11083:     {
                   11084: 	use integer;
                   11085: 	# strings need to be an even # of cahracters long, it it is odd the
                   11086:         # last characters gets thrown away
                   11087: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11088: 	my $symbseed=numval2($symb) << 10;
                   11089: 	my $namechck=unpack("%32S*",$username.' ');
                   11090: 	
                   11091: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11092: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11093: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11094: 	
                   11095: 	my $num1=$symbchck+$symbseed+$namechck;
                   11096: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11097: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11098: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11099: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11100: 	
1.503     albertel 11101: 	return "$num1:$num2";
1.443     albertel 11102:     }
                   11103: }
                   11104: 
1.575     albertel 11105: sub rndseed_64bit4 {
                   11106:     my ($symb,$courseid,$domain,$username)=@_;
                   11107:     {
                   11108: 	use integer;
                   11109: 	# strings need to be an even # of cahracters long, it it is odd the
                   11110:         # last characters gets thrown away
                   11111: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11112: 	my $symbseed=numval3($symb) << 10;
                   11113: 	my $namechck=unpack("%32S*",$username.' ');
                   11114: 	
                   11115: 	my $nameseed=numval3($username) << 21;
                   11116: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11117: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11118: 	
                   11119: 	my $num1=$symbchck+$symbseed+$namechck;
                   11120: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11121: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11122: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11123: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11124: 	
1.575     albertel 11125: 	return "$num1:$num2";
                   11126:     }
                   11127: }
                   11128: 
1.675     albertel 11129: sub rndseed_64bit5 {
                   11130:     my ($symb,$courseid,$domain,$username)=@_;
                   11131:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11132:     return "$num1:$num2";
                   11133: }
                   11134: 
1.366     albertel 11135: sub rndseed_CODE_64bit {
                   11136:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11137:     {
1.366     albertel 11138: 	use integer;
1.443     albertel 11139: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11140: 	my $symbseed=numval2($symb);
1.491     albertel 11141: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11142: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11143: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11144: 	my $num1=$symbseed+$CODEchck;
                   11145: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11146: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11147: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11148: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11149: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11150: 	return "$num1:$num2";
1.366     albertel 11151:     }
                   11152: }
                   11153: 
1.575     albertel 11154: sub rndseed_CODE_64bit4 {
                   11155:     my ($symb,$courseid,$domain,$username)=@_;
                   11156:     {
                   11157: 	use integer;
                   11158: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11159: 	my $symbseed=numval3($symb);
                   11160: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11161: 	my $CODEseed=numval3(&getCODE());
                   11162: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11163: 	my $num1=$symbseed+$CODEchck;
                   11164: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11165: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11166: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11167: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11168: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11169: 	return "$num1:$num2";
                   11170:     }
                   11171: }
                   11172: 
1.675     albertel 11173: sub rndseed_CODE_64bit5 {
                   11174:     my ($symb,$courseid,$domain,$username)=@_;
                   11175:     my $code = &getCODE();
                   11176:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11177:     return "$num1:$num2";
                   11178: }
                   11179: 
1.366     albertel 11180: sub setup_random_from_rndseed {
                   11181:     my ($rndseed)=@_;
1.503     albertel 11182:     if ($rndseed =~/([,:])/) {
                   11183: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11184: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11185:     } else {
                   11186: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11187:     }
1.36      albertel 11188: }
                   11189: 
1.474     albertel 11190: sub latest_receipt_algorithm_id {
1.835     albertel 11191:     return 'receipt3';
1.474     albertel 11192: }
                   11193: 
1.480     www      11194: sub recunique {
                   11195:     my $fucourseid=shift;
                   11196:     my $unique;
1.835     albertel 11197:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11198: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11199: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11200:     } else {
                   11201: 	$unique=$perlvar{'lonReceipt'};
                   11202:     }
                   11203:     return unpack("%32C*",$unique);
                   11204: }
                   11205: 
                   11206: sub recprefix {
                   11207:     my $fucourseid=shift;
                   11208:     my $prefix;
1.835     albertel 11209:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11210: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11211: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11212:     } else {
                   11213: 	$prefix=$perlvar{'lonHostID'};
                   11214:     }
                   11215:     return unpack("%32C*",$prefix);
                   11216: }
                   11217: 
1.76      www      11218: sub ireceipt {
1.474     albertel 11219:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11220: 
                   11221:     my $return =&recprefix($fucourseid).'-';
                   11222: 
                   11223:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11224: 	$env{'request.state'} eq 'construct') {
                   11225: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11226: 	return $return;
                   11227:     }
                   11228: 
1.76      www      11229:     my $cuname=unpack("%32C*",$funame);
                   11230:     my $cudom=unpack("%32C*",$fudom);
                   11231:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11232:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11233:     my $cunique=&recunique($fucourseid);
1.474     albertel 11234:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11235:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11236: 
1.790     albertel 11237: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11238: 			       
                   11239: 	$return.= ($cunique%$cuname+
                   11240: 		   $cunique%$cudom+
                   11241: 		   $cusymb%$cuname+
                   11242: 		   $cusymb%$cudom+
                   11243: 		   $cucourseid%$cuname+
                   11244: 		   $cucourseid%$cudom+
                   11245: 		   $cpart%$cuname+
                   11246: 		   $cpart%$cudom);
                   11247:     } else {
                   11248: 	$return.= ($cunique%$cuname+
                   11249: 		   $cunique%$cudom+
                   11250: 		   $cusymb%$cuname+
                   11251: 		   $cusymb%$cudom+
                   11252: 		   $cucourseid%$cuname+
                   11253: 		   $cucourseid%$cudom);
                   11254:     }
                   11255:     return $return;
1.76      www      11256: }
                   11257: 
                   11258: sub receipt {
1.474     albertel 11259:     my ($part)=@_;
1.790     albertel 11260:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11261:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11262: }
1.260     ng       11263: 
1.790     albertel 11264: sub whichuser {
                   11265:     my ($passedsymb)=@_;
                   11266:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11267:     if (defined($env{'form.grade_symb'})) {
                   11268: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11269: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11270: 	if (!$allowed &&
                   11271: 	    exists($env{'request.course.sec'}) &&
                   11272: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11273: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11274: 			      '/'.$env{'request.course.sec'});
                   11275: 	}
                   11276: 	if ($allowed) {
                   11277: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11278: 	    $courseid=$tmp_courseid;
                   11279: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11280: 	    ($name)=&get_env_multiple('form.grade_username');
                   11281: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11282: 	}
                   11283:     }
                   11284:     if (!$passedsymb) {
                   11285: 	$symb=&symbread();
                   11286:     } else {
                   11287: 	$symb=$passedsymb;
                   11288:     }
                   11289:     $courseid=$env{'request.course.id'};
                   11290:     $domain=$env{'user.domain'};
                   11291:     $name=$env{'user.name'};
                   11292:     if ($name eq 'public' && $domain eq 'public') {
                   11293: 	if (!defined($env{'form.username'})) {
                   11294: 	    $env{'form.username'}.=time.rand(10000000);
                   11295: 	}
                   11296: 	$name.=$env{'form.username'};
                   11297:     }
                   11298:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11299: 
                   11300: }
                   11301: 
1.36      albertel 11302: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11303: # returns either the contents of the file or 
                   11304: # -1 if the file doesn't exist
1.481     raeburn  11305: #
                   11306: # if the target is a file that was uploaded via DOCS, 
                   11307: # a check will be made to see if a current copy exists on the local server,
                   11308: # if it does this will be served, otherwise a copy will be retrieved from
                   11309: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11310: # the local server.   
1.472     albertel 11311: 
1.36      albertel 11312: sub getfile {
1.538     albertel 11313:     my ($file) = @_;
1.609     banghart 11314:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11315:     &repcopy($file);
                   11316:     return &readfile($file);
                   11317: }
                   11318: 
                   11319: sub repcopy_userfile {
                   11320:     my ($file)=@_;
1.1142    raeburn  11321:     my $londocroot = $perlvar{'lonDocRoot'};
                   11322:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11323:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11324:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11325: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11326:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11327:     if (-e "$file") {
1.828     www      11328: # we already have a local copy, check it out
1.538     albertel 11329: 	my @fileinfo = stat($file);
1.828     www      11330: 	my $rtncode;
                   11331: 	my $info;
1.538     albertel 11332: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11333: 	if ($lwpresp ne 'ok') {
1.828     www      11334: # there is no such file anymore, even though we had a local copy
1.482     albertel 11335: 	    if ($rtncode eq '404') {
1.538     albertel 11336: 		unlink($file);
1.482     albertel 11337: 	    }
                   11338: 	    return -1;
                   11339: 	}
                   11340: 	if ($info < $fileinfo[9]) {
1.828     www      11341: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11342: 	    return 'ok';
1.828     www      11343: 	} else {
                   11344: # the file is outdated, get rid of it
                   11345: 	    unlink($file);
1.482     albertel 11346: 	}
1.828     www      11347:     }
                   11348: # one way or the other, at this point, we don't have the file
                   11349: # construct the correct path for the file
                   11350:     my @parts = ($cdom,$cnum); 
                   11351:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11352: 	push @parts, split(/\//,$1);
                   11353:     }
                   11354:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11355:     foreach my $part (@parts) {
                   11356: 	$path .= '/'.$part;
                   11357: 	if (!-e $path) {
                   11358: 	    mkdir($path,0770);
1.482     albertel 11359: 	}
                   11360:     }
1.828     www      11361: # now the path exists for sure
                   11362: # get a user agent
                   11363:     my $ua=new LWP::UserAgent;
                   11364:     my $transferfile=$file.'.in.transfer';
                   11365: # FIXME: this should flock
                   11366:     if (-e $transferfile) { return 'ok'; }
                   11367:     my $request;
                   11368:     $uri=~s/^\///;
1.980     raeburn  11369:     my $homeserver = &homeserver($cnum,$cdom);
                   11370:     my $protocol = $protocol{$homeserver};
                   11371:     $protocol = 'http' if ($protocol ne 'https');
                   11372:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11373:     my $response=$ua->request($request,$transferfile);
                   11374: # did it work?
                   11375:     if ($response->is_error()) {
                   11376: 	unlink($transferfile);
                   11377: 	&logthis("Userfile repcopy failed for $uri");
                   11378: 	return -1;
                   11379:     }
                   11380: # worked, rename the transfer file
                   11381:     rename($transferfile,$file);
1.607     raeburn  11382:     return 'ok';
1.481     raeburn  11383: }
                   11384: 
1.517     albertel 11385: sub tokenwrapper {
                   11386:     my $uri=shift;
1.980     raeburn  11387:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11388:     $uri=~s|^/||;
1.620     albertel 11389:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11390:     my $token=$1;
1.552     albertel 11391:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11392:     if ($udom && $uname && $file) {
                   11393: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11394:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11395:         my $homeserver = &homeserver($uname,$udom);
                   11396:         my $protocol = $protocol{$homeserver};
                   11397:         $protocol = 'http' if ($protocol ne 'https');
                   11398:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11399:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11400:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11401:     } else {
                   11402:         return '/adm/notfound.html';
                   11403:     }
                   11404: }
                   11405: 
1.828     www      11406: # call with reqtype HEAD: get last modification time
                   11407: # call with reqtype GET: get the file contents
                   11408: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11409: #
1.481     raeburn  11410: sub getuploaded {
                   11411:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11412:     $uri=~s/^\///;
1.980     raeburn  11413:     my $homeserver = &homeserver($cnum,$cdom);
                   11414:     my $protocol = $protocol{$homeserver};
                   11415:     $protocol = 'http' if ($protocol ne 'https');
                   11416:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11417:     my $ua=new LWP::UserAgent;
                   11418:     my $request=new HTTP::Request($reqtype,$uri);
                   11419:     my $response=$ua->request($request);
                   11420:     $$rtncode = $response->code;
1.482     albertel 11421:     if (! $response->is_success()) {
                   11422: 	return 'failed';
                   11423:     }      
                   11424:     if ($reqtype eq 'HEAD') {
1.486     www      11425: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11426:     } elsif ($reqtype eq 'GET') {
                   11427: 	$$info = $response->content;
1.472     albertel 11428:     }
1.482     albertel 11429:     return 'ok';
1.36      albertel 11430: }
                   11431: 
1.481     raeburn  11432: sub readfile {
                   11433:     my $file = shift;
                   11434:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11435:     my $fh;
                   11436:     open($fh,"<$file");
                   11437:     my $a='';
1.800     albertel 11438:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11439:     return $a;
                   11440: }
                   11441: 
1.36      albertel 11442: sub filelocation {
1.590     banghart 11443:     my ($dir,$file) = @_;
                   11444:     my $location;
                   11445:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11446: 
                   11447:     if ($file =~ m-^/adm/-) {
                   11448: 	$file=~s-^/adm/wrapper/-/-;
                   11449: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11450:     }
1.882     albertel 11451: 
1.1139    www      11452:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11453:         $location = $file;
1.609     banghart 11454:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11455:         my ($udom,$uname,$filename)=
1.811     albertel 11456:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11457:         my $home=&homeserver($uname,$udom);
                   11458:         my $is_me=0;
                   11459:         my @ids=&current_machine_ids();
                   11460:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11461:         if ($is_me) {
1.1117    foxr     11462:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11463:         } else {
                   11464:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11465:   	      $udom.'/'.$uname.'/'.$filename;
                   11466:         }
1.882     albertel 11467:     } elsif ($file =~ m-^/adm/-) {
                   11468: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11469:     } else {
                   11470:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11471:         $file=~s:^/(res|priv)/:/:;
                   11472:         my $space=$1;
1.590     banghart 11473:         if ( !( $file =~ m:^/:) ) {
                   11474:             $location = $dir. '/'.$file;
                   11475:         } else {
1.1142    raeburn  11476:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11477:         }
1.59      albertel 11478:     }
1.590     banghart 11479:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11480:     while ($location=~m{/\.\./}) {
                   11481: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11482: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11483: 	} else {
                   11484: 	    $location=~ s{/\.\./}{/}g;
                   11485: 	}
                   11486:     } #remove dir/..
1.590     banghart 11487:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11488:     return $location;
1.46      www      11489: }
1.36      albertel 11490: 
1.46      www      11491: sub hreflocation {
                   11492:     my ($dir,$file)=@_;
1.980     raeburn  11493:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11494: 	$file=filelocation($dir,$file);
1.700     albertel 11495:     } elsif ($file=~m-^/adm/-) {
                   11496: 	$file=~s-^/adm/wrapper/-/-;
                   11497: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11498:     }
                   11499:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11500: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11501:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11502: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11503: 	        {/uploaded/$1/$2/}x;
1.46      www      11504:     }
1.913     albertel 11505:     if ($file=~ m{^/userfiles/}) {
                   11506: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11507:     }
1.462     albertel 11508:     return $file;
1.465     albertel 11509: }
                   11510: 
1.1139    www      11511: 
                   11512: 
                   11513: 
                   11514: 
1.465     albertel 11515: sub current_machine_domains {
1.853     albertel 11516:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11517: }
                   11518: 
                   11519: sub machine_domains {
                   11520:     my ($hostname) = @_;
1.465     albertel 11521:     my @domains;
1.838     albertel 11522:     my %hostname = &all_hostnames();
1.465     albertel 11523:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11524: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11525: 	if ($hostname eq $name) {
1.844     albertel 11526: 	    push(@domains,&host_domain($id));
1.465     albertel 11527: 	}
                   11528:     }
                   11529:     return @domains;
                   11530: }
                   11531: 
                   11532: sub current_machine_ids {
1.853     albertel 11533:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11534: }
                   11535: 
                   11536: sub machine_ids {
                   11537:     my ($hostname) = @_;
                   11538:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11539:     my @ids;
1.888     albertel 11540:     my %name_to_host = &all_names();
1.889     albertel 11541:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11542: 	return @{ $name_to_host{$hostname} };
                   11543:     }
                   11544:     return;
1.31      www      11545: }
                   11546: 
1.824     raeburn  11547: sub additional_machine_domains {
                   11548:     my @domains;
                   11549:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11550:     while( my $line = <$fh>) {
                   11551:         $line =~ s/\s//g;
                   11552:         push(@domains,$line);
                   11553:     }
                   11554:     return @domains;
                   11555: }
                   11556: 
                   11557: sub default_login_domain {
                   11558:     my $domain = $perlvar{'lonDefDomain'};
                   11559:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11560:     foreach my $posdom (&current_machine_domains(),
                   11561:                         &additional_machine_domains()) {
                   11562:         if (lc($posdom) eq lc($testdomain)) {
                   11563:             $domain=$posdom;
                   11564:             last;
                   11565:         }
                   11566:     }
                   11567:     return $domain;
                   11568: }
                   11569: 
1.31      www      11570: # ------------------------------------------------------------- Declutters URLs
                   11571: 
                   11572: sub declutter {
                   11573:     my $thisfn=shift;
1.569     albertel 11574:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11575:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11576:     $thisfn=~s/^\///;
1.697     albertel 11577:     $thisfn=~s|^adm/wrapper/||;
                   11578:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11579:     $thisfn=~s/^res\///;
1.1172    bisitz   11580:     $thisfn=~s/^priv\///;
1.1032    raeburn  11581:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11582:         $thisfn=~s/\?.+$//;
                   11583:     }
1.268     www      11584:     return $thisfn;
                   11585: }
                   11586: 
                   11587: # ------------------------------------------------------------- Clutter up URLs
                   11588: 
                   11589: sub clutter {
                   11590:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11591:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11592: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11593:        $thisfn='/res'.$thisfn; 
                   11594:     }
1.1031    raeburn  11595:     if ($thisfn !~m|^/adm|) {
                   11596: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11597: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11598: 	} else {
                   11599: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11600: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11601: 	    if ($embstyle eq 'ssi'
                   11602: 		|| ($embstyle eq 'hdn')
                   11603: 		|| ($embstyle eq 'rat')
                   11604: 		|| ($embstyle eq 'prv')
                   11605: 		|| ($embstyle eq 'ign')) {
                   11606: 		#do nothing with these
                   11607: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11608: 		|| ($embstyle eq 'emb')
                   11609: 		|| ($embstyle eq 'wrp')) {
                   11610: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11611: 	    } elsif ($embstyle eq 'unk'
                   11612: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11613: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11614: 	    } else {
1.718     www      11615: #		&logthis("Got a blank emb style");
1.695     albertel 11616: 	    }
1.694     albertel 11617: 	}
                   11618:     }
1.31      www      11619:     return $thisfn;
1.12      www      11620: }
                   11621: 
1.787     albertel 11622: sub clutter_with_no_wrapper {
                   11623:     my $uri = &clutter(shift);
                   11624:     if ($uri =~ m-^/adm/-) {
                   11625: 	$uri =~ s-^/adm/wrapper/-/-;
                   11626: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11627:     }
                   11628:     return $uri;
                   11629: }
                   11630: 
1.557     albertel 11631: sub freeze_escape {
                   11632:     my ($value)=@_;
                   11633:     if (ref($value)) {
                   11634: 	$value=&nfreeze($value);
                   11635: 	return '__FROZEN__'.&escape($value);
                   11636:     }
                   11637:     return &escape($value);
                   11638: }
                   11639: 
1.11      www      11640: 
1.557     albertel 11641: sub thaw_unescape {
                   11642:     my ($value)=@_;
                   11643:     if ($value =~ /^__FROZEN__/) {
                   11644: 	substr($value,0,10,undef);
                   11645: 	$value=&unescape($value);
                   11646: 	return &thaw($value);
                   11647:     }
                   11648:     return &unescape($value);
                   11649: }
                   11650: 
1.436     albertel 11651: sub correct_line_ends {
                   11652:     my ($result)=@_;
                   11653:     $$result =~s/\r\n/\n/mg;
                   11654:     $$result =~s/\r/\n/mg;
1.415     albertel 11655: }
1.1       albertel 11656: # ================================================================ Main Program
                   11657: 
1.184     www      11658: sub goodbye {
1.204     albertel 11659:    &logthis("Starting Shut down");
1.443     albertel 11660: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11661:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11662: #converted
1.599     albertel 11663: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11664:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11665: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11666: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11667: #1.1 only
1.870     albertel 11668: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11669: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11670: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11671: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11672:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11673:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11674:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11675:    &flushcourselogs();
                   11676:    &logthis("Shutting down");
                   11677: }
                   11678: 
1.852     albertel 11679: sub get_dns {
1.1210    raeburn  11680:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11681:     if (!$ignore_cache) {
                   11682: 	my ($content,$cached)=
                   11683: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11684: 	if ($cached) {
1.1210    raeburn  11685: 	    &$func($content,$hashref);
1.869     albertel 11686: 	    return;
                   11687: 	}
                   11688:     }
                   11689: 
                   11690:     my %alldns;
1.852     albertel 11691:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11692:     foreach my $dns (<$config>) {
                   11693: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11694:         my $line = $1;
                   11695:         my ($host,$protocol) = split(/:/,$line);
                   11696:         if ($protocol ne 'https') {
                   11697:             $protocol = 'http';
                   11698:         }
                   11699: 	$alldns{$host} = $protocol;
1.869     albertel 11700:     }
                   11701:     while (%alldns) {
                   11702: 	my ($dns) = keys(%alldns);
1.852     albertel 11703: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11704:         $ua->timeout(30);
1.979     raeburn  11705: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11706: 	my $response=$ua->request($request);
1.979     raeburn  11707:         delete($alldns{$dns});
1.852     albertel 11708: 	next if ($response->is_error());
                   11709: 	my @content = split("\n",$response->content);
1.1210    raeburn  11710: 	unless ($nocache) {
1.1219    raeburn  11711: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  11712: 	}
                   11713: 	&$func(\@content,$hashref);
1.869     albertel 11714: 	return;
1.852     albertel 11715:     }
                   11716:     close($config);
1.871     albertel 11717:     my $which = (split('/',$url))[3];
                   11718:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11719:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11720:     my @content = <$config>;
1.1210    raeburn  11721:     &$func(\@content,$hashref);
                   11722:     return;
                   11723: }
                   11724: 
                   11725: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11726: sub parse_dns_checksums_tab {
1.1210    raeburn  11727:     my ($lines,$hashref) = @_;
                   11728:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11729:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11730:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11731:     my (%chksum,%revnum);
                   11732:     if (ref($lines) eq 'ARRAY') {
                   11733:         chomp(@{$lines});
1.1238    raeburn  11734:         my $version = shift(@{$lines});
                   11735:         if ($version eq $release) {  
1.1210    raeburn  11736:             foreach my $line (@{$lines}) {
1.1238    raeburn  11737:                 my ($file,$version,$shasum) = split(/,/,$line);
                   11738:                 $chksum{$file} = $shasum;
                   11739:                 $revnum{$file} = $version;
1.1210    raeburn  11740:             }
                   11741:             if (ref($hashref) eq 'HASH') {
                   11742:                 %{$hashref} = (
                   11743:                                 sums     => \%chksum,
                   11744:                                 versions => \%revnum,
                   11745:                               );
                   11746:             }
                   11747:         }
                   11748:     }
1.869     albertel 11749:     return;
1.852     albertel 11750: }
1.1210    raeburn  11751: 
                   11752: sub fetch_dns_checksums {
1.1238    raeburn  11753:     my %checksums;
                   11754:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11755:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11756:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11757:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  11758:              \%checksums);
1.1210    raeburn  11759:     return \%checksums;
                   11760: }
                   11761: 
1.327     albertel 11762: # ------------------------------------------------------------ Read domain file
                   11763: {
1.852     albertel 11764:     my $loaded;
1.846     albertel 11765:     my %domain;
                   11766: 
1.852     albertel 11767:     sub parse_domain_tab {
                   11768: 	my ($lines) = @_;
                   11769: 	foreach my $line (@$lines) {
                   11770: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11771: 
1.846     albertel 11772: 	    chomp($line);
1.852     albertel 11773: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11774: 	    my %this_domain;
                   11775: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11776: 			       'lang_def', 'city', 'longi', 'lati',
                   11777: 			       'primary') {
                   11778: 		$this_domain{$field} = shift(@elements);
                   11779: 	    }
                   11780: 	    $domain{$name} = \%this_domain;
1.852     albertel 11781: 	}
                   11782:     }
1.864     albertel 11783: 
                   11784:     sub reset_domain_info {
                   11785: 	undef($loaded);
                   11786: 	undef(%domain);
                   11787:     }
                   11788: 
1.852     albertel 11789:     sub load_domain_tab {
1.869     albertel 11790: 	my ($ignore_cache) = @_;
                   11791: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11792: 	my $fh;
                   11793: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11794: 	    my @lines = <$fh>;
                   11795: 	    &parse_domain_tab(\@lines);
1.448     albertel 11796: 	}
1.852     albertel 11797: 	close($fh);
                   11798: 	$loaded = 1;
1.327     albertel 11799:     }
1.846     albertel 11800: 
                   11801:     sub domain {
1.852     albertel 11802: 	&load_domain_tab() if (!$loaded);
                   11803: 
1.846     albertel 11804: 	my ($name,$what) = @_;
                   11805: 	return if ( !exists($domain{$name}) );
                   11806: 
                   11807: 	if (!$what) {
                   11808: 	    return $domain{$name}{'description'};
                   11809: 	}
                   11810: 	return $domain{$name}{$what};
                   11811:     }
1.974     raeburn  11812: 
                   11813:     sub domain_info {
                   11814:         &load_domain_tab() if (!$loaded);
                   11815:         return %domain;
                   11816:     }
                   11817: 
1.327     albertel 11818: }
                   11819: 
                   11820: 
1.1       albertel 11821: # ------------------------------------------------------------- Read hosts file
                   11822: {
1.838     albertel 11823:     my %hostname;
1.844     albertel 11824:     my %hostdom;
1.845     albertel 11825:     my %libserv;
1.852     albertel 11826:     my $loaded;
1.888     albertel 11827:     my %name_to_host;
1.1074    raeburn  11828:     my %internetdom;
1.1107    raeburn  11829:     my %LC_dns_serv;
1.852     albertel 11830: 
                   11831:     sub parse_hosts_tab {
                   11832: 	my ($file) = @_;
                   11833: 	foreach my $configline (@$file) {
                   11834: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11835:             chomp($configline);
                   11836: 	    if ($configline =~ /^\^/) {
                   11837:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11838:                     $LC_dns_serv{$1} = 1;
                   11839:                 }
                   11840:                 next;
                   11841:             }
1.1074    raeburn  11842: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11843: 	    $name=~s/\s//g;
                   11844: 	    if ($id && $domain && $role && $name) {
                   11845: 		$hostname{$id}=$name;
1.888     albertel 11846: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11847: 		$hostdom{$id}=$domain;
                   11848: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11849:                 if (defined($protocol)) {
                   11850:                     if ($protocol eq 'https') {
                   11851:                         $protocol{$id} = $protocol;
                   11852:                     } else {
                   11853:                         $protocol{$id} = 'http'; 
                   11854:                     }
1.968     raeburn  11855:                 } else {
1.969     raeburn  11856:                     $protocol{$id} = 'http';
1.968     raeburn  11857:                 }
1.1074    raeburn  11858:                 if (defined($intdom)) {
                   11859:                     $internetdom{$id} = $intdom;
                   11860:                 }
1.852     albertel 11861: 	    }
                   11862: 	}
                   11863:     }
1.864     albertel 11864:     
                   11865:     sub reset_hosts_info {
1.897     albertel 11866: 	&purge_remembered();
1.864     albertel 11867: 	&reset_domain_info();
                   11868: 	&reset_hosts_ip_info();
1.892     albertel 11869: 	undef(%name_to_host);
1.864     albertel 11870: 	undef(%hostname);
                   11871: 	undef(%hostdom);
                   11872: 	undef(%libserv);
                   11873: 	undef($loaded);
                   11874:     }
1.1       albertel 11875: 
1.852     albertel 11876:     sub load_hosts_tab {
1.869     albertel 11877: 	my ($ignore_cache) = @_;
                   11878: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11879: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11880: 	my @config = <$config>;
                   11881: 	&parse_hosts_tab(\@config);
                   11882: 	close($config);
                   11883: 	$loaded=1;
1.1       albertel 11884:     }
1.852     albertel 11885: 
1.838     albertel 11886:     sub hostname {
1.852     albertel 11887: 	&load_hosts_tab() if (!$loaded);
                   11888: 
1.838     albertel 11889: 	my ($lonid) = @_;
                   11890: 	return $hostname{$lonid};
                   11891:     }
1.845     albertel 11892: 
1.838     albertel 11893:     sub all_hostnames {
1.852     albertel 11894: 	&load_hosts_tab() if (!$loaded);
                   11895: 
1.838     albertel 11896: 	return %hostname;
                   11897:     }
1.845     albertel 11898: 
1.888     albertel 11899:     sub all_names {
                   11900: 	&load_hosts_tab() if (!$loaded);
                   11901: 
                   11902: 	return %name_to_host;
                   11903:     }
                   11904: 
1.974     raeburn  11905:     sub all_host_domain {
                   11906:         &load_hosts_tab() if (!$loaded);
                   11907:         return %hostdom;
                   11908:     }
                   11909: 
1.845     albertel 11910:     sub is_library {
1.852     albertel 11911: 	&load_hosts_tab() if (!$loaded);
                   11912: 
1.845     albertel 11913: 	return exists($libserv{$_[0]});
                   11914:     }
                   11915: 
                   11916:     sub all_library {
1.852     albertel 11917: 	&load_hosts_tab() if (!$loaded);
                   11918: 
1.845     albertel 11919: 	return %libserv;
                   11920:     }
                   11921: 
1.1062    droeschl 11922:     sub unique_library {
                   11923: 	#2x reverse removes all hostnames that appear more than once
                   11924:         my %unique = reverse &all_library();
                   11925:         return reverse %unique;
                   11926:     }
                   11927: 
1.841     albertel 11928:     sub get_servers {
1.852     albertel 11929: 	&load_hosts_tab() if (!$loaded);
                   11930: 
1.841     albertel 11931: 	my ($domain,$type) = @_;
                   11932: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11933: 	                                          : %hostname;
                   11934: 	my %result;
1.842     albertel 11935: 	if (ref($domain) eq 'ARRAY') {
                   11936: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11937: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11938: 		    $result{$host} = $hostname;
                   11939: 		}
                   11940: 	    }
                   11941: 	} else {
                   11942: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11943: 		if ($hostdom{$host} eq $domain) {
                   11944: 		    $result{$host} = $hostname;
                   11945: 		}
1.841     albertel 11946: 	    }
                   11947: 	}
                   11948: 	return %result;
                   11949:     }
1.845     albertel 11950: 
1.1062    droeschl 11951:     sub get_unique_servers {
                   11952:         my %unique = reverse &get_servers(@_);
                   11953: 	return reverse %unique;
                   11954:     }
                   11955: 
1.844     albertel 11956:     sub host_domain {
1.852     albertel 11957: 	&load_hosts_tab() if (!$loaded);
                   11958: 
1.844     albertel 11959: 	my ($lonid) = @_;
                   11960: 	return $hostdom{$lonid};
                   11961:     }
                   11962: 
1.841     albertel 11963:     sub all_domains {
1.852     albertel 11964: 	&load_hosts_tab() if (!$loaded);
                   11965: 
1.841     albertel 11966: 	my %seen;
                   11967: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11968: 	return @uniq;
                   11969:     }
1.1074    raeburn  11970: 
                   11971:     sub internet_dom {
                   11972:         &load_hosts_tab() if (!$loaded);
                   11973: 
                   11974:         my ($lonid) = @_;
                   11975:         return $internetdom{$lonid};
                   11976:     }
1.1107    raeburn  11977: 
                   11978:     sub is_LC_dns {
                   11979:         &load_hosts_tab() if (!$loaded);
                   11980: 
                   11981:         my ($hostname) = @_;
                   11982:         return exists($LC_dns_serv{$hostname});
                   11983:     }
                   11984: 
1.1       albertel 11985: }
                   11986: 
1.847     albertel 11987: { 
                   11988:     my %iphost;
1.856     albertel 11989:     my %name_to_ip;
                   11990:     my %lonid_to_ip;
1.869     albertel 11991: 
1.847     albertel 11992:     sub get_hosts_from_ip {
                   11993: 	my ($ip) = @_;
                   11994: 	my %iphosts = &get_iphost();
                   11995: 	if (ref($iphosts{$ip})) {
                   11996: 	    return @{$iphosts{$ip}};
                   11997: 	}
                   11998: 	return;
1.839     albertel 11999:     }
1.864     albertel 12000:     
                   12001:     sub reset_hosts_ip_info {
                   12002: 	undef(%iphost);
                   12003: 	undef(%name_to_ip);
                   12004: 	undef(%lonid_to_ip);
                   12005:     }
1.856     albertel 12006: 
                   12007:     sub get_host_ip {
                   12008: 	my ($lonid) = @_;
                   12009: 	if (exists($lonid_to_ip{$lonid})) {
                   12010: 	    return $lonid_to_ip{$lonid};
                   12011: 	}
                   12012: 	my $name=&hostname($lonid);
                   12013:    	my $ip = gethostbyname($name);
                   12014: 	return if (!$ip || length($ip) ne 4);
                   12015: 	$ip=inet_ntoa($ip);
                   12016: 	$name_to_ip{$name}   = $ip;
                   12017: 	$lonid_to_ip{$lonid} = $ip;
                   12018: 	return $ip;
                   12019:     }
1.847     albertel 12020:     
                   12021:     sub get_iphost {
1.869     albertel 12022: 	my ($ignore_cache) = @_;
1.894     albertel 12023: 
1.869     albertel 12024: 	if (!$ignore_cache) {
                   12025: 	    if (%iphost) {
                   12026: 		return %iphost;
                   12027: 	    }
                   12028: 	    my ($ip_info,$cached)=
                   12029: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12030: 	    if ($cached) {
                   12031: 		%iphost      = %{$ip_info->[0]};
                   12032: 		%name_to_ip  = %{$ip_info->[1]};
                   12033: 		%lonid_to_ip = %{$ip_info->[2]};
                   12034: 		return %iphost;
                   12035: 	    }
                   12036: 	}
1.894     albertel 12037: 
                   12038: 	# get yesterday's info for fallback
                   12039: 	my %old_name_to_ip;
                   12040: 	my ($ip_info,$cached)=
                   12041: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12042: 	if ($cached) {
                   12043: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12044: 	}
                   12045: 
1.888     albertel 12046: 	my %name_to_host = &all_names();
                   12047: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12048: 	    my $ip;
                   12049: 	    if (!exists($name_to_ip{$name})) {
                   12050: 		$ip = gethostbyname($name);
                   12051: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12052: 		    if (defined($old_name_to_ip{$name})) {
                   12053: 			$ip = $old_name_to_ip{$name};
                   12054: 			&logthis("Can't find $name defaulting to old $ip");
                   12055: 		    } else {
                   12056: 			&logthis("Name $name no IP found");
                   12057: 			next;
                   12058: 		    }
                   12059: 		} else {
                   12060: 		    $ip=inet_ntoa($ip);
1.847     albertel 12061: 		}
                   12062: 		$name_to_ip{$name} = $ip;
                   12063: 	    } else {
                   12064: 		$ip = $name_to_ip{$name};
1.653     albertel 12065: 	    }
1.888     albertel 12066: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12067: 		$lonid_to_ip{$id} = $ip;
                   12068: 	    }
                   12069: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12070: 	}
1.1219    raeburn  12071: 	&do_cache_new('iphost','iphost',
                   12072: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12073: 		      48*60*60);
1.869     albertel 12074: 
1.847     albertel 12075: 	return %iphost;
1.598     albertel 12076:     }
                   12077: 
1.992     raeburn  12078:     #
                   12079:     #  Given a DNS returns the loncapa host name for that DNS 
                   12080:     # 
                   12081:     sub host_from_dns {
                   12082:         my ($dns) = @_;
                   12083:         my @hosts;
                   12084:         my $ip;
                   12085: 
1.993     raeburn  12086:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12087:             $ip = $name_to_ip{$dns};
                   12088:         }
                   12089:         if (!$ip) {
                   12090:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12091:             if (length($ip) == 4) { 
                   12092: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12093:             }
                   12094:         }
                   12095:         if ($ip) {
                   12096: 	    @hosts = get_hosts_from_ip($ip);
                   12097: 	    return $hosts[0];
                   12098:         }
                   12099:         return undef;
1.986     foxr     12100:     }
1.992     raeburn  12101: 
1.1074    raeburn  12102:     sub get_internet_names {
                   12103:         my ($lonid) = @_;
                   12104:         return if ($lonid eq '');
                   12105:         my ($idnref,$cached)=
                   12106:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12107:         if ($cached) {
                   12108:             return $idnref;
                   12109:         }
                   12110:         my $ip = &get_host_ip($lonid);
                   12111:         my @hosts = &get_hosts_from_ip($ip);
                   12112:         my %iphost = &get_iphost();
                   12113:         my (@idns,%seen);
                   12114:         foreach my $id (@hosts) {
                   12115:             my $dom = &host_domain($id);
                   12116:             my $prim_id = &domain($dom,'primary');
                   12117:             my $prim_ip = &get_host_ip($prim_id);
                   12118:             next if ($seen{$prim_ip});
                   12119:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12120:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12121:                     my $intdom = &internet_dom($id);
                   12122:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12123:                         push(@idns,$intdom);
                   12124:                     }
                   12125:                 }
                   12126:             }
                   12127:             $seen{$prim_ip} = 1;
                   12128:         }
1.1219    raeburn  12129:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12130:     }
                   12131: 
1.986     foxr     12132: }
                   12133: 
1.1079    raeburn  12134: sub all_loncaparevs {
                   12135:     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);
                   12136: }
                   12137: 
1.1227    raeburn  12138: # ---------------------------------------------------------- Read loncaparev table
                   12139: {
                   12140:     sub load_loncaparevs { 
                   12141:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12142:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12143:                 while (my $configline=<$config>) {
                   12144:                     chomp($configline);
                   12145:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12146:                     $loncaparevs{$hostid}=$loncaparev;
                   12147:                 }
                   12148:                 close($config);
                   12149:             }
                   12150:         }
                   12151:     }
                   12152: }
                   12153: 
                   12154: # ---------------------------------------------------------- Read serverhostID table
                   12155: {
                   12156:     sub load_serverhomeIDs {
                   12157:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12158:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12159:                 while (my $configline=<$config>) {
                   12160:                     chomp($configline);
                   12161:                     my ($name,$id)=split(/:/,$configline);
                   12162:                     $serverhomeIDs{$name}=$id;
                   12163:                 }
                   12164:                 close($config);
                   12165:             }
                   12166:         }
                   12167:     }
                   12168: }
                   12169: 
                   12170: 
1.862     albertel 12171: BEGIN {
                   12172: 
                   12173: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12174:     unless ($readit) {
                   12175: {
                   12176:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12177:     %perlvar = (%perlvar,%{$configvars});
                   12178: }
                   12179: 
                   12180: 
1.1       albertel 12181: # ------------------------------------------------------ Read spare server file
                   12182: {
1.448     albertel 12183:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12184: 
                   12185:     while (my $configline=<$config>) {
                   12186:        chomp($configline);
1.284     matthew  12187:        if ($configline) {
1.784     albertel 12188: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12189: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12190: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12191:        }
                   12192:     }
1.448     albertel 12193:     close($config);
1.1       albertel 12194: }
1.11      www      12195: # ------------------------------------------------------------ Read permissions
                   12196: {
1.448     albertel 12197:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12198: 
                   12199:     while (my $configline=<$config>) {
1.448     albertel 12200: 	chomp($configline);
                   12201: 	if ($configline) {
                   12202: 	    my ($role,$perm)=split(/ /,$configline);
                   12203: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12204: 	}
1.11      www      12205:     }
1.448     albertel 12206:     close($config);
1.11      www      12207: }
                   12208: 
                   12209: # -------------------------------------------- Read plain texts for permissions
                   12210: {
1.448     albertel 12211:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12212: 
                   12213:     while (my $configline=<$config>) {
1.448     albertel 12214: 	chomp($configline);
                   12215: 	if ($configline) {
1.742     raeburn  12216: 	    my ($short,@plain)=split(/:/,$configline);
                   12217:             %{$prp{$short}} = ();
                   12218: 	    if (@plain > 0) {
                   12219:                 $prp{$short}{'std'} = $plain[0];
                   12220:                 for (my $i=1; $i<@plain; $i++) {
                   12221:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12222:                 }
                   12223:             }
1.448     albertel 12224: 	}
1.135     www      12225:     }
1.448     albertel 12226:     close($config);
1.135     www      12227: }
                   12228: 
                   12229: # ---------------------------------------------------------- Read package table
                   12230: {
1.448     albertel 12231:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12232: 
                   12233:     while (my $configline=<$config>) {
1.483     albertel 12234: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12235: 	chomp($configline);
                   12236: 	my ($short,$plain)=split(/:/,$configline);
                   12237: 	my ($pack,$name)=split(/\&/,$short);
                   12238: 	if ($plain ne '') {
                   12239: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12240: 	    $packagetab{$short}=$plain; 
                   12241: 	}
1.11      www      12242:     }
1.448     albertel 12243:     close($config);
1.329     matthew  12244: }
                   12245: 
1.1073    raeburn  12246: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12247: 
                   12248: &load_loncaparevs();
1.1073    raeburn  12249: 
1.1074    raeburn  12250: # ---------------------------------------------------------- Read serverhostID table
                   12251: 
1.1227    raeburn  12252: &load_serverhomeIDs();
                   12253: 
                   12254: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12255: {
                   12256:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12257:     if (-e $file) {
                   12258:         my $parser = HTML::LCParser->new($file);
                   12259:         while (my $token = $parser->get_token()) {
                   12260:             if ($token->[0] eq 'S') {
                   12261:                 my $item = $token->[1];
                   12262:                 my $name = $token->[2]{'name'};
                   12263:                 my $value = $token->[2]{'value'};
                   12264:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12265:                     my $release = $parser->get_text();
                   12266:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12267:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12268:                 }
                   12269:             }
                   12270:         }
                   12271:     }
1.1073    raeburn  12272: }
                   12273: 
1.1138    raeburn  12274: # ---------------------------------------------------------- Read managers table
                   12275: {
                   12276:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12277:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12278:             while (my $configline=<$config>) {
                   12279:                 chomp($configline);
                   12280:                 next if ($configline =~ /^\#/);
                   12281:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12282:                     $managerstab{$configline} = 1;
                   12283:                 }
                   12284:             }
                   12285:             close($config);
                   12286:         }
                   12287:     }
                   12288: }
                   12289: 
1.329     matthew  12290: # ------------- set up temporary directory
                   12291: {
1.1117    foxr     12292:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12293: 
1.11      www      12294: }
                   12295: 
1.794     albertel 12296: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12297: 				'compress_threshold'=> 20_000,
                   12298:  			        });
1.185     www      12299: 
1.281     www      12300: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12301: $dumpcount=0;
1.958     www      12302: $locknum=0;
1.22      www      12303: 
1.163     harris41 12304: &logtouch();
1.672     albertel 12305: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12306: $readit=1;
1.564     albertel 12307:     {
                   12308: 	use integer;
                   12309: 	my $test=(2**32)+1;
1.568     albertel 12310: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12311: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12312:     }
1.195     www      12313: }
1.1       albertel 12314: }
1.179     www      12315: 
1.1       albertel 12316: 1;
1.191     harris41 12317: __END__
                   12318: 
1.243     albertel 12319: =pod
                   12320: 
1.191     harris41 12321: =head1 NAME
                   12322: 
1.243     albertel 12323: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12324: 
                   12325: =head1 SYNOPSIS
                   12326: 
1.243     albertel 12327: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12328: 
                   12329:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12330: 
1.243     albertel 12331: Common parameters:
                   12332: 
                   12333: =over 4
                   12334: 
                   12335: =item *
                   12336: 
                   12337: $uname : an internal username (if $cname expecting a course Id specifically)
                   12338: 
                   12339: =item *
                   12340: 
                   12341: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12342: 
                   12343: =item *
                   12344: 
                   12345: $symb : a resource instance identifier
                   12346: 
                   12347: =item *
                   12348: 
                   12349: $namespace : the name of a .db file that contains the data needed or
                   12350: being set.
                   12351: 
                   12352: =back
                   12353: 
1.394     bowersj2 12354: =head1 OVERVIEW
1.191     harris41 12355: 
1.394     bowersj2 12356: lonnet provides subroutines which interact with the
                   12357: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12358: about classes, users, and resources.
1.243     albertel 12359: 
                   12360: For many of these objects you can also use this to store data about
                   12361: them or modify them in various ways.
1.191     harris41 12362: 
1.394     bowersj2 12363: =head2 Symbs
1.191     harris41 12364: 
1.394     bowersj2 12365: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12366: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12367: map, the resource number of the resource in the map, and the URL of
                   12368: the resource itself. The latter is somewhat redundant, but might help
                   12369: if maps change.
                   12370: 
                   12371: An example is
                   12372: 
                   12373:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12374: 
                   12375: The respective map entry is
                   12376: 
                   12377:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12378:   title="Problem 2">
                   12379:  </resource>
                   12380: 
                   12381: Symbs are used by the random number generator, as well as to store and
                   12382: restore data specific to a certain instance of for example a problem.
                   12383: 
                   12384: =head2 Storing And Retrieving Data
                   12385: 
                   12386: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12387: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12388: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12389: is is the non-critical message twin of cstore. These functions are for
                   12390: handlers to store a perl hash to a user's permanent data space in an
                   12391: easy manner, and to retrieve it again on another call. It is expected
                   12392: that a handler would use this once at the beginning to retrieve data,
                   12393: and then again once at the end to send only the new data back.
                   12394: 
                   12395: The data is stored in the user's data directory on the user's
                   12396: homeserver under the ID of the course.
                   12397: 
                   12398: The hash that is returned by restore will have all of the previous
                   12399: value for all of the elements of the hash.
                   12400: 
                   12401: Example:
                   12402: 
                   12403:  #creating a hash
                   12404:  my %hash;
                   12405:  $hash{'foo'}='bar';
                   12406: 
                   12407:  #storing it
                   12408:  &Apache::lonnet::cstore(\%hash);
                   12409: 
                   12410:  #changing a value
                   12411:  $hash{'foo'}='notbar';
                   12412: 
                   12413:  #adding a new value
                   12414:  $hash{'bar'}='foo';
                   12415:  &Apache::lonnet::cstore(\%hash);
                   12416: 
                   12417:  #retrieving the hash
                   12418:  my %history=&Apache::lonnet::restore();
                   12419: 
                   12420:  #print the hash
                   12421:  foreach my $key (sort(keys(%history))) {
                   12422:    print("\%history{$key} = $history{$key}");
                   12423:  }
                   12424: 
                   12425: Will print out:
1.191     harris41 12426: 
1.394     bowersj2 12427:  %history{1:foo} = bar
                   12428:  %history{1:keys} = foo:timestamp
                   12429:  %history{1:timestamp} = 990455579
                   12430:  %history{2:bar} = foo
                   12431:  %history{2:foo} = notbar
                   12432:  %history{2:keys} = foo:bar:timestamp
                   12433:  %history{2:timestamp} = 990455580
                   12434:  %history{bar} = foo
                   12435:  %history{foo} = notbar
                   12436:  %history{timestamp} = 990455580
                   12437:  %history{version} = 2
                   12438: 
                   12439: Note that the special hash entries C<keys>, C<version> and
                   12440: C<timestamp> were added to the hash. C<version> will be equal to the
                   12441: total number of versions of the data that have been stored. The
                   12442: C<timestamp> attribute will be the UNIX time the hash was
                   12443: stored. C<keys> is available in every historical section to list which
                   12444: keys were added or changed at a specific historical revision of a
                   12445: hash.
                   12446: 
                   12447: B<Warning>: do not store the hash that restore returns directly. This
                   12448: will cause a mess since it will restore the historical keys as if the
                   12449: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12450: 
1.394     bowersj2 12451: Calling convention:
1.191     harris41 12452: 
1.1225    raeburn  12453:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12454:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12455: 
1.394     bowersj2 12456: For more detailed information, see lonnet specific documentation.
1.191     harris41 12457: 
1.394     bowersj2 12458: =head1 RETURN MESSAGES
1.191     harris41 12459: 
1.394     bowersj2 12460: =over 4
1.191     harris41 12461: 
1.394     bowersj2 12462: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12463: 
1.394     bowersj2 12464: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12465: when the connection is brought back up
1.191     harris41 12466: 
1.394     bowersj2 12467: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12468: for later delivery
1.191     harris41 12469: 
1.967     bisitz   12470: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12471: 
1.394     bowersj2 12472: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12473: that was requested
1.191     harris41 12474: 
1.243     albertel 12475: =back
1.191     harris41 12476: 
1.243     albertel 12477: =head1 PUBLIC SUBROUTINES
1.191     harris41 12478: 
1.243     albertel 12479: =head2 Session Environment Functions
1.191     harris41 12480: 
1.243     albertel 12481: =over 4
1.191     harris41 12482: 
1.394     bowersj2 12483: =item * 
                   12484: X<appenv()>
1.949     raeburn  12485: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12486: the user envirnoment file, and will be restored for each access this
1.620     albertel 12487: user makes during this session, also modifies the %env for the current
1.949     raeburn  12488: process. Optional rolesarrayref - if defined contains a reference to an array
                   12489: of roles which are exempt from the restriction on modifying user.role entries 
                   12490: in the user's environment.db and in %env.    
1.191     harris41 12491: 
                   12492: =item *
1.394     bowersj2 12493: X<delenv()>
1.987     raeburn  12494: B<delenv($delthis,$regexp)>: removes all items from the session
                   12495: environment file that begin with $delthis. If the 
                   12496: optional second arg - $regexp - is true, $delthis is treated as a 
                   12497: regular expression, otherwise \Q$delthis\E is used. 
                   12498: The values are also deleted from the current processes %env.
1.191     harris41 12499: 
1.795     albertel 12500: =item * get_env_multiple($name) 
                   12501: 
                   12502: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12503: values may be defined and end up as an array ref.
                   12504: 
                   12505: returns an array of values
                   12506: 
1.243     albertel 12507: =back
                   12508: 
                   12509: =head2 User Information
1.191     harris41 12510: 
1.243     albertel 12511: =over 4
1.191     harris41 12512: 
                   12513: =item *
1.394     bowersj2 12514: X<queryauthenticate()>
                   12515: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12516: authentication scheme
                   12517: 
                   12518: =item *
1.394     bowersj2 12519: X<authenticate()>
1.1073    raeburn  12520: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12521: authenticate user from domain's lib servers (first use the current
                   12522: one). C<$upass> should be the users password.
1.1073    raeburn  12523: $checkdefauth is optional (value is 1 if a check should be made to
                   12524:    authenticate user using default authentication method, and allow
                   12525:    account creation if username does not have account in the domain).
                   12526: $clientcancheckhost is optional (value is 1 if checking whether the
                   12527:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12528: 
                   12529: =item *
1.394     bowersj2 12530: X<homeserver()>
                   12531: B<homeserver($uname,$udom)>: find the server which has
                   12532: the user's directory and files (there must be only one), this caches
                   12533: the answer, and also caches if there is a borken connection.
1.191     harris41 12534: 
                   12535: =item *
1.394     bowersj2 12536: X<idget()>
                   12537: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12538: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12539: username, and only 1 username per ID in a specific domain) (returns
                   12540: hash: id=>name,id=>name)
1.191     harris41 12541: 
                   12542: =item *
1.394     bowersj2 12543: X<idrget()>
                   12544: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12545: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12546: 
                   12547: =item *
1.394     bowersj2 12548: X<idput()>
                   12549: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12550: 
                   12551: =item *
1.394     bowersj2 12552: X<rolesinit()>
1.1169    droeschl 12553: B<rolesinit($udom,$username)>: get user privileges.
                   12554: returns user role, first access and timer interval hashes
1.243     albertel 12555: 
                   12556: =item *
1.1171    droeschl 12557: X<privileged()>
                   12558: B<privileged($username,$domain)>: returns a true if user has a
                   12559: privileged and active role (i.e. su or dc), false otherwise.
                   12560: 
                   12561: =item *
1.551     albertel 12562: X<getsection()>
                   12563: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12564: course $cname, return section name/number or '' for "not in course"
                   12565: and '-1' for "no section"
                   12566: 
                   12567: =item *
1.394     bowersj2 12568: X<userenvironment()>
                   12569: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12570: passed in @what from the requested user's environment, returns a hash
                   12571: 
1.858     raeburn  12572: =item * 
                   12573: X<userlog_query()>
1.859     albertel 12574: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12575: activity.log file. %filters defines filters applied when parsing the
                   12576: log file. These can be start or end timestamps, or the type of action
                   12577: - log to look for Login or Logout events, check for Checkin or
                   12578: Checkout, role for role selection. The response is in the form
                   12579: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12580: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12581: 
1.243     albertel 12582: =back
                   12583: 
                   12584: =head2 User Roles
                   12585: 
                   12586: =over 4
                   12587: 
                   12588: =item *
                   12589: 
1.810     raeburn  12590: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12591:  F: full access
                   12592:  U,I,K: authentication modes (cxx only)
                   12593:  '': forbidden
                   12594:  1: user needs to choose course
                   12595:  2: browse allowed
1.766     albertel 12596:  A: passphrase authentication needed
1.243     albertel 12597: 
                   12598: =item *
                   12599: 
1.1192    raeburn  12600: constructaccess($url,$setpriv) : check for access to construction space URL
                   12601: 
                   12602: See if the owner domain and name in the URL match those in the
                   12603: expected environment.  If so, return three element list
                   12604: ($ownername,$ownerdomain,$ownerhome).
                   12605: 
                   12606: Otherwise return the null string.
                   12607: 
                   12608: If second argument 'setpriv' is true, it assigns the privileges,
                   12609: and returns the same three element list, unless the owner has
                   12610: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12611: in which case the null string is returned.
                   12612: 
                   12613: =item *
                   12614: 
1.243     albertel 12615: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12616: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12617: and course level
                   12618: 
                   12619: =item *
                   12620: 
1.988     raeburn  12621: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12622: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12623: $type is Course (default) or Community.
1.988     raeburn  12624: If $forcedefault evaluates to true, text returned will be default 
                   12625: text for $type. Otherwise, if this is a course, the text returned 
                   12626: will be a custom name for the role (if defined in the course's 
                   12627: environment).  If no custom name is defined the default is returned.
                   12628:    
1.832     raeburn  12629: =item *
                   12630: 
1.1219    raeburn  12631: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12632: All arguments are optional. Returns a hash of a roles, either for
                   12633: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12634: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12635: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12636: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12637: For each key, value is set to colon-separated start and end times for
                   12638: the role.  If no username and domain are specified, will default to
1.934     raeburn  12639: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12640: of role statuses (active, future or previous), roles 
                   12641: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12642: to restrict the list of roles reported. If no array ref is 
                   12643: provided for types, will default to return only active roles.
1.834     albertel 12644: 
1.1195    raeburn  12645: =item *
                   12646: 
                   12647: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12648: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12649: 
                   12650: Additional optional arguments are: $type (if role checking is to be restricted 
                   12651: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12652: available roles) or future (roles available in the future), and
                   12653: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  12654: have active Domain Coordinator role in course's domain or in additional
                   12655: domains (specified in 'Domains to check for privileged users' in course
                   12656: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12657: 
                   12658: =item *
                   12659: 
                   12660: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12661: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12662: $possdomains and $possroles are optional array refs -- to domains to check and
                   12663: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12664: users' roles.db to check for a dc or su role in any domain. This can be
                   12665: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12666: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12667: this then allows &privileged_by_domain() to be used, which caches the identity
                   12668: of privileged users, eliminating the need for repeated calls to &dump().
                   12669: 
                   12670: =item *
                   12671: 
                   12672: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12673: where the outer hash keys are domains specified in the $possdomains array ref,
                   12674: next inner hash keys are privileged roles specified in the $roles array ref,
                   12675: and the innermost hash contains key = value pairs for username:domain = end:start
                   12676: for active or future "privileged" users with that role in that domain. To avoid
                   12677: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12678: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  12679: 
1.243     albertel 12680: =back
                   12681: 
                   12682: =head2 User Modification
                   12683: 
                   12684: =over 4
                   12685: 
                   12686: =item *
                   12687: 
1.957     raeburn  12688: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12689: user for the level given by URL.  Optional start and end dates (leave empty
                   12690: string or zero for "no date")
1.191     harris41 12691: 
                   12692: =item *
                   12693: 
1.243     albertel 12694: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12695: change a users, password, possible return values are: ok,
                   12696: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12697: refused
1.191     harris41 12698: 
                   12699: =item *
                   12700: 
1.243     albertel 12701: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12702: 
                   12703: =item *
                   12704: 
1.1058    raeburn  12705: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12706:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12707: 
                   12708: will update user information (firstname,middlename,lastname,generation,
                   12709: permanentemail), and if forceid is true, student/employee ID also.
                   12710: A user's institutional affiliation(s) can also be updated.
                   12711: User information fields will not be overwritten with empty entries 
                   12712: unless the field is included in the $candelete array reference.
                   12713: This array is included when a single user is modified via "Manage Users",
                   12714: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12715: 
                   12716: =item *
                   12717: 
1.286     matthew  12718: modifystudent
                   12719: 
1.957     raeburn  12720: modify a student's enrollment and identification information.
1.1235    raeburn  12721: The course id is resolved based on the current user's environment.  
                   12722: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12723: associated with a course.
                   12724: 
1.297     matthew  12725: This call is essentially a wrapper for lonnet::modifyuser and
                   12726: lonnet::modify_student_enrollment
1.286     matthew  12727: 
                   12728: Inputs: 
                   12729: 
                   12730: =over 4
                   12731: 
1.957     raeburn  12732: =item B<$udom> Student's loncapa domain
1.286     matthew  12733: 
1.957     raeburn  12734: =item B<$uname> Student's loncapa login name
1.286     matthew  12735: 
1.964     bisitz   12736: =item B<$uid> Student/Employee ID
1.286     matthew  12737: 
1.957     raeburn  12738: =item B<$umode> Student's authentication mode
1.286     matthew  12739: 
1.957     raeburn  12740: =item B<$upass> Student's password
1.286     matthew  12741: 
1.957     raeburn  12742: =item B<$first> Student's first name
1.286     matthew  12743: 
1.957     raeburn  12744: =item B<$middle> Student's middle name
1.286     matthew  12745: 
1.957     raeburn  12746: =item B<$last> Student's last name
1.286     matthew  12747: 
1.957     raeburn  12748: =item B<$gene> Student's generation
1.286     matthew  12749: 
1.957     raeburn  12750: =item B<$usec> Student's section in course
1.286     matthew  12751: 
                   12752: =item B<$end> Unix time of the roles expiration
                   12753: 
                   12754: =item B<$start> Unix time of the roles start date
                   12755: 
                   12756: =item B<$forceid> If defined, allow $uid to be changed
                   12757: 
                   12758: =item B<$desiredhome> server to use as home server for student
                   12759: 
1.957     raeburn  12760: =item B<$email> Student's permanent e-mail address
                   12761: 
                   12762: =item B<$type> Type of enrollment (auto or manual)
                   12763: 
1.963     raeburn  12764: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12765: 
                   12766: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12767: 
1.963     raeburn  12768: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12769: 
1.963     raeburn  12770: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12771: 
1.1216    raeburn  12772: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12773: 
                   12774: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  12775: 
1.286     matthew  12776: =back
1.297     matthew  12777: 
                   12778: =item *
                   12779: 
                   12780: modify_student_enrollment
                   12781: 
1.1235    raeburn  12782: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12783: 'role.request.course' must be defined for this function to proceed.
                   12784: 
                   12785: Inputs:
                   12786: 
                   12787: =over 4
                   12788: 
1.1235    raeburn  12789: =item $udom, student's domain
1.297     matthew  12790: 
1.1235    raeburn  12791: =item $uname, student's name
1.297     matthew  12792: 
1.1235    raeburn  12793: =item $uid, student's user id
1.297     matthew  12794: 
1.1235    raeburn  12795: =item $first, student's first name
1.297     matthew  12796: 
                   12797: =item $middle
                   12798: 
                   12799: =item $last
                   12800: 
                   12801: =item $gene
                   12802: 
                   12803: =item $usec
                   12804: 
                   12805: =item $end
                   12806: 
                   12807: =item $start
                   12808: 
1.957     raeburn  12809: =item $type
                   12810: 
                   12811: =item $locktype
                   12812: 
                   12813: =item $cid
                   12814: 
                   12815: =item $selfenroll
                   12816: 
                   12817: =item $context
                   12818: 
1.1216    raeburn  12819: =item $credits, number of credits student will earn from this class
                   12820: 
1.297     matthew  12821: =back
                   12822: 
1.191     harris41 12823: 
                   12824: =item *
                   12825: 
1.243     albertel 12826: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12827: custom role; give a custom role to a user for the level given by URL.  Specify
                   12828: name and domain of role author, and role name
1.191     harris41 12829: 
                   12830: =item *
                   12831: 
1.243     albertel 12832: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12833: 
                   12834: =item *
                   12835: 
1.243     albertel 12836: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12837: 
                   12838: =back
                   12839: 
                   12840: =head2 Course Infomation
                   12841: 
                   12842: =over 4
1.191     harris41 12843: 
                   12844: =item *
                   12845: 
1.1118    foxr     12846: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12847: specified course id, including all environment settings for the
                   12848: course, the description of the course will be in the hash under the
                   12849: key 'description'
1.191     harris41 12850: 
1.1118    foxr     12851: $options is an optional parameter that if supplied is a hash reference that controls
                   12852: what how this function works.  It has the following key/values:
                   12853: 
                   12854: =over 4
                   12855: 
                   12856: =item freshen_cache
                   12857: 
                   12858: If defined, and the environment cache for the course is valid, it is 
                   12859: returned in the returned hash.
                   12860: 
                   12861: =item one_time
                   12862: 
                   12863: If defined, the last cache time is set to _now_
                   12864: 
                   12865: =item user
                   12866: 
                   12867: If defined, the supplied username is used instead of the current user.
                   12868: 
                   12869: 
                   12870: =back
                   12871: 
1.191     harris41 12872: =item *
                   12873: 
1.624     albertel 12874: resdata($name,$domain,$type,@which) : request for current parameter
                   12875: setting for a specific $type, where $type is either 'course' or 'user',
                   12876: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  12877: answers for 10 minutes.
1.243     albertel 12878: 
1.877     foxr     12879: =item *
                   12880: 
                   12881: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12882: data base, returning a hash that is keyed by the resource name and has
                   12883: values that are the resource value.  I believe that the timestamps and
                   12884: versions are also returned.
                   12885: 
1.1236    raeburn  12886: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   12887: supplemental content area. This routine caches the number of files for 
                   12888: 10 minutes.
                   12889: 
1.243     albertel 12890: =back
                   12891: 
                   12892: =head2 Course Modification
                   12893: 
                   12894: =over 4
1.191     harris41 12895: 
                   12896: =item *
                   12897: 
1.243     albertel 12898: writecoursepref($courseid,%prefs) : write preferences (environment
                   12899: database) for a course
1.191     harris41 12900: 
                   12901: =item *
                   12902: 
1.1011    raeburn  12903: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12904: 
                   12905: =item *
                   12906: 
1.1038    raeburn  12907: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12908: 
1.1167    droeschl 12909: =item *
                   12910: 
                   12911: is_course($courseid), is_course($cdom, $cnum)
                   12912: 
                   12913: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12914: two component version $cdom, $cnum. It checks if the specified course exists.
                   12915: 
                   12916: Returns:
                   12917:     undef if the course doesn't exist, otherwise
                   12918:     in scalar context the combined courseid.
                   12919:     in list context the two components of the course identifier, domain and 
                   12920:     courseid.    
                   12921: 
1.243     albertel 12922: =back
                   12923: 
                   12924: =head2 Resource Subroutines
                   12925: 
                   12926: =over 4
1.191     harris41 12927: 
                   12928: =item *
                   12929: 
1.243     albertel 12930: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12931: 
                   12932: =item *
                   12933: 
1.243     albertel 12934: repcopy($filename) : subscribes to the requested file, and attempts to
                   12935: replicate from the owning library server, Might return
1.607     raeburn  12936: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12937: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12938: resource. Expects the local filesystem pathname
                   12939: (/home/httpd/html/res/....)
                   12940: 
                   12941: =back
                   12942: 
                   12943: =head2 Resource Information
                   12944: 
                   12945: =over 4
1.191     harris41 12946: 
                   12947: =item *
                   12948: 
1.1228    raeburn  12949: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   12950: and returns the value of a variety of different possible values,
                   12951: $varname should be a request string, and the other parameters can be
                   12952: used to specify who and what one is asking about. Ordinarily, $cid 
                   12953: does not need to be specified, as it is retrived from 
                   12954: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   12955: within lonuserstate::loadmap() when initializing a course, before
                   12956: $env{'request.course.id'} has been set, so it needs to be provided
                   12957: in that one case.
1.243     albertel 12958: 
                   12959: Possible values for $varname are environment.lastname (or other item
                   12960: from the envirnment hash), user.name (or someother aspect about the
                   12961: user), resource.0.maxtries (or some other part and parameter of a
                   12962: resource)
1.204     albertel 12963: 
                   12964: =item *
                   12965: 
1.243     albertel 12966: directcondval($number) : get current value of a condition; reads from a state
                   12967: string
1.204     albertel 12968: 
                   12969: =item *
                   12970: 
1.243     albertel 12971: condval($condidx) : value of condition index based on state
1.204     albertel 12972: 
                   12973: =item *
                   12974: 
1.243     albertel 12975: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12976: resource's metadata, $what should be either a specific key, or either
                   12977: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12978: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12979: 
                   12980: this function automatically caches all requests
1.191     harris41 12981: 
                   12982: =item *
                   12983: 
1.243     albertel 12984: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12985: network of library servers; returns file handle of where SQL and regex results
                   12986: will be stored for query
1.191     harris41 12987: 
                   12988: =item *
                   12989: 
1.243     albertel 12990: symbread($filename) : return symbolic list entry (filename argument optional);
                   12991: returns the data handle
1.191     harris41 12992: 
                   12993: =item *
                   12994: 
1.1190    raeburn  12995: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   12996: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12997: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  12998: on failure, user must be in a course, as it assumes the existence of
                   12999: the course initial hash, and uses $env('request.course.id'}.  The third
                   13000: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13001: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13002: encrypted; otherwise it will be null.  
1.191     harris41 13003: 
                   13004: =item *
                   13005: 
1.243     albertel 13006: symbclean($symb) : removes versions numbers from a symb, returns the
                   13007: cleaned symb
1.191     harris41 13008: 
                   13009: =item *
                   13010: 
1.243     albertel 13011: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13012: course map, user must be in a course for it to work.
1.191     harris41 13013: 
                   13014: =item *
                   13015: 
1.243     albertel 13016: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13017: 
                   13018: =item *
                   13019: 
1.243     albertel 13020: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13021: a random seed, all arguments are optional, if they aren't sent it uses the
                   13022: environment to derive them. Note: if symb isn't sent and it can't get one
                   13023: from &symbread it will use the current time as its return value
1.191     harris41 13024: 
                   13025: =item *
                   13026: 
1.243     albertel 13027: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13028: unfakeable, receipt
1.191     harris41 13029: 
                   13030: =item *
                   13031: 
1.620     albertel 13032: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13033: 
                   13034: =item *
                   13035: 
1.243     albertel 13036: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13037: 
                   13038: =item *
                   13039: 
1.243     albertel 13040: 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 13041: 
                   13042: =item *
                   13043: 
1.243     albertel 13044: 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 13045: 
                   13046: =item *
                   13047: 
1.243     albertel 13048: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13049: 
                   13050: =item *
                   13051: 
1.243     albertel 13052: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13053: forcing spreadsheet to reevaluate the resource scores next time.
                   13054: 
1.1195    raeburn  13055: =item * 
                   13056: 
1.1196    raeburn  13057: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13058: when viewing in course context.
1.1195    raeburn  13059: 
1.1196    raeburn  13060:  input: six args -- filename (decluttered), course number, course domain,
                   13061:                     url, symb (if registered) and group (if this is a 
                   13062:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13063: 
1.1196    raeburn  13064:  output: array of five scalars --
1.1195    raeburn  13065:          $cfile -- url for file editing if editable on current server
                   13066:          $home -- homeserver of resource (i.e., for author if published,
                   13067:                                           or course if uploaded.).
                   13068:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13069:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13070:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13071: 
                   13072: =item *
                   13073: 
                   13074: is_course_upload($file,$cnum,$cdom)
                   13075: 
                   13076: Used in course context to determine if current file was uploaded to 
                   13077: the course (i.e., would be found in /userfiles/docs on the course's 
                   13078: homeserver.
                   13079: 
                   13080:   input: 3 args -- filename (decluttered), course number and course domain.
                   13081:   output: boolean -- 1 if file was uploaded.
                   13082: 
1.243     albertel 13083: =back
                   13084: 
                   13085: =head2 Storing/Retreiving Data
                   13086: 
                   13087: =over 4
1.191     harris41 13088: 
                   13089: =item *
                   13090: 
1.243     albertel 13091: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13092: for this url; hashref needs to be given and should be a \%hashname; the
                   13093: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13094: be derived from the env
1.191     harris41 13095: 
                   13096: =item *
                   13097: 
1.243     albertel 13098: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13099: uses critical subroutine
1.191     harris41 13100: 
                   13101: =item *
                   13102: 
1.243     albertel 13103: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13104: all args are optional
1.191     harris41 13105: 
                   13106: =item *
                   13107: 
1.717     albertel 13108: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13109: dumps the complete (or key matching regexp) namespace into a hash
                   13110: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13111: normally &store()ed into
                   13112: 
                   13113: $range should be either an integer '100' (give me the first 100
                   13114:                                            matching records)
                   13115:               or be  two integers sperated by a - with no spaces
                   13116:                  '30-50' (give me the 30th through the 50th matching
                   13117:                           records)
                   13118: 
                   13119: 
                   13120: =item *
                   13121: 
                   13122: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13123: replaces a &store() version of data with a replacement set of data
                   13124: for a particular resource in a namespace passed in the $storehash hash 
                   13125: reference
                   13126: 
                   13127: =item *
                   13128: 
1.243     albertel 13129: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13130: works very similar to store/cstore, but all data is stored in a
                   13131: temporary location and can be reset using tmpreset, $storehash should
                   13132: be a hash reference, returns nothing on success
1.191     harris41 13133: 
                   13134: =item *
                   13135: 
1.243     albertel 13136: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13137: similar to restore, but all data is stored in a temporary location and
                   13138: can be reset using tmpreset. Returns a hash of values on success,
                   13139: error string otherwise.
1.191     harris41 13140: 
                   13141: =item *
                   13142: 
1.243     albertel 13143: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13144: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13145: 
                   13146: =item *
                   13147: 
1.243     albertel 13148: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13149: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13150: 
                   13151: =item *
                   13152: 
1.243     albertel 13153: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13154: namesp ($udom and $uname are optional)
1.191     harris41 13155: 
                   13156: =item *
                   13157: 
1.702     albertel 13158: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13159: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13160: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13161: 
1.702     albertel 13162: $range should be either an integer '100' (give me the first 100
                   13163:                                            matching records)
                   13164:               or be  two integers sperated by a - with no spaces
                   13165:                  '30-50' (give me the 30th through the 50th matching
                   13166:                           records)
1.449     matthew  13167: =item *
                   13168: 
                   13169: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13170: $store can be a scalar, an array reference, or if the amount to be 
                   13171: incremented is > 1, a hash reference.
                   13172: 
                   13173: ($udom and $uname are optional)
1.191     harris41 13174: 
                   13175: =item *
                   13176: 
1.243     albertel 13177: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13178: ($udom and $uname are optional)
1.191     harris41 13179: 
                   13180: =item *
                   13181: 
1.243     albertel 13182: cput($namespace,$storehash,$udom,$uname) : critical put
                   13183: ($udom and $uname are optional)
1.191     harris41 13184: 
                   13185: =item *
                   13186: 
1.748     albertel 13187: newput($namespace,$storehash,$udom,$uname) :
                   13188: 
                   13189: Attempts to store the items in the $storehash, but only if they don't
                   13190: currently exist, if this succeeds you can be certain that you have 
                   13191: successfully created a new key value pair in the $namespace db.
                   13192: 
                   13193: 
                   13194: Args:
                   13195:  $namespace: name of database to store values to
                   13196:  $storehash: hashref to store to the db
                   13197:  $udom: (optional) domain of user containing the db
                   13198:  $uname: (optional) name of user caontaining the db
                   13199: 
                   13200: Returns:
                   13201:  'ok' -> succeeded in storing all keys of $storehash
                   13202:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13203:                         least <key> already existed in the db (other
                   13204:                         requested keys may also already exist)
1.967     bisitz   13205:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13206:  'con_lost' -> unable to contact request server
                   13207:  'refused' -> action was not allowed by remote machine
                   13208: 
                   13209: 
                   13210: =item *
                   13211: 
1.243     albertel 13212: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13213: reference filled in from namesp (encrypts the return communication)
                   13214: ($udom and $uname are optional)
1.191     harris41 13215: 
                   13216: =item *
                   13217: 
1.243     albertel 13218: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13219: critical subroutine
                   13220: 
1.806     raeburn  13221: =item *
                   13222: 
1.860     raeburn  13223: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13224: array reference filled in from namespace found in domain level on either
                   13225: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13226: 
                   13227: =item *
                   13228: 
1.860     raeburn  13229: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13230: domain level either on specified domain server ($uhome) or primary domain 
                   13231: server ($udom and $uhome are optional)
1.806     raeburn  13232: 
1.943     raeburn  13233: =item * 
                   13234: 
1.1240    raeburn  13235: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13236: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13237: the target domain.
                   13238: 
                   13239: May also include additional key => value pairs for the following groups:
                   13240: 
                   13241: =over
                   13242: 
                   13243: =item
                   13244: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13245: 
                   13246: =over
                   13247: 
                   13248: =item defaultquota, authorquota
                   13249: 
                   13250: =back
                   13251: 
                   13252: =item
                   13253: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13254: portfolio for users).
                   13255: 
                   13256: =over
                   13257: 
                   13258: =item
                   13259: aboutme, blog, webdav, portfolio
                   13260: 
                   13261: =back
                   13262: 
                   13263: =item
                   13264: requestcourses: ability to request courses, and how requests are processed.
                   13265: 
                   13266: =over
                   13267: 
                   13268: =item
                   13269: official, unofficial, community
                   13270: 
                   13271: =back
                   13272: 
                   13273: =item
                   13274: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13275: 
                   13276: =over
                   13277: 
                   13278: =item
                   13279: inststatustypes, inststatusorder
                   13280: 
                   13281: =back
                   13282: 
                   13283: =item
                   13284: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13285: for course's uploaded content.
                   13286: 
                   13287: =over
                   13288: 
                   13289: =item
                   13290: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
                   13291: 
                   13292: =back
                   13293: 
                   13294: =item
                   13295: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13296: on your servers.
                   13297: 
                   13298: =over
                   13299: 
                   13300: =item 
                   13301: remotesessions, hostedsessions
                   13302: 
                   13303: =back
                   13304: 
                   13305: =back
                   13306: 
                   13307: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13308: utility to create a configuration.db file on a domain's primary library server 
                   13309: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13310: -- corresponding values are authentication type (internal, krb4, krb5,
                   13311: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13312: will be available. Values are retrieved from cache (if current), unless the
                   13313: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13314: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13315: 
                   13316: Typical usage:
1.943     raeburn  13317: 
1.1240    raeburn  13318: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13319: 
1.243     albertel 13320: =back
                   13321: 
                   13322: =head2 Network Status Functions
                   13323: 
                   13324: =over 4
1.191     harris41 13325: 
                   13326: =item *
                   13327: 
1.1137    raeburn  13328: dirlist() : return directory list based on URI (first arg).
                   13329: 
                   13330: Inputs: 1 required, 5 optional.
                   13331: 
                   13332: =over
                   13333: 
                   13334: =item 
                   13335: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13336: 
                   13337: =item
                   13338: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13339: 
                   13340: =item
                   13341: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13342: 
                   13343: =item
                   13344: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13345: 
                   13346: =item
                   13347: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13348: 
                   13349: =item 
                   13350: $alternateRoot - path to prepend in place of path from $uri.
                   13351: 
                   13352: =back
                   13353: 
                   13354: Returns: Array of up to two items.
                   13355: 
                   13356: =over
                   13357: 
                   13358: a reference to an array of files/subdirectories
                   13359: 
                   13360: =over
                   13361: 
                   13362: Each element in the array of files/subdirectories is a & separated list of
                   13363: item name and the result of running stat on the item.  If dirlist was requested
                   13364: for a file instead of a directory, the item name will be ''. For a directory 
                   13365: listing, if the item is a metadata file, the element will end &N&M 
                   13366: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13367: default copyright set (1).  
                   13368: 
                   13369: =back
                   13370: 
                   13371: a scalar containing error condition (if encountered).
                   13372: 
                   13373: =over
                   13374: 
                   13375: =item 
                   13376: no_host (no homeserver identified for $username:$domain).
                   13377: 
                   13378: =item 
                   13379: no_such_host (server contacted for listing not identified as valid host).
                   13380: 
                   13381: =item 
                   13382: con_lost (connection to remote server failed).
                   13383: 
                   13384: =item 
                   13385: refused (invalid $username:$domain received on lond side).
                   13386: 
                   13387: =item 
                   13388: no_such_dir (directory at specified path on lond side does not exist). 
                   13389: 
                   13390: =item 
                   13391: empty (directory at specified path on lond side is empty).
                   13392: 
                   13393: =over
                   13394: 
                   13395: This is currently not encountered because the &ls3, &ls2, 
                   13396: &ls (_handler) routines on the lond side do not filter out
                   13397: . and .. from a directory listing. 
                   13398: 
                   13399: =back
                   13400: 
                   13401: =back
                   13402: 
                   13403: =back
1.191     harris41 13404: 
                   13405: =item *
                   13406: 
1.243     albertel 13407: spareserver() : find server with least workload from spare.tab
                   13408: 
1.986     foxr     13409: 
                   13410: =item *
                   13411: 
                   13412: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13413: if there is no corresponding loncapa host.
                   13414: 
1.243     albertel 13415: =back
                   13416: 
1.986     foxr     13417: 
1.243     albertel 13418: =head2 Apache Request
                   13419: 
                   13420: =over 4
1.191     harris41 13421: 
                   13422: =item *
                   13423: 
1.243     albertel 13424: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13425: localhost, posts hash
                   13426: 
                   13427: =back
                   13428: 
                   13429: =head2 Data to String to Data
                   13430: 
                   13431: =over 4
1.191     harris41 13432: 
                   13433: =item *
                   13434: 
1.243     albertel 13435: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13436: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13437: 
                   13438: =item *
                   13439: 
1.243     albertel 13440: hashref2str($hashref) : convert a hashref into a string complete with
                   13441: escaping and '=' and '&' separators, supports elements that are
                   13442: arrayrefs and hashrefs
1.191     harris41 13443: 
                   13444: =item *
                   13445: 
1.243     albertel 13446: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13447: with escaping and '&' separators, supports elements that are arrayrefs
                   13448: and hashrefs
1.191     harris41 13449: 
                   13450: =item *
                   13451: 
1.243     albertel 13452: str2hash($string) : convert string to hash using unescaping and
                   13453: splitting on '=' and '&', supports elements that are arrayrefs and
                   13454: hashrefs
1.191     harris41 13455: 
                   13456: =item *
                   13457: 
1.243     albertel 13458: str2array($string) : convert string to hash using unescaping and
                   13459: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13460: 
                   13461: =back
                   13462: 
                   13463: =head2 Logging Routines
                   13464: 
                   13465: 
                   13466: These routines allow one to make log messages in the lonnet.log and
                   13467: lonnet.perm logfiles.
1.191     harris41 13468: 
1.1119    foxr     13469: =over 4
                   13470: 
1.191     harris41 13471: =item *
                   13472: 
1.243     albertel 13473: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13474: 
                   13475: =item *
                   13476: 
1.243     albertel 13477: logthis() : append message to the normal lonnet.log file, it gets
                   13478: preiodically rolled over and deleted.
1.191     harris41 13479: 
                   13480: =item *
                   13481: 
1.243     albertel 13482: logperm() : append a permanent message to lonnet.perm.log, this log
                   13483: file never gets deleted by any automated portion of the system, only
                   13484: messages of critical importance should go in here.
                   13485: 
1.1119    foxr     13486: 
1.243     albertel 13487: =back
                   13488: 
                   13489: =head2 General File Helper Routines
                   13490: 
                   13491: =over 4
1.191     harris41 13492: 
                   13493: =item *
                   13494: 
1.481     raeburn  13495: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13496: (a) files in /uploaded
                   13497:   (i) If a local copy of the file exists - 
                   13498:       compares modification date of local copy with last-modified date for 
                   13499:       definitive version stored on home server for course. If local copy is 
                   13500:       stale, requests a new version from the home server and stores it. 
                   13501:       If the original has been removed from the home server, then local copy 
                   13502:       is unlinked.
                   13503:   (ii) If local copy does not exist -
                   13504:       requests the file from the home server and stores it. 
                   13505:   
                   13506:   If $caller is 'uploadrep':  
                   13507:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13508:     for request for files originally uploaded via DOCS. 
                   13509:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13510:   
                   13511:   Otherwise:
                   13512:      This indicates a call from the content generation phase of the request.
                   13513:      -  returns the entire contents of the file or -1.
                   13514:      
                   13515: (b) files in /res
                   13516:    - returns the entire contents of a file or -1; 
                   13517:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13518: 
1.712     albertel 13519: 
                   13520: =item *
                   13521: 
                   13522: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13523:                   reference
                   13524: 
                   13525: returns either a stat() list of data about the file or an empty list
                   13526: if the file doesn't exist or couldn't find out about it (connection
                   13527: problems or user unknown)
                   13528: 
1.191     harris41 13529: =item *
                   13530: 
1.243     albertel 13531: filelocation($dir,$file) : returns file system location of a file
                   13532: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13533: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13534: and a file of ../bob will become /a/bob)
1.191     harris41 13535: 
                   13536: =item *
                   13537: 
                   13538: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13539: filelocation except for hrefs
                   13540: 
                   13541: =item *
                   13542: 
                   13543: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13544: 
1.243     albertel 13545: =back
                   13546: 
1.608     albertel 13547: =head2 Usererfile file routines (/uploaded*)
                   13548: 
                   13549: =over 4
                   13550: 
                   13551: =item *
                   13552: 
                   13553: userfileupload(): main rotine for putting a file in a user or course's
                   13554:                   filespace, arguments are,
                   13555: 
1.620     albertel 13556:  formname - required - this is the name of the element in $env where the
1.608     albertel 13557:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13558:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13559:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13560:  context - if coursedoc, store the file in the course of the active role
                   13561:              of the current user; 
                   13562:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13563:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13564:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13565:          if undefined, it will be placed in "unknown"
                   13566: 
                   13567:  (This routine calls clean_filename() to remove any dangerous
                   13568:  characters from the filename, and then calls finuserfileupload() to
                   13569:  complete the transaction)
                   13570: 
                   13571:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13572:  and /adm/notfound.html if unsuccessful
                   13573: 
                   13574: =item *
                   13575: 
                   13576: clean_filename(): routine for cleaing a filename up for storage in
                   13577:                  userfile space, argument is:
                   13578: 
                   13579:  filename - proposed filename
                   13580: 
                   13581: returns: the new clean filename
                   13582: 
                   13583: =item *
                   13584: 
1.1090    raeburn  13585: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13586: userspace, probably shouldn't be called directly
                   13587: 
                   13588:   docuname: username or courseid of destination for the file
                   13589:   docudom: domain of user/course of destination for the file
                   13590:   formname: same as for userfileupload()
1.1090    raeburn  13591:   fname: filename (including subdirectories) for the file
                   13592:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13593:   allfiles: reference to hash used to store objects found by parser
                   13594:   codebase: reference to hash used for codebases of java objects found by parser
                   13595:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13596:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13597:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13598:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13599:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13600:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13601:   mimetype: reference to scalar to accommodate mime type determined
                   13602:             from File::MMagic if $parser = parse.
1.608     albertel 13603: 
                   13604:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13605:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13606:  was 'overwrite').
                   13607:  
1.608     albertel 13608: 
                   13609: =item *
                   13610: 
                   13611: renameuserfile(): renames an existing userfile to a new name
                   13612: 
                   13613:   Args:
                   13614:    docuname: username or courseid of destination for the file
                   13615:    docudom: domain of user/course of destination for the file
                   13616:    old: current file name (including any subdirs under userfiles)
                   13617:    new: desired file name (including any subdirs under userfiles)
                   13618: 
                   13619: =item *
                   13620: 
                   13621: mkdiruserfile(): creates a directory is a userfiles dir
                   13622: 
                   13623:   Args:
                   13624:    docuname: username or courseid of destination for the file
                   13625:    docudom: domain of user/course of destination for the file
                   13626:    dir: dir to create (including any subdirs under userfiles)
                   13627: 
                   13628: =item *
                   13629: 
                   13630: removeuserfile(): removes a file that exists in userfiles
                   13631: 
                   13632:   Args:
                   13633:    docuname: username or courseid of destination for the file
                   13634:    docudom: domain of user/course of destination for the file
                   13635:    fname: filname to delete (including any subdirs under userfiles)
                   13636: 
                   13637: =item *
                   13638: 
                   13639: removeuploadedurl(): convience function for removeuserfile()
                   13640: 
                   13641:   Args:
                   13642:    url:  a full /uploaded/... url to delete
                   13643: 
1.747     albertel 13644: =item * 
                   13645: 
                   13646: get_portfile_permissions():
                   13647:   Args:
                   13648:     domain: domain of user or course contain the portfolio files
                   13649:     user: name of user or num of course contain the portfolio files
                   13650:   Returns:
                   13651:     hashref of a dump of the proper file_permissions.db
                   13652:    
                   13653: 
                   13654: =item * 
                   13655: 
                   13656: get_access_controls():
                   13657: 
                   13658: Args:
                   13659:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13660:   group: (optional) the group you want the files associated with
                   13661:   file: (optional) the file you want access info on
                   13662: 
                   13663: Returns:
1.749     raeburn  13664:     a hash (keys are file names) of hashes containing
                   13665:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13666:         values are XML containing access control settings (see below) 
1.747     albertel 13667: 
                   13668: Internal notes:
                   13669: 
1.749     raeburn  13670:  access controls are stored in file_permissions.db as key=value pairs.
                   13671:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13672:         where scope -> public,guest,course,group,domains or users.
                   13673:               end -> UNIX time for end of access (0 -> no end date)
                   13674:               start -> UNIX time for start of access
                   13675: 
                   13676:     value -> XML description of access control
                   13677:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13678:             <start></start>
                   13679:             <end></end>
                   13680: 
                   13681:             <password></password>  for scope type = guest
                   13682: 
                   13683:             <domain></domain>     for scope type = course or group
                   13684:             <number></number>
                   13685:             <roles id="">
                   13686:              <role></role>
                   13687:              <access></access>
                   13688:              <section></section>
                   13689:              <group></group>
                   13690:             </roles>
                   13691: 
                   13692:             <dom></dom>         for scope type = domains
                   13693: 
                   13694:             <users>             for scope type = users
                   13695:              <user>
                   13696:               <uname></uname>
                   13697:               <udom></udom>
                   13698:              </user>
                   13699:             </users>
                   13700:            </scope> 
                   13701:               
                   13702:  Access data is also aggregated for each file in an additional key=value pair:
                   13703:  key -> path to file/file_name\0accesscontrol 
                   13704:  value -> reference to hash
                   13705:           hash contains key = value pairs
                   13706:           where key = uniqueID:scope_end_start
                   13707:                 value = UNIX time record was last updated
                   13708: 
                   13709:           Used to improve speed of look-ups of access controls for each file.  
                   13710:  
                   13711:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13712: 
1.1198    raeburn  13713: =item *
                   13714: 
1.749     raeburn  13715: modify_access_controls():
                   13716: 
                   13717: Modifies access controls for a portfolio file
                   13718: Args
                   13719: 1. file name
                   13720: 2. reference to hash of required changes,
                   13721: 3. domain
                   13722: 4. username
                   13723:   where domain,username are the domain of the portfolio owner 
                   13724:   (either a user or a course) 
                   13725: 
                   13726: Returns:
                   13727: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13728: 2. result of deletions ('ok' or 'error', with error message).
                   13729: 3. reference to hash of any new or updated access controls.
                   13730: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13731:    key = integer (inbound ID)
1.1198    raeburn  13732:    value = uniqueID
                   13733: 
                   13734: =item *
                   13735: 
                   13736: get_timebased_id():
                   13737: 
                   13738: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13739: course via the Course Editor (e.g., folders, composite pages, 
                   13740: group bulletin boards).
                   13741: 
                   13742: Args: (first three required; six others optional)
                   13743: 
                   13744: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13745:    docssequence, or name of group
                   13746: 
                   13747: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13748:    e.g., num, boardids
                   13749: 
                   13750: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   13751:    file will be named nohist_namespace.db
                   13752: 
                   13753: 4. cdom: domain of course; default is current course domain from %env
                   13754: 
                   13755: 5. cnum: course number; default is current course number from %env
                   13756: 
                   13757: 6. idtype: set to concat if an additional digit is to be appended to the 
                   13758:    unix timestamp to form the suffix, if the plain timestamp is already
                   13759:    in use.  Default is to not do this, but simply increment the unix 
                   13760:    timestamp by 1 until a unique key is obtained.
                   13761: 
                   13762: 7. who: holder of locking key; defaults to user:domain for user.
                   13763: 
                   13764: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   13765:    retrying); default is 3.
                   13766: 
                   13767: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   13768: 
                   13769: Returns:
                   13770: 
                   13771: 1. suffix obtained (numeric)
                   13772: 
                   13773: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13774: 
                   13775: 3. error: contains (localized) error message if an error occurred.
                   13776: 
1.747     albertel 13777: 
1.608     albertel 13778: =back
                   13779: 
1.243     albertel 13780: =head2 HTTP Helper Routines
                   13781: 
                   13782: =over 4
                   13783: 
1.191     harris41 13784: =item *
                   13785: 
                   13786: escape() : unpack non-word characters into CGI-compatible hex codes
                   13787: 
                   13788: =item *
                   13789: 
                   13790: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13791: 
1.243     albertel 13792: =back
                   13793: 
                   13794: =head1 PRIVATE SUBROUTINES
                   13795: 
                   13796: =head2 Underlying communication routines (Shouldn't call)
                   13797: 
                   13798: =over 4
                   13799: 
                   13800: =item *
                   13801: 
                   13802: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13803: 
                   13804: =item *
                   13805: 
                   13806: reply() : uses subreply to send a message to remote machine, logs all failures
                   13807: 
                   13808: =item *
                   13809: 
                   13810: critical() : passes a critical message to another server; if cannot
                   13811: get through then place message in connection buffer directory and
                   13812: returns con_delayed, if incapable of saving message, returns
                   13813: con_failed
                   13814: 
                   13815: =item *
                   13816: 
                   13817: reconlonc() : tries to reconnect lonc client processes.
                   13818: 
                   13819: =back
                   13820: 
                   13821: =head2 Resource Access Logging
                   13822: 
                   13823: =over 4
                   13824: 
                   13825: =item *
                   13826: 
                   13827: flushcourselogs() : flush (save) buffer logs and access logs
                   13828: 
                   13829: =item *
                   13830: 
                   13831: courselog($what) : save message for course in hash
                   13832: 
                   13833: =item *
                   13834: 
                   13835: courseacclog($what) : save message for course using &courselog().  Perform
                   13836: special processing for specific resource types (problems, exams, quizzes, etc).
                   13837: 
1.191     harris41 13838: =item *
                   13839: 
                   13840: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13841: as a PerlChildExitHandler
1.243     albertel 13842: 
                   13843: =back
                   13844: 
                   13845: =head2 Other
                   13846: 
                   13847: =over 4
                   13848: 
                   13849: =item *
                   13850: 
                   13851: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13852: 
                   13853: =back
                   13854: 
                   13855: =cut
1.877     foxr     13856: 

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