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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1303  ! raeburn     4: # $Id: lonnet.pm,v 1.1302 2016/03/02 18:23:17 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.1289    damieng    95: use Time::HiRes qw( sleep 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.1288    damieng   108: my $max_connection_retries = 20;     # 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.
1.1289    damieng   378: 	sleep(0.1);
1.549     foxr      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.1289    damieng   396:         sleep(0.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:     if ($lonid) {
1.1295    raeburn   426:         my $hostname = &hostname($lonid);
1.891     albertel  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.1295    raeburn   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') {
1.1295    raeburn   472: 	&reconlonc($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:             }
1.1288    damieng   489:             sleep 1;
1.1       albertel  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') {
1.1250    raeburn   679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   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'} }) {
1.1279    raeburn   852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    853:                                              $try_server));
1.1123    raeburn   854: 	        ($spare_server, $lowest_load) =
                    855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:             }
1.1083    raeburn   857:         }
1.784     albertel  858: 
1.1123    raeburn   859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    860: 
                    861:         if (!$found_server) {
                    862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   864:                     next unless (&spare_can_host($udom,$uint_dom,
                    865:                                                  $remotesessions,$try_server));
1.1123    raeburn   866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
1.1253    raeburn   889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    890: 
                    891:     if ($required) {
                    892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    895:         if (($major eq '' && $minor eq '') ||
                    896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    897:             return ($spare_server,$lowest_load);
                    898:         }
                    899:     }
1.784     albertel  900: 
                    901:     my $loadans     = &reply('load',    $try_server);
                    902:     my $userloadans = &reply('userload',$try_server);
                    903: 
                    904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  906:     }
                    907: 
                    908:     my $load;
                    909:     if ($loadans =~ /\d/) {
                    910: 	if ($userloadans =~ /\d/) {
                    911: 	    #both are numbers, pick the bigger one
                    912: 	    $load = ($loadans > $userloadans) ? $loadans 
                    913: 		                              : $userloadans;
1.411     albertel  914: 	} else {
1.784     albertel  915: 	    $load = $loadans;
1.411     albertel  916: 	}
1.784     albertel  917:     } else {
                    918: 	$load = $userloadans;
                    919:     }
                    920: 
                    921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    922: 	$spare_server = $try_server;
                    923: 	$lowest_load  = $load;
1.370     albertel  924:     }
1.784     albertel  925:     return ($spare_server,$lowest_load);
1.202     matthew   926: }
1.914     albertel  927: 
                    928: # --------------------------- ask offload servers if user already has a session
                    929: sub find_existing_session {
                    930:     my ($udom,$uname) = @_;
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
                    938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    941:             }
                    942:         }
1.914     albertel  943:     }
                    944:     return;
                    945: }
                    946: 
                    947: # -------------------------------- ask if server already has a session for user
                    948: sub has_user_session {
                    949:     my ($lonid,$udom,$uname) = @_;
                    950:     my $result = &reply(join(':','userhassession',
                    951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    952:     return 1 if ($result eq 'ok');
                    953: 
                    954:     return 0;
                    955: }
                    956: 
1.1076    raeburn   957: # --------- determine least loaded server in a user's domain which allows login
                    958: 
                    959: sub choose_server {
1.1259    raeburn   960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   962:     my %servers = &get_servers($udom);
1.1076    raeburn   963:     my $lowest_load = 30000;
1.1259    raeburn   964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    965:     if ($skiploadbal) {
                    966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    967:         unless (defined($cached)) {
                    968:             my $cachetime = 60*60*24;
                    969:             my %domconfig =
                    970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    973:                                            $cachetime);
                    974:             }
                    975:         }
                    976:     }
1.1076    raeburn   977:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn   978:         if ($skiploadbal) {
                    979:             if (ref($balancers) eq 'HASH') {
                    980:                 next if (exists($balancers->{$lonhost}));
                    981:             }
                    982:         }   
1.1115    raeburn   983:         my $loginvia;
                    984:         if ($checkloginvia) {
                    985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   986:             if ($loginvia) {
                    987:                 my ($server,$path) = split(/:/,$loginvia);
                    988:                 ($login_host, $lowest_load) =
1.1253    raeburn   989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   990:                 if ($login_host eq $server) {
                    991:                     $portal_path = $path;
1.1151    raeburn   992:                     $isredirect = 1;
1.1116    raeburn   993:                 }
                    994:             } else {
                    995:                 ($login_host, $lowest_load) =
1.1253    raeburn   996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $lonhost) {
                    998:                     $portal_path = '';
1.1151    raeburn   999:                     $isredirect = ''; 
1.1116    raeburn  1000:                 }
                   1001:             }
                   1002:         } else {
1.1076    raeburn  1003:             ($login_host, $lowest_load) =
1.1253    raeburn  1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1005:         }
                   1006:     }
                   1007:     if ($login_host ne '') {
1.1116    raeburn  1008:         $hostname = &hostname($login_host);
1.1076    raeburn  1009:     }
1.1151    raeburn  1010:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1011: }
                   1012: 
1.202     matthew  1013: # --------------------------------------------- Try to change a user's password
                   1014: 
                   1015: sub changepass {
1.799     raeburn  1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1017:     $currentpass = &escape($currentpass);
                   1018:     $newpass     = &escape($newpass);
1.1030    raeburn  1019:     my $lonhost = $perlvar{'lonHostID'};
                   1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1021: 		       $server);
                   1022:     if (! $answer) {
                   1023: 	&logthis("No reply on password change request to $server ".
                   1024: 		 "by $uname in domain $udom.");
                   1025:     } elsif ($answer =~ "^ok") {
                   1026:         &logthis("$uname in $udom successfully changed their password ".
                   1027: 		 "on $server.");
                   1028:     } elsif ($answer =~ "^pwchange_failure") {
                   1029: 	&logthis("$uname in $udom was unable to change their password ".
                   1030: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1031: 		 "or pwchange");
                   1032:     } elsif ($answer =~ "^non_authorized") {
                   1033:         &logthis("$uname in $udom did not get their password correct when ".
                   1034: 		 "attempting to change it on $server.");
                   1035:     } elsif ($answer =~ "^auth_mode_error") {
                   1036:         &logthis("$uname in $udom attempted to change their password despite ".
                   1037: 		 "not being locally or internally authenticated on $server.");
                   1038:     } elsif ($answer =~ "^unknown_user") {
                   1039:         &logthis("$uname in $udom attempted to change their password ".
                   1040: 		 "on $server but were unable to because $server is not ".
                   1041: 		 "their home server.");
                   1042:     } elsif ($answer =~ "^refused") {
                   1043: 	&logthis("$server refused to change $uname in $udom password because ".
                   1044: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1045:     } elsif ($answer =~ "invalid_client") {
                   1046:         &logthis("$server refused to change $uname in $udom password because ".
                   1047:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1048:     }
                   1049:     return $answer;
1.1       albertel 1050: }
                   1051: 
1.169     harris41 1052: # ----------------------- Try to determine user's current authentication scheme
                   1053: 
                   1054: sub queryauthenticate {
                   1055:     my ($uname,$udom)=@_;
1.456     albertel 1056:     my $uhome=&homeserver($uname,$udom);
                   1057:     if (!$uhome) {
                   1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1059: 	return 'no_host';
                   1060:     }
                   1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1064:     }
1.456     albertel 1065:     return $answer;
1.169     harris41 1066: }
                   1067: 
1.1       albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1069: 
1.1       albertel 1070: sub authenticate {
1.1073    raeburn  1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1072:     $upass=&escape($upass);
                   1073:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1074:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1075:     my $newhome;
1.836     www      1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1077: # Maybe the machine was offline and only re-appeared again recently?
                   1078:         &reconlonc();
                   1079: # One more
1.952     raeburn  1080: 	$uhome=&homeserver($uname,$udom,1);
                   1081:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1082:             if (defined(&domain($udom,'primary'))) {
                   1083:                 $newhome=&domain($udom,'primary');
                   1084:             }
                   1085:             if ($newhome ne '') {
                   1086:                 $uhome = $newhome;
                   1087:             }
                   1088:         }
1.836     www      1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1091: 	    return 'no_host';
                   1092:         }
1.1       albertel 1093:     }
1.1073    raeburn  1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1095:     if ($answer eq 'authorized') {
1.952     raeburn  1096:         if ($newhome) {
                   1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1098:             return 'no_account_on_host'; 
                   1099:         } else {
                   1100:             &logthis("User $uname at $udom authorized by $uhome");
                   1101:             return $uhome;
                   1102:         }
1.471     albertel 1103:     }
                   1104:     if ($answer eq 'non_authorized') {
                   1105: 	&logthis("User $uname at $udom rejected by $uhome");
                   1106: 	return 'no_host'; 
1.9       www      1107:     }
1.471     albertel 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1109:     return 'no_host';
                   1110: }
                   1111: 
1.1073    raeburn  1112: sub can_host_session {
1.1074    raeburn  1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1114:     my $canhost = 1;
1.1074    raeburn  1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1116:     if (ref($remotesessions) eq 'HASH') {
                   1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1119:                 $canhost = 0;
                   1120:             } else {
                   1121:                 $canhost = 1;
                   1122:             }
                   1123:         }
                   1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 1;
                   1127:             } else {
                   1128:                 $canhost = 0;
                   1129:             }
                   1130:         }
                   1131:         if ($canhost) {
                   1132:             if ($remotesessions->{'version'} ne '') {
                   1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1134:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1136:                         my $major = $1;
                   1137:                         my $minor = $2;
                   1138:                         if (($major < $reqmajor ) ||
                   1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1140:                             $canhost = 0;
                   1141:                         }
                   1142:                     } else {
                   1143:                         $canhost = 0;
                   1144:                     }
                   1145:                 }
                   1146:             }
                   1147:         }
                   1148:     }
                   1149:     if ($canhost) {
                   1150:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1154:                 if (($uint_dom ne '') && 
                   1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1156:                     $canhost = 0;
                   1157:                 } else {
                   1158:                     $canhost = 1;
                   1159:                 }
                   1160:             }
                   1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1162:                 if (($uint_dom ne '') && 
                   1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1164:                     $canhost = 1;
                   1165:                 } else {
                   1166:                     $canhost = 0;
                   1167:                 }
                   1168:             }
                   1169:         }
                   1170:     }
                   1171:     return $canhost;
                   1172: }
                   1173: 
1.1083    raeburn  1174: sub spare_can_host {
                   1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1176:     my $canhost=1;
1.1279    raeburn  1177:     my $try_server_hostname = &hostname($try_server);
                   1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1179:     my $serverhomedom = &host_domain($serverhomeID);
                   1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1183:             $canhost = 0;
                   1184:         }
                   1185:     }
                   1186:     if (($canhost) && ($uint_dom)) {
                   1187:         my @intdoms;
                   1188:         my $internet_names = &get_internet_names($try_server);
                   1189:         if (ref($internet_names) eq 'ARRAY') {
                   1190:             @intdoms = @{$internet_names};
                   1191:         }
                   1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1195:                                          $remotesessions,
                   1196:                                          $defdomdefaults{'hostedsessions'});
                   1197:         }
1.1083    raeburn  1198:     }
                   1199:     return $canhost;
                   1200: }
                   1201: 
1.1123    raeburn  1202: sub this_host_spares {
                   1203:     my ($dom) = @_;
1.1126    raeburn  1204:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1205:     my @hosts = &current_machine_ids();
                   1206:     foreach my $lonhost (@hosts) {
                   1207:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1208:             $dom_in_use = $dom;
                   1209:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1210:             last;
                   1211:         }
                   1212:     }
1.1126    raeburn  1213:     if ($dom_in_use ne '') {
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:     }
                   1216:     if (ref($result) ne 'HASH') {
                   1217:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1218:         $dom_in_use = &host_domain($lonhost_in_use);
                   1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1220:         if (ref($result) ne 'HASH') {
                   1221:             $result = \%spareid;
                   1222:         }
                   1223:     }
                   1224:     return $result;
                   1225: }
                   1226: 
                   1227: sub spares_for_offload  {
                   1228:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1230:     if (defined($cached)) {
                   1231:         return $result;
                   1232:     } else {
1.1126    raeburn  1233:         my $cachetime = 60*60*24;
                   1234:         my %domconfig =
                   1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1240:                 }
                   1241:             }
                   1242:         }
                   1243:     }
1.1126    raeburn  1244:     return;
1.1123    raeburn  1245: }
                   1246: 
1.1129    raeburn  1247: sub get_lonbalancer_config {
                   1248:     my ($servers) = @_;
                   1249:     my ($currbalancer,$currtargets);
                   1250:     if (ref($servers) eq 'HASH') {
                   1251:         foreach my $server (keys(%{$servers})) {
                   1252:             my %what = (
                   1253:                          spareid => 1,
                   1254:                          perlvar => 1,
                   1255:                        );
                   1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1257:             if ($result eq 'ok') {
                   1258:                 if (ref($returnhash) eq 'HASH') {
                   1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1261:                             $currbalancer = $server;
                   1262:                             $currtargets = {};
                   1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1266:                                 }
                   1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1269:                                 }
                   1270:                             }
                   1271:                             last;
                   1272:                         }
                   1273:                     }
                   1274:                 }
                   1275:             }
                   1276:         }
                   1277:     }
                   1278:     return ($currbalancer,$currtargets);
                   1279: }
                   1280: 
                   1281: sub check_loadbalancing {
                   1282:     my ($uname,$udom) = @_;
1.1191    raeburn  1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1284:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1285:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1286:     my @hosts = &current_machine_ids();
1.1129    raeburn  1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1290:     my $serverhomedom = &host_domain($lonhost);
                   1291: 
                   1292:     my $cachetime = 60*60*24;
                   1293: 
                   1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1295:         $dom_in_use = $udom;
                   1296:         $homeintdom = 1;
                   1297:     } else {
                   1298:         $dom_in_use = $serverhomedom;
                   1299:     }
                   1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1301:     unless (defined($cached)) {
                   1302:         my %domconfig =
                   1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1306:         }
                   1307:     }
                   1308:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1309:         ($is_balancer,$currtargets,$currrules) = 
                   1310:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1311:         if ($is_balancer) {
                   1312:             if (ref($currrules) eq 'HASH') {
                   1313:                 if ($homeintdom) {
                   1314:                     if ($uname ne '') {
                   1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1321:                             }
                   1322:                         }
                   1323:                         if ($rule_in_effect eq '') {
                   1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1325:                             if ($userenv{'inststatus'} ne '') {
                   1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1327:                                 my ($othertitle,$usertypes,$types) =
                   1328:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1329:                                 if (ref($types) eq 'ARRAY') {
                   1330:                                     foreach my $type (@{$types}) {
                   1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1332:                                             if (exists($currrules->{$type})) {
                   1333:                                                 $rule_in_effect = $currrules->{$type};
                   1334:                                             }
                   1335:                                         }
                   1336:                                     }
                   1337:                                 }
                   1338:                             } else {
                   1339:                                 if (exists($currrules->{'default'})) {
                   1340:                                     $rule_in_effect = $currrules->{'default'};
                   1341:                                 }
                   1342:                             }
                   1343:                         }
                   1344:                     } else {
                   1345:                         if (exists($currrules->{'default'})) {
                   1346:                             $rule_in_effect = $currrules->{'default'};
                   1347:                         }
                   1348:                     }
                   1349:                 } else {
                   1350:                     if ($currrules->{'_LC_external'} ne '') {
                   1351:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1352:                     }
                   1353:                 }
                   1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1355:                                                        $uname,$udom);
                   1356:             }
                   1357:         }
                   1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1360:         unless (defined($cached)) {
                   1361:             my %domconfig =
                   1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1365:             }
                   1366:         }
                   1367:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1368:             ($is_balancer,$currtargets,$currrules) = 
                   1369:                 &check_balancer_result($result,@hosts);
                   1370:             if ($is_balancer) {
1.1129    raeburn  1371:                 if (ref($currrules) eq 'HASH') {
                   1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1374:                     }
                   1375:                 }
                   1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1377:                                                        $uname,$udom);
                   1378:             }
                   1379:         } else {
                   1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1381:                 $is_balancer = 1;
                   1382:                 $offloadto = &this_host_spares($dom_in_use);
                   1383:             }
                   1384:         }
                   1385:     } else {
                   1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1387:             $is_balancer = 1;
                   1388:             $offloadto = &this_host_spares($dom_in_use);
                   1389:         }
                   1390:     }
1.1176    raeburn  1391:     if ($is_balancer) {
                   1392:         my $lowest_load = 30000;
                   1393:         if (ref($offloadto) eq 'HASH') {
                   1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1396:                     ($otherserver,$lowest_load) =
                   1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1398:                 }
1.1129    raeburn  1399:             }
1.1176    raeburn  1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1401: 
1.1176    raeburn  1402:             if (!$found_server) {
                   1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1405:                         ($otherserver,$lowest_load) =
                   1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1407:                     }
                   1408:                 }
                   1409:             }
                   1410:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1411:             if (@{$offloadto} == 1) {
                   1412:                 $otherserver = $offloadto->[0];
                   1413:             } elsif (@{$offloadto} > 1) {
                   1414:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1415:                     ($otherserver,$lowest_load) =
                   1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1417:                 }
                   1418:             }
                   1419:         }
1.1176    raeburn  1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1421:             $is_balancer = 0;
                   1422:             if ($uname ne '' && $udom ne '') {
                   1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1424:                     
                   1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1426:                              'user.loadbalcheck.time' => time});
                   1427:                 }
1.1129    raeburn  1428:             }
                   1429:         }
                   1430:     }
                   1431:     return ($is_balancer,$otherserver);
                   1432: }
                   1433: 
1.1191    raeburn  1434: sub check_balancer_result {
                   1435:     my ($result,@hosts) = @_;
                   1436:     my ($is_balancer,$currtargets,$currrules);
                   1437:     if (ref($result) eq 'HASH') {
                   1438:         if ($result->{'lonhost'} ne '') {
                   1439:             my $currbalancer = $result->{'lonhost'};
                   1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1441:                 $is_balancer = 1;
                   1442:                 $currtargets = $result->{'targets'};
                   1443:                 $currrules = $result->{'rules'};
                   1444:             }
                   1445:         } else {
                   1446:             foreach my $key (keys(%{$result})) {
                   1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1448:                     (ref($result->{$key}) eq 'HASH')) {
                   1449:                     $is_balancer = 1;
                   1450:                     $currrules = $result->{$key}{'rules'};
                   1451:                     $currtargets = $result->{$key}{'targets'};
                   1452:                     last;
                   1453:                 }
                   1454:             }
                   1455:         }
                   1456:     }
                   1457:     return ($is_balancer,$currtargets,$currrules);
                   1458: }
                   1459: 
1.1129    raeburn  1460: sub get_loadbalancer_targets {
                   1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1462:     my $offloadto;
1.1175    raeburn  1463:     if ($rule_in_effect eq 'none') {
                   1464:         return [$perlvar{'lonHostID'}];
                   1465:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1466:         $offloadto = $currtargets;
                   1467:     } else {
                   1468:         if ($rule_in_effect eq 'homeserver') {
                   1469:             my $homeserver = &homeserver($uname,$udom);
                   1470:             if ($homeserver ne 'no_host') {
                   1471:                 $offloadto = [$homeserver];
                   1472:             }
                   1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1474:             my %domconfig =
                   1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1480:                     }
                   1481:                 }
                   1482:             } else {
1.1178    raeburn  1483:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1485:                 if (&hostname($remotebalancer) ne '') {
                   1486:                     $offloadto = [$remotebalancer];
                   1487:                 }
                   1488:             }
                   1489:         } elsif (&hostname($rule_in_effect) ne '') {
                   1490:             $offloadto = [$rule_in_effect];
                   1491:         }
                   1492:     }
                   1493:     return $offloadto;
                   1494: }
                   1495: 
1.1127    raeburn  1496: sub internet_dom_servers {
                   1497:     my ($dom) = @_;
                   1498:     my (%uniqservers,%servers);
                   1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1500:     my @machinedoms = &machine_domains($primaryserver);
                   1501:     foreach my $mdom (@machinedoms) {
                   1502:         my %currservers = %servers;
                   1503:         my %server = &get_servers($mdom);
                   1504:         %servers = (%currservers,%server);
                   1505:     }
                   1506:     my %by_hostname;
                   1507:     foreach my $id (keys(%servers)) {
                   1508:         push(@{$by_hostname{$servers{$id}}},$id);
                   1509:     }
                   1510:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1511:         if (@{$by_hostname{$hostname}} > 1) {
                   1512:             my $match = 0;
                   1513:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1514:                 if (&host_domain($id) eq $dom) {
                   1515:                     $uniqservers{$id} = $hostname;
                   1516:                     $match = 1;
                   1517:                 }
                   1518:             }
                   1519:             unless ($match) {
                   1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1521:             }
                   1522:         } else {
                   1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1524:         }
                   1525:     }
                   1526:     return %uniqservers;
                   1527: }
                   1528: 
1.1       albertel 1529: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1530: 
1.599     albertel 1531: my %homecache;
1.1       albertel 1532: sub homeserver {
1.230     stredwic 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1534:     my $index="$uname:$udom";
1.426     albertel 1535: 
1.599     albertel 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1537: 
                   1538:     my %servers = &get_servers($udom,'library');
                   1539:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1540:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1541: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1542: 
                   1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1544: 	if ($answer eq 'found') {
                   1545: 	    delete($badServerCache{$tryserver}); 
                   1546: 	    return $homecache{$index}=$tryserver;
                   1547: 	} elsif ($answer eq 'no_host') {
                   1548: 	    $badServerCache{$tryserver}=1;
                   1549: 	}
1.1       albertel 1550:     }    
                   1551:     return 'no_host';
1.70      www      1552: }
                   1553: 
1.1300    raeburn  1554: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1555: 
                   1556: sub idget {
1.1300    raeburn  1557:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1558:     my %returnhash=();
1.1300    raeburn  1559:     my @ids=(); 
                   1560:     if (ref($idsref) eq 'ARRAY') {
                   1561:         @ids = @{$idsref};
                   1562:     } else {
                   1563:         return %returnhash; 
                   1564:     }
                   1565:     if ($namespace eq '') {
                   1566:         $namespace = 'ids';
                   1567:     }
1.70      www      1568:     
1.841     albertel 1569:     my %servers = &get_servers($udom,'library');
                   1570:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1571: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1572: 	if ($namespace eq 'ids') {
                   1573: 	    $idlist=~tr/A-Z/a-z/;
                   1574: 	}
                   1575: 	my $reply;
                   1576: 	if ($namespace eq 'ids') {
                   1577: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1578: 	} else {
                   1579: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1580: 	}
1.841     albertel 1581: 	my @answer=();
                   1582: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1583: 	    @answer=split(/\&/,$reply);
                   1584: 	}                    ;
                   1585: 	my $i;
                   1586: 	for ($i=0;$i<=$#ids;$i++) {
                   1587: 	    if ($answer[$i]) {
1.1299    raeburn  1588: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1589: 	    }
1.841     albertel 1590: 	}
1.1300    raeburn  1591:     }
1.70      www      1592:     return %returnhash;
                   1593: }
                   1594: 
                   1595: # ------------------------------------- Find the IDs behind a list of usernames
                   1596: 
                   1597: sub idrget {
                   1598:     my ($udom,@unames)=@_;
                   1599:     my %returnhash=();
1.800     albertel 1600:     foreach my $uname (@unames) {
                   1601:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1602:     }
1.70      www      1603:     return %returnhash;
                   1604: }
                   1605: 
1.1300    raeburn  1606: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1607: 
                   1608: sub idput {
1.1300    raeburn  1609:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1610:     my %servers=();
1.1300    raeburn  1611:     my %ids=();
                   1612:     my %byid = ();
                   1613:     if (ref($idsref) eq 'HASH') {
                   1614:         %ids=%{$idsref};
                   1615:     }
                   1616:     if ($namespace eq '') {
                   1617:         $namespace = 'ids'; 
                   1618:     }
1.800     albertel 1619:     foreach my $uname (keys(%ids)) {
                   1620: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1621:         if ($uhom eq '') {
                   1622:             $uhom=&homeserver($uname,$udom);
                   1623:         }
1.70      www      1624:         if ($uhom ne 'no_host') {
1.800     albertel 1625:             my $esc_unam=&escape($uname);
1.1300    raeburn  1626:             if ($namespace eq 'ids') {
                   1627:                 my $id=&escape($ids{$uname});
                   1628:                 $id=~tr/A-Z/a-z/;
                   1629:                 my $esc_unam=&escape($uname);
                   1630:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1631:             } else {
1.1300    raeburn  1632:                 my @currids = split(/,/,$ids{$uname});
                   1633:                 foreach my $id (@currids) {
                   1634:                     $byid{$uhom}{$id} .= $uname.',';
                   1635:                 }
                   1636:             }
                   1637:         }
                   1638:     }
                   1639:     if ($namespace eq 'clickers') {
                   1640:         foreach my $server (keys(%byid)) {
                   1641:             if (ref($byid{$server}) eq 'HASH') {
                   1642:                 foreach my $id (keys(%{$byid{$server}})) {
                   1643:                     $byid{$server} =~ s/,$//;
                   1644:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1645:                 }
1.70      www      1646:             }
                   1647:         }
1.191     harris41 1648:     }
1.800     albertel 1649:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1650:         $servers{$server} =~ s/\&$//;
                   1651:         if ($namespace eq 'ids') {     
                   1652:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1653:         } else {
                   1654:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1655:         }
1.191     harris41 1656:     }
1.344     www      1657: }
                   1658: 
1.1300    raeburn  1659: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1660: 
                   1661: sub iddel {
1.1300    raeburn  1662:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1663:     my %result=();
1.1300    raeburn  1664:     my %ids=();
                   1665:     my %byid = ();
                   1666:     if (ref($idshashref) eq 'HASH') {
                   1667:         %ids=%{$idshashref};
                   1668:     } else {
1.1231    raeburn  1669:         return %result;
                   1670:     }
1.1300    raeburn  1671:     if ($namespace eq '') {
                   1672:         $namespace = 'ids';
                   1673:     }
1.1231    raeburn  1674:     my %servers=();
1.1300    raeburn  1675:     while (my ($id,$unamestr) = each(%ids)) {
                   1676:         if ($namespace eq 'ids') {
                   1677:             my $uhom = $uhome;
                   1678:             if ($uhom eq '') { 
                   1679:                 $uhom=&homeserver($unamestr,$udom);
                   1680:             }
                   1681:             if ($uhom ne 'no_host') {
                   1682:                 $servers{$uhom}.='&'.&escape($id);
                   1683:             }
                   1684:          } else {
                   1685:             my @curritems = split(/,/,$ids{$id});
                   1686:             foreach my $uname (@curritems) {
                   1687:                 my $uhom = $uhome;
                   1688:                 if ($uhom eq '') {
                   1689:                     $uhom=&homeserver($uname,$udom);
                   1690:                 }
                   1691:                 if ($uhom ne 'no_host') { 
                   1692:                     $byid{$uhom}{$id} .= $uname.',';
                   1693:                 }
                   1694:             }
1.1231    raeburn  1695:         }
1.1300    raeburn  1696:     }
                   1697:     if ($namespace eq 'clickers') {
                   1698:         foreach my $server (keys(%byid)) {
                   1699:             if (ref($byid{$server}) eq 'HASH') {
                   1700:                 foreach my $id (keys(%{$byid{$server}})) {
                   1701:                     $byid{$server}{$id} =~ s/,$//;
                   1702:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1703:                 }
1.1231    raeburn  1704:             }
                   1705:         }
                   1706:     }
                   1707:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1708:         $servers{$server} =~ s/\&$//;
                   1709:         if ($namespace eq 'ids') {
                   1710:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1711:         } elsif ($namespace eq 'clickers') {
                   1712:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1713:         }
1.1231    raeburn  1714:     }
                   1715:     return %result;
                   1716: }
                   1717: 
1.1300    raeburn  1718: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1719: 
                   1720: sub updateclickers {
                   1721:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1722:     my %clickers;
                   1723:     if (ref($idshashref) eq 'HASH') {
                   1724:         %clickers=%{$idshashref};
                   1725:     } else {
                   1726:         return;
                   1727:     }
                   1728:     my $items='';
                   1729:     foreach my $item (keys(%clickers)) {
                   1730:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1731:     }
                   1732:     $items=~s/\&$//;
                   1733:     my $request = "updateclickers:$udom:$action:$items";
                   1734:     if ($critical) {
                   1735:         return &critical($request,$uhome);
                   1736:     } else {
                   1737:         return &reply($request,$uhome);
                   1738:     }
                   1739: }
                   1740: 
1.1023    raeburn  1741: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1742: sub dump_dom {
1.1165    droeschl 1743:     my ($namespace, $udom, $regexp) = @_;
                   1744: 
                   1745:     $udom ||= $env{'user.domain'};
                   1746: 
                   1747:     return () unless $udom;
                   1748: 
                   1749:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1750: }
                   1751: 
1.1023    raeburn  1752: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1753: 
                   1754: sub get_dom {
1.860     raeburn  1755:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1756:     return if ($udom eq 'public');
1.806     raeburn  1757:     my $items='';
                   1758:     foreach my $item (@$storearr) {
                   1759:         $items.=&escape($item).'&';
                   1760:     }
                   1761:     $items=~s/\&$//;
1.860     raeburn  1762:     if (!$udom) {
                   1763:         $udom=$env{'user.domain'};
1.1267    raeburn  1764:         return if ($udom eq 'public');
1.860     raeburn  1765:         if (defined(&domain($udom,'primary'))) {
                   1766:             $uhome=&domain($udom,'primary');
                   1767:         } else {
1.874     albertel 1768:             undef($uhome);
1.860     raeburn  1769:         }
                   1770:     } else {
                   1771:         if (!$uhome) {
                   1772:             if (defined(&domain($udom,'primary'))) {
                   1773:                 $uhome=&domain($udom,'primary');
                   1774:             }
                   1775:         }
                   1776:     }
                   1777:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1778:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1779:         my %returnhash;
1.875     albertel 1780:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1781:             return %returnhash;
                   1782:         }
1.806     raeburn  1783:         my @pairs=split(/\&/,$rep);
                   1784:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1785:             return @pairs;
                   1786:         }
                   1787:         my $i=0;
                   1788:         foreach my $item (@$storearr) {
                   1789:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1790:             $i++;
                   1791:         }
                   1792:         return %returnhash;
                   1793:     } else {
1.880     banghart 1794:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1795:     }
                   1796: }
                   1797: 
                   1798: # -------------------------------------------- put items in domain db files 
                   1799: 
                   1800: sub put_dom {
1.860     raeburn  1801:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1802:     if (!$udom) {
                   1803:         $udom=$env{'user.domain'};
                   1804:         if (defined(&domain($udom,'primary'))) {
                   1805:             $uhome=&domain($udom,'primary');
                   1806:         } else {
1.874     albertel 1807:             undef($uhome);
1.860     raeburn  1808:         }
                   1809:     } else {
                   1810:         if (!$uhome) {
                   1811:             if (defined(&domain($udom,'primary'))) {
                   1812:                 $uhome=&domain($udom,'primary');
                   1813:             }
                   1814:         }
                   1815:     } 
                   1816:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1817:         my $items='';
                   1818:         foreach my $item (keys(%$storehash)) {
                   1819:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1820:         }
                   1821:         $items=~s/\&$//;
                   1822:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1823:     } else {
1.860     raeburn  1824:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1825:     }
                   1826: }
                   1827: 
1.1023    raeburn  1828: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1829: sub newput_dom {
1.1023    raeburn  1830:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1831:     my $result;
                   1832:     if (!$udom) {
                   1833:         $udom=$env{'user.domain'};
                   1834:     }
1.1023    raeburn  1835:     if ($udom) {
                   1836:         my $uname = &get_domainconfiguser($udom);
                   1837:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1838:     }
                   1839:     return $result;
                   1840: }
                   1841: 
1.1023    raeburn  1842: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1843: sub del_dom {
1.1023    raeburn  1844:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1845:     if (ref($storearr) eq 'ARRAY') {
                   1846:         if (!$udom) {
                   1847:             $udom=$env{'user.domain'};
                   1848:         }
1.1023    raeburn  1849:         if ($udom) {
                   1850:             my $uname = &get_domainconfiguser($udom); 
                   1851:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1852:         }
                   1853:     }
                   1854: }
                   1855: 
1.1023    raeburn  1856: # ----------------------------------construct domainconfig user for a domain 
                   1857: sub get_domainconfiguser {
                   1858:     my ($udom) = @_;
                   1859:     return $udom.'-domainconfig';
                   1860: }
                   1861: 
1.837     raeburn  1862: sub retrieve_inst_usertypes {
                   1863:     my ($udom) = @_;
                   1864:     my (%returnhash,@order);
1.989     raeburn  1865:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1866:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1867:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1868:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1869:     } else {
                   1870:         if (defined(&domain($udom,'primary'))) {
                   1871:             my $uhome=&domain($udom,'primary');
                   1872:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1873:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1874:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1875:                 return (\%returnhash,\@order);
                   1876:             }
                   1877:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1878:             my @pairs=split(/\&/,$hashitems);
                   1879:             foreach my $item (@pairs) {
                   1880:                 my ($key,$value)=split(/=/,$item,2);
                   1881:                 $key = &unescape($key);
                   1882:                 next if ($key =~ /^error: 2 /);
                   1883:                 $returnhash{$key}=&thaw_unescape($value);
                   1884:             }
                   1885:             my @esc_order = split(/\&/,$orderitems);
                   1886:             foreach my $item (@esc_order) {
                   1887:                 push(@order,&unescape($item));
                   1888:             }
                   1889:         } else {
1.1256    raeburn  1890:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1891:         }
1.1256    raeburn  1892:         return (\%returnhash,\@order);
1.837     raeburn  1893:     }
                   1894: }
                   1895: 
1.868     raeburn  1896: sub is_domainimage {
                   1897:     my ($url) = @_;
                   1898:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1899:         if (&domain($1) ne '') {
                   1900:             return '1';
                   1901:         }
                   1902:     }
                   1903:     return;
                   1904: }
                   1905: 
1.899     raeburn  1906: sub inst_directory_query {
                   1907:     my ($srch) = @_;
                   1908:     my $udom = $srch->{'srchdomain'};
                   1909:     my %results;
                   1910:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1911:     my $outcome;
1.899     raeburn  1912:     if ($homeserver ne '') {
1.904     albertel 1913: 	my $queryid=&reply("querysend:instdirsearch:".
                   1914: 			   &escape($srch->{'srchby'}).':'.
                   1915: 			   &escape($srch->{'srchterm'}).':'.
                   1916: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1917: 	my $host=&hostname($homeserver);
                   1918: 	if ($queryid !~/^\Q$host\E\_/) {
                   1919: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1920: 	    return;
                   1921: 	}
                   1922: 	my $response = &get_query_reply($queryid);
                   1923: 	my $maxtries = 5;
                   1924: 	my $tries = 1;
                   1925: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1926: 	    $response = &get_query_reply($queryid);
                   1927: 	    $tries ++;
                   1928: 	}
                   1929: 
                   1930:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1931:             if ($response eq 'unavailable') {
                   1932:                 $outcome = $response;
                   1933:             } else {
                   1934:                 $outcome = 'ok';
                   1935:                 my @matches = split(/\n/,$response);
                   1936:                 foreach my $match (@matches) {
                   1937:                     my ($key,$value) = split(/=/,$match);
                   1938:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1939:                 }
1.899     raeburn  1940:             }
                   1941:         }
                   1942:     }
1.909     raeburn  1943:     return ($outcome,%results);
1.899     raeburn  1944: }
                   1945: 
                   1946: sub usersearch {
                   1947:     my ($srch) = @_;
                   1948:     my $dom = $srch->{'srchdomain'};
                   1949:     my %results;
                   1950:     my %libserv = &all_library();
                   1951:     my $query = 'usersearch';
                   1952:     foreach my $tryserver (keys(%libserv)) {
                   1953:         if (&host_domain($tryserver) eq $dom) {
                   1954:             my $host=&hostname($tryserver);
                   1955:             my $queryid=
1.911     raeburn  1956:                 &reply("querysend:".&escape($query).':'.
                   1957:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1958:                        &escape($srch->{'srchtype'}).':'.
                   1959:                        &escape($srch->{'srchterm'}),$tryserver);
                   1960:             if ($queryid !~/^\Q$host\E\_/) {
                   1961:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1962:                 next;
1.899     raeburn  1963:             }
                   1964:             my $reply = &get_query_reply($queryid);
                   1965:             my $maxtries = 1;
                   1966:             my $tries = 1;
                   1967:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1968:                 $reply = &get_query_reply($queryid);
                   1969:                 $tries ++;
                   1970:             }
                   1971:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1972:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1973:             } else {
1.911     raeburn  1974:                 my @matches;
                   1975:                 if ($reply =~ /\n/) {
                   1976:                     @matches = split(/\n/,$reply);
                   1977:                 } else {
                   1978:                     @matches = split(/\&/,$reply);
                   1979:                 }
1.899     raeburn  1980:                 foreach my $match (@matches) {
                   1981:                     my ($uname,$udom,%userhash);
1.911     raeburn  1982:                     foreach my $entry (split(/:/,$match)) {
                   1983:                         my ($key,$value) =
                   1984:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1985:                         $userhash{$key} = $value;
                   1986:                         if ($key eq 'username') {
                   1987:                             $uname = $value;
                   1988:                         } elsif ($key eq 'domain') {
                   1989:                             $udom = $value;
1.911     raeburn  1990:                         }
1.899     raeburn  1991:                     }
                   1992:                     $results{$uname.':'.$udom} = \%userhash;
                   1993:                 }
                   1994:             }
                   1995:         }
                   1996:     }
                   1997:     return %results;
                   1998: }
                   1999: 
1.912     raeburn  2000: sub get_instuser {
                   2001:     my ($udom,$uname,$id) = @_;
                   2002:     my $homeserver = &domain($udom,'primary');
                   2003:     my ($outcome,%results);
                   2004:     if ($homeserver ne '') {
                   2005:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2006:                            &escape($id).':'.&escape($udom),$homeserver);
                   2007:         my $host=&hostname($homeserver);
                   2008:         if ($queryid !~/^\Q$host\E\_/) {
                   2009:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2010:             return;
                   2011:         }
                   2012:         my $response = &get_query_reply($queryid);
                   2013:         my $maxtries = 5;
                   2014:         my $tries = 1;
                   2015:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2016:             $response = &get_query_reply($queryid);
                   2017:             $tries ++;
                   2018:         }
                   2019:         if (!&error($response) && $response ne 'refused') {
                   2020:             if ($response eq 'unavailable') {
                   2021:                 $outcome = $response;
                   2022:             } else {
                   2023:                 $outcome = 'ok';
                   2024:                 my @matches = split(/\n/,$response);
                   2025:                 foreach my $match (@matches) {
                   2026:                     my ($key,$value) = split(/=/,$match);
                   2027:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2028:                 }
                   2029:             }
                   2030:         }
                   2031:     }
                   2032:     my %userinfo;
                   2033:     if (ref($results{$uname}) eq 'HASH') {
                   2034:         %userinfo = %{$results{$uname}};
                   2035:     } 
                   2036:     return ($outcome,%userinfo);
                   2037: }
                   2038: 
1.1290    raeburn  2039: sub get_multiple_instusers {
                   2040:     my ($udom,$users,$caller) = @_;
                   2041:     my ($outcome,$results);
                   2042:     if (ref($users) eq 'HASH') {
                   2043:         my $count = keys(%{$users}); 
                   2044:         my $requested = &freeze_escape($users);
                   2045:         my $homeserver = &domain($udom,'primary');
                   2046:         if ($homeserver ne '') {
                   2047:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2048:             my $host=&hostname($homeserver);
                   2049:             if ($queryid !~/^\Q$host\E\_/) {
                   2050:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2051:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2052:                 return ($outcome,$results);
                   2053:             }
                   2054:             my $response = &get_query_reply($queryid);
                   2055:             my $maxtries = 5;
                   2056:             if ($count > 100) {
                   2057:                 $maxtries = 1+int($count/20);
                   2058:             }
                   2059:             my $tries = 1;
                   2060:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2061:                 $response = &get_query_reply($queryid);
                   2062:                 $tries ++;
                   2063:             }
                   2064:             if ($response eq '') {
                   2065:                 $results = {};
                   2066:                 foreach my $key (keys(%{$users})) {
                   2067:                     my ($uname,$id);
                   2068:                     if ($caller eq 'id') {
                   2069:                         $id = $key;
                   2070:                     } else {
                   2071:                         $uname = $key;
                   2072:                     }
                   2073:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2074:                     $outcome = $resp;
1.1290    raeburn  2075:                     if ($resp eq 'ok') {
                   2076:                         %{$results} = (%{$results}, %info);
                   2077:                     } else {
                   2078:                         last;
                   2079:                     }
                   2080:                 }
                   2081:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2082:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2083:                     $outcome = $response;
                   2084:                 } else {
1.1291    raeburn  2085:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2086:                     if ($outcome eq 'ok') {
                   2087:                         $results = &thaw_unescape($userdata); 
                   2088:                     }
                   2089:                 }
                   2090:             }
                   2091:         }
                   2092:     }
                   2093:     return ($outcome,$results);
                   2094: }
                   2095: 
1.912     raeburn  2096: sub inst_rulecheck {
1.923     raeburn  2097:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2098:     my %returnhash;
                   2099:     if ($udom ne '') {
                   2100:         if (ref($rules) eq 'ARRAY') {
                   2101:             @{$rules} = map {&escape($_);} (@{$rules});
                   2102:             my $rulestr = join(':',@{$rules});
                   2103:             my $homeserver=&domain($udom,'primary');
                   2104:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2105:                 my $response;
                   2106:                 if ($item eq 'username') {                
                   2107:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2108:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2109:                                               $homeserver));
1.923     raeburn  2110:                 } elsif ($item eq 'id') {
                   2111:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2112:                                               ':'.&escape($id).':'.$rulestr,
                   2113:                                               $homeserver));
1.945     raeburn  2114:                 } elsif ($item eq 'selfcreate') {
                   2115:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2116:                                                &escape($udom).':'.&escape($uname).
                   2117:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2118:                 }
1.912     raeburn  2119:                 if ($response ne 'refused') {
                   2120:                     my @pairs=split(/\&/,$response);
                   2121:                     foreach my $item (@pairs) {
                   2122:                         my ($key,$value)=split(/=/,$item,2);
                   2123:                         $key = &unescape($key);
                   2124:                         next if ($key =~ /^error: 2 /);
                   2125:                         $returnhash{$key}=&thaw_unescape($value);
                   2126:                     }
                   2127:                 }
                   2128:             }
                   2129:         }
                   2130:     }
                   2131:     return %returnhash;
                   2132: }
                   2133: 
                   2134: sub inst_userrules {
1.923     raeburn  2135:     my ($udom,$check) = @_;
1.912     raeburn  2136:     my (%ruleshash,@ruleorder);
                   2137:     if ($udom ne '') {
                   2138:         my $homeserver=&domain($udom,'primary');
                   2139:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2140:             my $response;
                   2141:             if ($check eq 'id') {
                   2142:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2143:                                  $homeserver);
1.943     raeburn  2144:             } elsif ($check eq 'email') {
                   2145:                 $response=&reply('instemailrules:'.&escape($udom),
                   2146:                                  $homeserver);
1.923     raeburn  2147:             } else {
                   2148:                 $response=&reply('instuserrules:'.&escape($udom),
                   2149:                                  $homeserver);
                   2150:             }
1.912     raeburn  2151:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2152:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2153:                 ($response ne 'no_such_host')) {
                   2154:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2155:                 my @pairs=split(/\&/,$hashitems);
                   2156:                 foreach my $item (@pairs) {
                   2157:                     my ($key,$value)=split(/=/,$item,2);
                   2158:                     $key = &unescape($key);
                   2159:                     next if ($key =~ /^error: 2 /);
                   2160:                     $ruleshash{$key}=&thaw_unescape($value);
                   2161:                 }
                   2162:                 my @esc_order = split(/\&/,$orderitems);
                   2163:                 foreach my $item (@esc_order) {
                   2164:                     push(@ruleorder,&unescape($item));
                   2165:                 }
                   2166:             }
                   2167:         }
                   2168:     }
                   2169:     return (\%ruleshash,\@ruleorder);
                   2170: }
                   2171: 
1.976     raeburn  2172: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2173: 
                   2174: sub get_domain_defaults {
1.1240    raeburn  2175:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2176:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2177:     my $cachetime = 60*60*24;
1.1240    raeburn  2178:     unless ($ignore_cache) {
                   2179:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2180:         if (defined($cached)) {
                   2181:             if (ref($result) eq 'HASH') {
                   2182:                 return %{$result};
                   2183:             }
1.943     raeburn  2184:         }
                   2185:     }
                   2186:     my %domdefaults;
                   2187:     my %domconfig =
1.989     raeburn  2188:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2189:                                   'requestcourses','inststatus',
1.1183    raeburn  2190:                                   'coursedefaults','usersessions',
1.1258    raeburn  2191:                                   'requestauthor','selfenrollment',
                   2192:                                   'coursecategories'],$domain);
1.1254    raeburn  2193:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2194:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2195:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2196:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2197:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2198:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2199:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2200:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2201:     } else {
                   2202:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2203:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2204:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2205:     }
1.976     raeburn  2206:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2207:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2208:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2209:         } else {
                   2210:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2211:         }
1.1177    raeburn  2212:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2213:         foreach my $item (@usertools) {
                   2214:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2215:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2216:             }
                   2217:         }
1.1229    raeburn  2218:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2219:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2220:         }
1.976     raeburn  2221:     }
1.985     raeburn  2222:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246    raeburn  2223:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2224:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2225:         }
                   2226:     }
1.1183    raeburn  2227:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2228:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2229:     }
1.989     raeburn  2230:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2231:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2232:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2233:         }
                   2234:     }
1.1047    raeburn  2235:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2236:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2237:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2238:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2239:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2240:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2241:         }
1.1254    raeburn  2242:         foreach my $type (@coursetypes) {
                   2243:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2244:                 unless ($type eq 'community') {
                   2245:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2246:                 }
                   2247:             }
                   2248:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2249:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2250:             }
1.1277    raeburn  2251:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2252:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2253:                     $domdefaults{$type.'postsubtimeout'} = 
                   2254:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2255:                 }
                   2256:             }
1.1230    raeburn  2257:         }
1.1286    raeburn  2258:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2259:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2260:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2261:                 if (@clonecodes) {
                   2262:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2263:                 }
                   2264:             }
                   2265:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2266:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2267:         }
1.1047    raeburn  2268:     }
1.1073    raeburn  2269:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2270:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2271:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2272:         }
                   2273:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2274:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2275:         }
1.1279    raeburn  2276:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2277:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2278:         }
1.1073    raeburn  2279:     }
1.1254    raeburn  2280:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2281:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2282:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2283:                             'approval','limit');
                   2284:             foreach my $type (@coursetypes) {
                   2285:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2286:                     my @mgrdc = ();
                   2287:                     foreach my $item (@settings) {
                   2288:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2289:                             push(@mgrdc,$item);
                   2290:                         }
                   2291:                     }
                   2292:                     if (@mgrdc) {
                   2293:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2294:                     }
                   2295:                 }
                   2296:             }
                   2297:         }
                   2298:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2299:             foreach my $type (@coursetypes) {
                   2300:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2301:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2302:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2303:                     }
                   2304:                 }
                   2305:             }
                   2306:         }
                   2307:     }
1.1258    raeburn  2308:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2309:         $domdefaults{'catauth'} = 'std';
                   2310:         $domdefaults{'catunauth'} = 'std';
                   2311:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2312:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2313:         }
                   2314:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2315:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2316:         }
                   2317:     }
1.1219    raeburn  2318:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2319:     return %domdefaults;
                   2320: }
                   2321: 
1.344     www      2322: # --------------------------------------------------- Assign a key to a student
                   2323: 
                   2324: sub assign_access_key {
1.364     www      2325: #
                   2326: # a valid key looks like uname:udom#comments
                   2327: # comments are being appended
                   2328: #
1.498     www      2329:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2330:     $kdom=
1.620     albertel 2331:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2332:     $knum=
1.620     albertel 2333:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2334:     $cdom=
1.620     albertel 2335:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2336:     $cnum=
1.620     albertel 2337:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2338:     $udom=$env{'user.name'} unless (defined($udom));
                   2339:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2340:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2341:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2342:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2343:                                                   # assigned to this person
                   2344:                                                   # - this should not happen,
1.345     www      2345:                                                   # unless something went wrong
                   2346:                                                   # the first time around
                   2347: # ready to assign
1.364     www      2348:         $logentry=$1.'; '.$logentry;
1.496     www      2349:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2350:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2351: # key now belongs to user
1.346     www      2352: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2353:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2354:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2355:                 return 'ok';
                   2356:             } else {
                   2357:                 return 
                   2358:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2359: 	    }
                   2360:         } else {
                   2361:             return 'error: Could not assign key, try again later.';
                   2362:         }
1.364     www      2363:     } elsif (!$existing{$ckey}) {
1.345     www      2364: # the key does not exist
                   2365: 	return 'error: The key does not exist';
                   2366:     } else {
                   2367: # the key is somebody else's
                   2368: 	return 'error: The key is already in use';
                   2369:     }
1.344     www      2370: }
                   2371: 
1.364     www      2372: # ------------------------------------------ put an additional comment on a key
                   2373: 
                   2374: sub comment_access_key {
                   2375: #
                   2376: # a valid key looks like uname:udom#comments
                   2377: # comments are being appended
                   2378: #
                   2379:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2380:     $cdom=
1.620     albertel 2381:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2382:     $cnum=
1.620     albertel 2383:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2384:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2385:     if ($existing{$ckey}) {
                   2386:         $existing{$ckey}.='; '.$logentry;
                   2387: # ready to assign
1.367     www      2388:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2389:                                                  $cdom,$cnum) eq 'ok') {
                   2390: 	    return 'ok';
                   2391:         } else {
                   2392: 	    return 'error: Count not store comment.';
                   2393:         }
                   2394:     } else {
                   2395: # the key does not exist
                   2396: 	return 'error: The key does not exist';
                   2397:     }
                   2398: }
                   2399: 
1.344     www      2400: # ------------------------------------------------------ Generate a set of keys
                   2401: 
                   2402: sub generate_access_keys {
1.364     www      2403:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2404:     $cdom=
1.620     albertel 2405:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2406:     $cnum=
1.620     albertel 2407:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2408:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2409:     unless (($cdom) && ($cnum)) { return 0; }
                   2410:     if ($number>10000) { return 0; }
                   2411:     sleep(2); # make sure don't get same seed twice
                   2412:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2413:     my $total=0;
                   2414:     for (my $i=1;$i<=$number;$i++) {
                   2415:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2416:                   sprintf("%lx",int(100000*rand)).'-'.
                   2417:                   sprintf("%lx",int(100000*rand));
                   2418:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2419:        $newkey=~s/0/h/g; # and also 0 and O
                   2420:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2421:        if ($existing{$newkey}) {
                   2422:            $i--;
                   2423:        } else {
1.364     www      2424: 	  if (&put('accesskeys',
                   2425:               { $newkey => '# generated '.localtime().
1.620     albertel 2426:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2427:                            '; '.$logentry },
                   2428: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2429:               $total++;
                   2430: 	  }
                   2431:        }
                   2432:     }
1.620     albertel 2433:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2434:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2435:     return $total;
                   2436: }
                   2437: 
                   2438: # ------------------------------------------------------- Validate an accesskey
                   2439: 
                   2440: sub validate_access_key {
                   2441:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2442:     $cdom=
1.620     albertel 2443:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2444:     $cnum=
1.620     albertel 2445:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2446:     $udom=$env{'user.domain'} unless (defined($udom));
                   2447:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2448:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2449:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2450: }
                   2451: 
                   2452: # ------------------------------------- Find the section of student in a course
1.652     albertel 2453: sub devalidate_getsection_cache {
                   2454:     my ($udom,$unam,$courseid)=@_;
                   2455:     my $hashid="$udom:$unam:$courseid";
                   2456:     &devalidate_cache_new('getsection',$hashid);
                   2457: }
1.298     matthew  2458: 
1.815     albertel 2459: sub courseid_to_courseurl {
                   2460:     my ($courseid) = @_;
                   2461:     #already url style courseid
                   2462:     return $courseid if ($courseid =~ m{^/});
                   2463: 
                   2464:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2465: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2466: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2467: 	return "/$cdom/$cnum";
                   2468:     }
                   2469: 
                   2470:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2471:     if (exists($courseinfo{'num'})) {
                   2472: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2473:     }
                   2474: 
                   2475:     return undef;
                   2476: }
                   2477: 
1.298     matthew  2478: sub getsection {
                   2479:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2480:     my $cachetime=1800;
1.551     albertel 2481: 
                   2482:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2483:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2484:     if (defined($cached)) { return $result; }
                   2485: 
1.298     matthew  2486:     my %Pending; 
                   2487:     my %Expired;
                   2488:     #
                   2489:     # Each role can either have not started yet (pending), be active, 
                   2490:     #    or have expired.
                   2491:     #
                   2492:     # If there is an active role, we are done.
                   2493:     #
                   2494:     # If there is more than one role which has not started yet, 
                   2495:     #     choose the one which will start sooner
                   2496:     # If there is one role which has not started yet, return it.
                   2497:     #
                   2498:     # If there is more than one expired role, choose the one which ended last.
                   2499:     # If there is a role which has expired, return it.
                   2500:     #
1.815     albertel 2501:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2502:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2503:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2504:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2505:         my $section=$1;
                   2506:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2507:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2508:         my $now=time;
1.548     albertel 2509:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2510:             $Expired{$end}=$section;
                   2511:             next;
                   2512:         }
1.548     albertel 2513:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2514:             $Pending{$start}=$section;
                   2515:             next;
                   2516:         }
1.599     albertel 2517:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2518:     }
                   2519:     #
                   2520:     # Presumedly there will be few matching roles from the above
                   2521:     # loop and the sorting time will be negligible.
                   2522:     if (scalar(keys(%Pending))) {
                   2523:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2524:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2525:     } 
                   2526:     if (scalar(keys(%Expired))) {
                   2527:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2528:         my $time = pop(@sorted);
1.599     albertel 2529:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2530:     }
1.599     albertel 2531:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2532: }
1.70      www      2533: 
1.599     albertel 2534: sub save_cache {
                   2535:     &purge_remembered();
1.722     albertel 2536:     #&Apache::loncommon::validate_page();
1.620     albertel 2537:     undef(%env);
1.780     albertel 2538:     undef($env_loaded);
1.599     albertel 2539: }
1.452     albertel 2540: 
1.599     albertel 2541: my $to_remember=-1;
                   2542: my %remembered;
                   2543: my %accessed;
                   2544: my $kicks=0;
                   2545: my $hits=0;
1.849     albertel 2546: sub make_key {
                   2547:     my ($name,$id) = @_;
1.872     albertel 2548:     if (length($id) > 65 
                   2549: 	&& length(&escape($id)) > 200) {
                   2550: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2551:     }
1.849     albertel 2552:     return &escape($name.':'.$id);
                   2553: }
                   2554: 
1.599     albertel 2555: sub devalidate_cache_new {
                   2556:     my ($name,$id,$debug) = @_;
                   2557:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2558:     $id=&make_key($name,$id);
1.599     albertel 2559:     $memcache->delete($id);
                   2560:     delete($remembered{$id});
                   2561:     delete($accessed{$id});
                   2562: }
                   2563: 
                   2564: sub is_cached_new {
                   2565:     my ($name,$id,$debug) = @_;
1.849     albertel 2566:     $id=&make_key($name,$id);
1.599     albertel 2567:     if (exists($remembered{$id})) {
1.1133    foxr     2568: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2569: 	$accessed{$id}=[&gettimeofday()];
                   2570: 	$hits++;
                   2571: 	return ($remembered{$id},1);
                   2572:     }
                   2573:     my $value = $memcache->get($id);
                   2574:     if (!(defined($value))) {
                   2575: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2576: 	return (undef,undef);
1.416     albertel 2577:     }
1.599     albertel 2578:     if ($value eq '__undef__') {
                   2579: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2580: 	$value=undef;
                   2581:     }
                   2582:     &make_room($id,$value,$debug);
                   2583:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2584:     return ($value,1);
                   2585: }
                   2586: 
                   2587: sub do_cache_new {
                   2588:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2589:     $id=&make_key($name,$id);
1.599     albertel 2590:     my $setvalue=$value;
                   2591:     if (!defined($setvalue)) {
                   2592: 	$setvalue='__undef__';
                   2593:     }
1.623     albertel 2594:     if (!defined($time) ) {
                   2595: 	$time=600;
                   2596:     }
1.599     albertel 2597:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2598:     my $result = $memcache->set($id,$setvalue,$time);
                   2599:     if (! $result) {
1.872     albertel 2600: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2601: 	$memcache->disconnect_all();
1.872     albertel 2602:     }
1.600     albertel 2603:     # need to make a copy of $value
1.919     albertel 2604:     &make_room($id,$value,$debug);
1.599     albertel 2605:     return $value;
                   2606: }
                   2607: 
                   2608: sub make_room {
                   2609:     my ($id,$value,$debug)=@_;
1.919     albertel 2610: 
                   2611:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2612:                                     : $value;
1.599     albertel 2613:     if ($to_remember<0) { return; }
                   2614:     $accessed{$id}=[&gettimeofday()];
                   2615:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2616:     my $to_kick;
                   2617:     my $max_time=0;
                   2618:     foreach my $other (keys(%accessed)) {
                   2619: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2620: 	    $to_kick=$other;
                   2621: 	    $max_time=&tv_interval($accessed{$other});
                   2622: 	}
                   2623:     }
                   2624:     delete($remembered{$to_kick});
                   2625:     delete($accessed{$to_kick});
                   2626:     $kicks++;
                   2627:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2628:     return;
                   2629: }
                   2630: 
1.599     albertel 2631: sub purge_remembered {
1.604     albertel 2632:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2633:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2634:     undef(%remembered);
                   2635:     undef(%accessed);
1.428     albertel 2636: }
1.70      www      2637: # ------------------------------------- Read an entry from a user's environment
                   2638: 
                   2639: sub userenvironment {
                   2640:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2641:     my $items;
                   2642:     foreach my $item (@what) {
                   2643:         $items.=&escape($item).'&';
                   2644:     }
                   2645:     $items=~s/\&$//;
1.70      www      2646:     my %returnhash=();
1.1009    raeburn  2647:     my $uhome = &homeserver($unam,$udom);
                   2648:     unless ($uhome eq 'no_host') {
                   2649:         my @answer=split(/\&/, 
                   2650:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2651:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2652:             return %returnhash;
                   2653:         }
1.1009    raeburn  2654:         my $i;
                   2655:         for ($i=0;$i<=$#what;$i++) {
                   2656: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2657:         }
1.70      www      2658:     }
                   2659:     return %returnhash;
1.1       albertel 2660: }
                   2661: 
1.617     albertel 2662: # ---------------------------------------------------------- Get a studentphoto
                   2663: sub studentphoto {
                   2664:     my ($udom,$unam,$ext) = @_;
                   2665:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2666:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2667:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2668:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2669:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2670:             } else {
                   2671:                 my ($result,$perm_reqd)=
1.707     albertel 2672: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2673:                 if ($result eq 'ok') {
                   2674:                     if (!($perm_reqd eq 'yes')) {
                   2675:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2676:                     }
                   2677:                 }
                   2678:             }
                   2679:         }
                   2680:     } else {
                   2681:         my ($result,$perm_reqd) = 
1.707     albertel 2682: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2683:         if ($result eq 'ok') {
                   2684:             if (!($perm_reqd eq 'yes')) {
                   2685:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2686:             }
                   2687:         }
                   2688:     }
                   2689:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2690: }
                   2691: 
                   2692: sub retrievestudentphoto {
                   2693:     my ($udom,$unam,$ext,$type) = @_;
                   2694:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2695:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2696:     if ($ret eq 'ok') {
                   2697:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2698:         if ($type eq 'thumbnail') {
                   2699:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2700:         }
                   2701:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2702:         return $tokenurl;
                   2703:     } else {
                   2704:         if ($type eq 'thumbnail') {
                   2705:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2706:         } else { 
                   2707:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2708:         }
1.617     albertel 2709:     }
                   2710: }
                   2711: 
1.263     www      2712: # -------------------------------------------------------------------- New chat
                   2713: 
                   2714: sub chatsend {
1.724     raeburn  2715:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2716:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2717:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2718:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2719:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2720: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2721: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2722: }
                   2723: 
                   2724: # ------------------------------------------ Find current version of a resource
                   2725: 
                   2726: sub getversion {
                   2727:     my $fname=&clutter(shift);
1.1189    raeburn  2728:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2729:     return &currentversion(&filelocation('',$fname));
                   2730: }
                   2731: 
                   2732: sub currentversion {
                   2733:     my $fname=shift;
                   2734:     my $author=$fname;
                   2735:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2736:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2737:     my $home=&homeserver($uname,$udom);
1.292     www      2738:     if ($home eq 'no_host') { 
                   2739:         return -1; 
                   2740:     }
1.1112    www      2741:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2742:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2743: 	return -1;
                   2744:     }
1.1112    www      2745:     return $answer;
1.263     www      2746: }
                   2747: 
1.1111    www      2748: #
                   2749: # Return special version number of resource if set by override, empty otherwise
                   2750: #
                   2751: sub usedversion {
                   2752:     my $fname=shift;
                   2753:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2754:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2755:     if ($urlversion) { return $urlversion; }
                   2756:     return '';
                   2757: }
                   2758: 
1.1       albertel 2759: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2760: 
1.1       albertel 2761: sub subscribe {
                   2762:     my $fname=shift;
1.761     raeburn  2763:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2764:     $fname=~s/[\n\r]//g;
1.1       albertel 2765:     my $author=$fname;
                   2766:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2767:     my ($udom,$uname)=split(/\//,$author);
                   2768:     my $home=homeserver($uname,$udom);
1.335     albertel 2769:     if ($home eq 'no_host') {
                   2770:         return 'not_found';
1.1       albertel 2771:     }
                   2772:     my $answer=reply("sub:$fname",$home);
1.64      www      2773:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2774: 	$answer.=' by '.$home;
                   2775:     }
1.1       albertel 2776:     return $answer;
                   2777: }
                   2778:     
1.8       www      2779: # -------------------------------------------------------------- Replicate file
                   2780: 
                   2781: sub repcopy {
                   2782:     my $filename=shift;
1.23      www      2783:     $filename=~s/\/+/\//g;
1.1142    raeburn  2784:     my $londocroot = $perlvar{'lonDocRoot'};
                   2785:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2786:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2787:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2788: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2789: 	return &repcopy_userfile($filename);
                   2790:     }
1.532     albertel 2791:     $filename=~s/[\n\r]//g;
1.8       www      2792:     my $transname="$filename.in.transfer";
1.828     www      2793: # FIXME: this should flock
1.607     raeburn  2794:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2795:     my $remoteurl=subscribe($filename);
1.64      www      2796:     if ($remoteurl =~ /^con_lost by/) {
                   2797: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2798:            return 'unavailable';
1.8       www      2799:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2800: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2801: 	   return 'not_found';
1.64      www      2802:     } elsif ($remoteurl =~ /^rejected by/) {
                   2803: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2804:            return 'forbidden';
1.20      www      2805:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2806:            return 'ok';
1.8       www      2807:     } else {
1.290     www      2808:         my $author=$filename;
                   2809:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2810:         my ($udom,$uname)=split(/\//,$author);
                   2811:         my $home=homeserver($uname,$udom);
                   2812:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2813:            my @parts=split(/\//,$filename);
                   2814:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2815:            if ($path ne "$londocroot/res") {
1.8       www      2816:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2817: 	       return 'bad_request';
1.8       www      2818:            }
                   2819:            my $count;
                   2820:            for ($count=5;$count<$#parts;$count++) {
                   2821:                $path.="/$parts[$count]";
                   2822:                if ((-e $path)!=1) {
                   2823: 		   mkdir($path,0777);
                   2824:                }
                   2825:            }
                   2826:            my $ua=new LWP::UserAgent;
                   2827:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2828:            my $response=$ua->request($request,$transname);
                   2829:            if ($response->is_error()) {
                   2830: 	       unlink($transname);
                   2831:                my $message=$response->status_line;
1.672     albertel 2832:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2833:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2834:                return 'unavailable';
1.8       www      2835:            } else {
1.16      www      2836: 	       if ($remoteurl!~/\.meta$/) {
                   2837:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2838:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2839:                   if ($mresponse->is_error()) {
                   2840: 		      unlink($filename.'.meta');
                   2841:                       &logthis(
1.672     albertel 2842:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2843:                   }
                   2844: 	       }
1.8       www      2845:                rename($transname,$filename);
1.607     raeburn  2846:                return 'ok';
1.8       www      2847:            }
1.290     www      2848:        }
1.8       www      2849:     }
1.330     www      2850: }
                   2851: 
                   2852: # ------------------------------------------------ Get server side include body
                   2853: sub ssi_body {
1.381     albertel 2854:     my ($filelink,%form)=@_;
1.606     matthew  2855:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2856:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2857:     }
1.953     www      2858:     my $output='';
                   2859:     my $response;
1.980     raeburn  2860:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2861:        ($output,$response)=&externalssi($filelink);
1.953     www      2862:     } else {
1.1004    droeschl 2863:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2864:        $filelink .= 'inhibitmenu=yes';
1.953     www      2865:        ($output,$response)=&ssi($filelink,%form);
                   2866:     }
1.778     albertel 2867:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2868:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2869:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2870:     if (wantarray) {
                   2871:         return ($output, $response);
                   2872:     } else {
                   2873:         return $output;
                   2874:     }
1.8       www      2875: }
                   2876: 
1.15      www      2877: # --------------------------------------------------------- Server Side Include
                   2878: 
1.782     albertel 2879: sub absolute_url {
                   2880:     my ($host_name) = @_;
                   2881:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2882:     if ($host_name eq '') {
                   2883: 	$host_name = $ENV{'SERVER_NAME'};
                   2884:     }
                   2885:     return $protocol.$host_name;
                   2886: }
                   2887: 
1.942     foxr     2888: #
                   2889: #   Server side include.
                   2890: # Parameters:
                   2891: #  fn     Possibly encrypted resource name/id.
                   2892: #  form   Hash that describes how the rendering should be done
                   2893: #         and other things.
1.944     foxr     2894: # Returns:
1.950     raeburn  2895: #   Scalar context: The content of the response.
                   2896: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2897: #     
1.15      www      2898: sub ssi {
                   2899: 
1.944     foxr     2900:     my ($fn,%form)=@_;
1.15      www      2901:     my $ua=new LWP::UserAgent;
1.23      www      2902:     my $request;
1.711     albertel 2903: 
                   2904:     $form{'no_update_last_known'}=1;
1.895     albertel 2905:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2906:     if (%form) {
1.782     albertel 2907:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2908:       $request->content(join('&',map { 
                   2909:             my $name = escape($_);
                   2910:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2911:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2912:             : &escape($form{$_}) );    
                   2913:         } keys(%form)));
1.23      www      2914:     } else {
1.782     albertel 2915:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2916:     }
                   2917: 
1.15      www      2918:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2919:     my $response= $ua->request($request);
1.1182    foxr     2920:     my $content = $response->content;
                   2921: 
                   2922: 
1.944     foxr     2923:     if (wantarray) {
1.1173    foxr     2924: 	return ($content, $response);
1.944     foxr     2925:     } else {
1.1173    foxr     2926: 	return $content;
1.942     foxr     2927:     }
1.324     www      2928: }
                   2929: 
                   2930: sub externalssi {
                   2931:     my ($url)=@_;
                   2932:     my $ua=new LWP::UserAgent;
                   2933:     my $request=new HTTP::Request('GET',$url);
                   2934:     my $response=$ua->request($request);
1.954     raeburn  2935:     if (wantarray) {
                   2936:         return ($response->content, $response);
                   2937:     } else {
                   2938:         return $response->content;
                   2939:     }
1.15      www      2940: }
1.254     www      2941: 
1.492     albertel 2942: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2943: 
                   2944: sub allowuploaded {
                   2945:     my ($srcurl,$url)=@_;
                   2946:     $url=&clutter(&declutter($url));
                   2947:     my $dir=$url;
                   2948:     $dir=~s/\/[^\/]+$//;
                   2949:     my %httpref=();
                   2950:     my $httpurl=&hreflocation('',$url);
                   2951:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2952:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2953: }
1.477     raeburn  2954: 
1.1193    raeburn  2955: #
                   2956: # Determine if the current user should be able to edit a particular resource,
                   2957: # when viewing in course context.
                   2958: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2959: #     Functions.
                   2960: # (b) When displaying folder contents in course editor, used to determine if
                   2961: #     "Edit" link will be displayed alongside resource.
                   2962: #
1.1196    raeburn  2963: #  input: six args -- filename (decluttered), course number, course domain,
                   2964: #                   url, symb (if registered) and group (if this is a group
                   2965: #                   item -- e.g., bulletin board, group page etc.).
                   2966: #  output: array of five scalars -- 
1.1193    raeburn  2967: #          $cfile -- url for file editing if editable on current server
                   2968: #          $home -- homeserver of resource (i.e., for author if published,
                   2969: #                                           or course if uploaded.).
                   2970: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2971: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2972: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2973: #
                   2974: 
                   2975: sub can_edit_resource {
1.1194    raeburn  2976:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2977:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2978: #
                   2979: # For aboutme pages user can only edit his/her own.
                   2980: #
1.1199    raeburn  2981:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2982:         my ($sdom,$sname) = ($1,$2);
                   2983:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2984:             $home = $env{'user.home'};
                   2985:             $cfile = $resurl;
                   2986:             if ($env{'form.forceedit'}) {
                   2987:                 $forceview = 1;
                   2988:             } else {
                   2989:                 $forceedit = 1;
                   2990:             }
                   2991:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2992:         } else {
                   2993:             return;
                   2994:         }
                   2995:     }
                   2996: 
                   2997:     if ($env{'request.course.id'}) {
                   2998:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2999:         if ($group ne '') {
                   3000: # if this is a group homepage or group bulletin board, check group privs
                   3001:             my $allowed = 0;
1.1197    raeburn  3002:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3003:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3004:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3005:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3006:                     $allowed = 1;
                   3007:                 }
1.1197    raeburn  3008:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3009:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3010:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3011:                     $allowed = 1;
                   3012:                 }
                   3013:             }
                   3014:             if ($allowed) {
                   3015:                 $home=&homeserver($cnum,$cdom);
                   3016:                 if ($env{'form.forceedit'}) {
                   3017:                     $forceview = 1;
                   3018:                 } else {
                   3019:                     $forceedit = 1;
                   3020:                 }
                   3021:                 $cfile = $resurl;
                   3022:             } else {
                   3023:                 return;
                   3024:             }
                   3025:         } else {
1.1208    raeburn  3026:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3027:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3028:                     return;
                   3029:                 }
                   3030:             } elsif (!$crsedit) {
1.1194    raeburn  3031: #
                   3032: # No edit allowed where CC has switched to student role.
                   3033: #
                   3034:                 return;
                   3035:             }
                   3036:         }
                   3037:     }
                   3038: 
1.1193    raeburn  3039:     if ($file ne '') {
                   3040:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3041:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3042:                 $uploaded = 1;
                   3043:                 $incourse = 1;
1.1193    raeburn  3044:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3045:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3046:                     if ($env{'form.forceedit'}) {
                   3047:                         $forceview = 1;
                   3048:                     } else {
                   3049:                         $forceedit = 1;
                   3050:                     }
1.1194    raeburn  3051:                 }
                   3052:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3053:                 $incourse = 1;
                   3054:                 if ($env{'form.forceedit'}) {
                   3055:                     $forceview = 1;
                   3056:                 } else {
                   3057:                     $forceedit = 1;
                   3058:                 }
                   3059:                 $cfile = $resurl;
                   3060:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3061:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3062:                     $incourse = 1;
                   3063:                     if ($env{'form.forceedit'}) {
                   3064:                         $forceview = 1;
                   3065:                     } else {
                   3066:                         $forceedit = 1;
                   3067:                     }
                   3068:                     $cfile = $resurl;
1.1199    raeburn  3069:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3070:                     $incourse = 1;
                   3071:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3072:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3073:                     $incourse = 1;
1.1199    raeburn  3074:                     if ($env{'form.forceedit'}) {
                   3075:                         $forceview = 1;
                   3076:                     } else {
                   3077:                         $forceedit = 1;
                   3078:                     }
                   3079:                     $cfile = $resurl;
1.1298    raeburn  3080:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3081:                     $incourse = 1;
                   3082:                     if ($env{'form.forceedit'}) {
                   3083:                         $forceview = 1;
                   3084:                     } else {
                   3085:                         $forceedit = 1;
                   3086:                     }
                   3087:                     $cfile = $resurl;
1.1208    raeburn  3088:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3089:                     $incourse = 1;
                   3090:                     if ($env{'form.forceedit'}) {
                   3091:                         $forceview = 1;
                   3092:                     } else {
                   3093:                         $forceedit = 1;
                   3094:                     }
                   3095:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3096:                 }
                   3097:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3098:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3099:                 if (&is_on_map($template)) { 
                   3100:                     $incourse = 1;
                   3101:                     $forceview = 1;
                   3102:                     $cfile = $template;
1.1193    raeburn  3103:                 }
1.1199    raeburn  3104:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3105:                     $incourse = 1;
                   3106:                     if ($env{'form.forceedit'}) {
                   3107:                         $forceview = 1;
                   3108:                     } else {
                   3109:                         $forceedit = 1;
                   3110:                     }
                   3111:                     $cfile = $resurl;
1.1298    raeburn  3112:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3113:                 $incourse = 1;
                   3114:                 if ($env{'form.forceedit'}) {
                   3115:                     $forceview = 1;
                   3116:                 } else {
                   3117:                     $forceedit = 1;
                   3118:                 }
                   3119:                 $cfile = $resurl;
1.1199    raeburn  3120:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3121:                 $incourse = 1;
                   3122:                 $forceview = 1;
                   3123:                 if ($symb) {
                   3124:                     my ($map,$id,$res)=&decode_symb($symb);
                   3125:                     $env{'request.symb'} = $symb;
                   3126:                     $cfile = &clutter($res);
                   3127:                 } else {
                   3128:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3129:                     my $escfile = &unescape($cfile);
                   3130:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3131:                         $cfile = '/adm/wrapper'.$escfile;
                   3132:                     } else {
                   3133:                         $escfile =~ s{^http://}{};
                   3134:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3135:                     }
1.1199    raeburn  3136:                 }
1.1234    raeburn  3137:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3138:                 if ($env{'form.forceedit'}) {
                   3139:                     $forceview = 1;
                   3140:                 } else {
                   3141:                     $forceedit = 1;
                   3142:                 }
                   3143:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3144:             }
                   3145:         }
1.1194    raeburn  3146:         if ($uploaded || $incourse) {
                   3147:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3148:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3149:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3150:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3151:             # Check that the user has permission to edit this resource
                   3152:             my $setpriv = 1;
                   3153:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3154:             if (defined($cfudom)) {
                   3155:                 $home=&homeserver($cfuname,$cfudom);
                   3156:                 $cfile=$file;
                   3157:             }
                   3158:         }
1.1194    raeburn  3159:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3160:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3161:             my @ids=&current_machine_ids();
                   3162:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3163:                 $switchserver=1;
                   3164:             }
                   3165:         }
                   3166:     }
1.1194    raeburn  3167:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3168: }
                   3169: 
                   3170: sub is_course_upload {
                   3171:     my ($file,$cnum,$cdom) = @_;
                   3172:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3173:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3174:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3175:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3176:         return 1;
                   3177:     }
                   3178:     return;
                   3179: }
                   3180: 
1.1194    raeburn  3181: sub in_course {
1.1195    raeburn  3182:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3183:     if ($hideprivileged) {
                   3184:         my $skipuser;
1.1219    raeburn  3185:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3186:         my @possdoms = ($cdom);  
                   3187:         if ($coursehash{'checkforpriv'}) { 
                   3188:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3189:         }
                   3190:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3191:             $skipuser = 1;
                   3192:             if ($coursehash{'nothideprivileged'}) {
                   3193:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3194:                     my $user;
                   3195:                     if ($item =~ /:/) {
                   3196:                         $user = $item;
                   3197:                     } else {
                   3198:                         $user = join(':',split(/[\@]/,$item));
                   3199:                     }
                   3200:                     if ($user eq $uname.':'.$udom) {
                   3201:                         undef($skipuser);
                   3202:                         last;
                   3203:                     }
                   3204:                 }
                   3205:             }
                   3206:             if ($skipuser) {
                   3207:                 return 0;
                   3208:             }
                   3209:         }
                   3210:     }
1.1194    raeburn  3211:     $type ||= 'any';
                   3212:     if (!defined($cdom) || !defined($cnum)) {
                   3213:         my $cid  = $env{'request.course.id'};
                   3214:         $cdom = $env{'course.'.$cid.'.domain'};
                   3215:         $cnum = $env{'course.'.$cid.'.num'};
                   3216:     }
                   3217:     my $typesref;
1.1195    raeburn  3218:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3219:         $typesref = ['active','previous','future'];
                   3220:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3221:         $typesref = [$type];
                   3222:     }
                   3223:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3224:                               $typesref,undef,[$cdom]);
                   3225:     my ($tmp) = keys(%roles);
                   3226:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3227:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3228:     if (@course_roles > 0) {
                   3229:         return 1;
                   3230:     }
                   3231:     return 0;
                   3232: }
                   3233: 
1.478     albertel 3234: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3235: # input: action, courseID, current domain, intended
1.637     raeburn  3236: #        path to file, source of file, instruction to parse file for objects,
                   3237: #        ref to hash for embedded objects,
                   3238: #        ref to hash for codebase of java objects.
1.1095    raeburn  3239: #        reference to scalar to accommodate mime type determined
                   3240: #          from File::MMagic if $parser = parse.
1.637     raeburn  3241: #
1.485     raeburn  3242: # output: url to file (if action was uploaddoc), 
                   3243: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3244: #
1.478     albertel 3245: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3246: # course.
1.477     raeburn  3247: #
1.478     albertel 3248: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3249: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3250: #          course's home server.
1.477     raeburn  3251: #
1.478     albertel 3252: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3253: #          be copied from $source (current location) to 
                   3254: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3255: #         and will then be copied to
                   3256: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3257: #         course's home server.
1.485     raeburn  3258: #
1.481     raeburn  3259: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3260: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3261: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3262: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3263: #         in course's home server.
1.637     raeburn  3264: #
1.477     raeburn  3265: 
                   3266: sub process_coursefile {
1.1095    raeburn  3267:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3268:         $mimetype)=@_;
1.477     raeburn  3269:     my $fetchresult;
1.638     albertel 3270:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3271:     if ($action eq 'propagate') {
1.638     albertel 3272:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3273: 			     $home);
1.481     raeburn  3274:     } else {
1.477     raeburn  3275:         my $fpath = '';
                   3276:         my $fname = $file;
1.478     albertel 3277:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3278:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3279:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3280:         if ($action eq 'copy') {
                   3281:             if ($source eq '') {
                   3282:                 $fetchresult = 'no source file';
                   3283:                 return $fetchresult;
                   3284:             } else {
                   3285:                 my $destination = $filepath.'/'.$fname;
                   3286:                 rename($source,$destination);
                   3287:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3288:                                  $home);
1.481     raeburn  3289:             }
                   3290:         } elsif ($action eq 'uploaddoc') {
                   3291:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3292:             print $fh $env{'form.'.$source};
1.481     raeburn  3293:             close($fh);
1.637     raeburn  3294:             if ($parser eq 'parse') {
1.1024    raeburn  3295:                 my $mm = new File::MMagic;
1.1095    raeburn  3296:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3297:                 if ($type eq 'text/html') {
1.1024    raeburn  3298:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3299:                     unless ($parse_result eq 'ok') {
                   3300:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3301:                     }
1.637     raeburn  3302:                 }
1.1095    raeburn  3303:                 if (ref($mimetype)) {
                   3304:                     $$mimetype = $type;
                   3305:                 } 
1.637     raeburn  3306:             }
1.477     raeburn  3307:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3308:                                  $home);
1.481     raeburn  3309:             if ($fetchresult eq 'ok') {
                   3310:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3311:             } else {
                   3312:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3313:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3314:                 return '/adm/notfound.html';
                   3315:             }
1.477     raeburn  3316:         }
                   3317:     }
1.485     raeburn  3318:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3319:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3320:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3321:     }
                   3322:     return $fetchresult;
                   3323: }
                   3324: 
1.637     raeburn  3325: sub build_filepath {
                   3326:     my ($fpath) = @_;
                   3327:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3328:     unless ($fpath eq '') {
                   3329:         my @parts=split('/',$fpath);
                   3330:         foreach my $part (@parts) {
                   3331:             $filepath.= '/'.$part;
                   3332:             if ((-e $filepath)!=1) {
                   3333:                 mkdir($filepath,0777);
                   3334:             }
                   3335:         }
                   3336:     }
                   3337:     return $filepath;
                   3338: }
                   3339: 
                   3340: sub store_edited_file {
1.638     albertel 3341:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3342:     my $file = $primary_url;
                   3343:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3344:     my $fpath = '';
                   3345:     my $fname = $file;
                   3346:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3347:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3348:     my $filepath = &build_filepath($fpath);
                   3349:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3350:     print $fh $content;
                   3351:     close($fh);
1.638     albertel 3352:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3353:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3354: 			  $home);
1.637     raeburn  3355:     if ($$fetchresult eq 'ok') {
                   3356:         return '/uploaded/'.$fpath.'/'.$fname;
                   3357:     } else {
1.638     albertel 3358:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3359: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3360:         return '/adm/notfound.html';
                   3361:     }
                   3362: }
                   3363: 
1.531     albertel 3364: sub clean_filename {
1.831     albertel 3365:     my ($fname,$args)=@_;
1.315     www      3366: # Replace Windows backslashes by forward slashes
1.257     www      3367:     $fname=~s/\\/\//g;
1.831     albertel 3368:     if (!$args->{'keep_path'}) {
                   3369:         # Get rid of everything but the actual filename
                   3370: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3371:     }
1.315     www      3372: # Replace spaces by underscores
                   3373:     $fname=~s/\s+/\_/g;
                   3374: # Replace all other weird characters by nothing
1.831     albertel 3375:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3376: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3377: # numbers
                   3378:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3379:     return $fname;
                   3380: }
1.1051    raeburn  3381: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3382: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3383: # image with the same aspect ratio as the original, but with dimensions which do 
                   3384: # not exceed $resizewidth and $resizeheight.
                   3385:  
1.984     neumanie 3386: sub resizeImage {
1.1051    raeburn  3387:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3388:     my $ima = Image::Magick->new;
                   3389:     my $resized;
                   3390:     if (-e $img_path) {
                   3391:         $ima->Read($img_path);
                   3392:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3393:             my $width = $ima->Get('width');
                   3394:             my $height = $ima->Get('height');
                   3395:             if ($width > $resizewidth) {
                   3396: 	        my $factor = $width/$resizewidth;
                   3397:                 my $newheight = $height/$factor;
                   3398:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3399:                 $resized = 1;
                   3400:             }
                   3401:         }
                   3402:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3403:             my $width = $ima->Get('width');
                   3404:             my $height = $ima->Get('height');
                   3405:             if ($height > $resizeheight) {
                   3406:                 my $factor = $height/$resizeheight;
                   3407:                 my $newwidth = $width/$factor;
                   3408:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3409:                 $resized = 1;
                   3410:             }
                   3411:         }
                   3412:         if ($resized) {
                   3413:             $ima->Write($img_path);
                   3414:         }
                   3415:     }
                   3416:     return;
1.977     amueller 3417: }
                   3418: 
1.608     albertel 3419: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3420: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3421: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3422: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3423: #                                    canceloverwrite, or ''. 
                   3424: #                   if 'coursedoc': upload to the current course
                   3425: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3426: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3427: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3428: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3429: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3430: #        $allfiles - reference to hash for embedded objects
                   3431: #        $codebase - reference to hash for codebase of java objects
                   3432: #        $desuname - username for permanent storage of uploaded file
                   3433: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3434: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3435: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3436: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3437: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3438: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3439: #                    from File::MMagic.
1.858     raeburn  3440: # 
1.686     albertel 3441: # output: url of file in userspace, or error: <message> 
                   3442: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3443: 
1.531     albertel 3444: sub userfileupload {
1.1090    raeburn  3445:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3446:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3447:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3448:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3449:     $fname=&clean_filename($fname);
1.1090    raeburn  3450:     # See if there is anything left
1.257     www      3451:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3452:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3453:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3454:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3455:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3456:         my $now = time;
1.1090    raeburn  3457:         my $filepath;
1.1095    raeburn  3458:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3459:              $filepath = 'tmp/helprequests/'.$now;
                   3460:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3461:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3462:                          '_'.$env{'user.domain'}.'/pending';
                   3463:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3464:             my ($docuname,$docudom);
                   3465:             if ($destudom) {
                   3466:                 $docudom = $destudom;
                   3467:             } else {
                   3468:                 $docudom = $env{'user.domain'};
                   3469:             }
                   3470:             if ($destuname) {
                   3471:                 $docuname = $destuname;
                   3472:             } else {
                   3473:                 $docuname = $env{'user.name'};
                   3474:             }
                   3475:             if (exists($env{'form.group'})) {
                   3476:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3477:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3478:             }
                   3479:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3480:             if ($context eq 'canceloverwrite') {
                   3481:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3482:                 if (-e  $tempfile) {
                   3483:                     my @info = stat($tempfile);
                   3484:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3485:                         unlink($tempfile);
                   3486:                     }
                   3487:                 }
                   3488:                 return;
1.523     raeburn  3489:             }
                   3490:         }
1.1090    raeburn  3491:         # Create the directory if not present
1.741     raeburn  3492:         my @parts=split(/\//,$filepath);
                   3493:         my $fullpath = $perlvar{'lonDaemons'};
                   3494:         for (my $i=0;$i<@parts;$i++) {
                   3495:             $fullpath .= '/'.$parts[$i];
                   3496:             if ((-e $fullpath)!=1) {
                   3497:                 mkdir($fullpath,0777);
                   3498:             }
                   3499:         }
                   3500:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3501:         print $fh $env{'form.'.$formname};
                   3502:         close($fh);
1.1090    raeburn  3503:         if ($context eq 'existingfile') {
                   3504:             my @info = stat($fullpath.'/'.$fname);
                   3505:             return ($fullpath.'/'.$fname,$info[9]);
                   3506:         } else {
                   3507:             return $fullpath.'/'.$fname;
                   3508:         }
1.523     raeburn  3509:     }
1.995     raeburn  3510:     if ($subdir eq 'scantron') {
                   3511:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3512:     } else {
1.995     raeburn  3513:         $fname="$subdir/$fname";
                   3514:     }
1.1090    raeburn  3515:     if ($context eq 'coursedoc') {
1.638     albertel 3516: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3517: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3518:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3519:             return &finishuserfileupload($docuname,$docudom,
                   3520: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3521: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3522:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3523:         } else {
1.1218    raeburn  3524:             if ($env{'form.folder'}) {
                   3525:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3526:             }
1.638     albertel 3527:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3528: 				       $fname,$formname,$parser,
1.1095    raeburn  3529: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3530:         }
1.719     banghart 3531:     } elsif (defined($destuname)) {
                   3532:         my $docuname=$destuname;
                   3533:         my $docudom=$destudom;
1.860     raeburn  3534: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3535: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3536:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3537:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3538:     } else {
1.638     albertel 3539:         my $docuname=$env{'user.name'};
                   3540:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3541:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3542:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3543:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3544:         }
1.860     raeburn  3545: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3546: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3547:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3548:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3549:     }
1.271     www      3550: }
                   3551: 
                   3552: sub finishuserfileupload {
1.860     raeburn  3553:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3554:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3555:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3556:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3557:   
1.860     raeburn  3558:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3559:     $file=$fname;
                   3560:     if ($fname=~m|/|) {
                   3561:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3562: 	$path.=$fnamepath.'/';
                   3563:     }
1.259     www      3564:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3565:     my $count;
                   3566:     for ($count=4;$count<=$#parts;$count++) {
                   3567:         $filepath.="/$parts[$count]";
                   3568:         if ((-e $filepath)!=1) {
                   3569: 	    mkdir($filepath,0777);
                   3570:         }
                   3571:     }
1.984     neumanie 3572: 
1.258     www      3573: # Save the file
                   3574:     {
1.701     albertel 3575: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3576: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3577: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3578: 	    return '/adm/notfound.html';
                   3579: 	}
1.1090    raeburn  3580:         if ($context eq 'overwrite') {
1.1117    foxr     3581:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3582:             my $target = $filepath.'/'.$file;
                   3583:             if (-e $source) {
                   3584:                 my @info = stat($source);
                   3585:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3586:                     unless (&File::Copy::move($source,$target)) {
                   3587:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3588:                         return "Moving from $source failed";
                   3589:                     }
                   3590:                 } else {
                   3591:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3592:                 }
                   3593:             } else {
                   3594:                 return "Temporary file: $source missing";
                   3595:             }
                   3596:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3597: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3598: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3599: 	    return '/adm/notfound.html';
                   3600: 	}
1.570     albertel 3601: 	close(FH);
1.1051    raeburn  3602:         if ($resizewidth && $resizeheight) {
                   3603:             my $mm = new File::MMagic;
                   3604:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3605:             if ($mime_type =~ m{^image/}) {
                   3606: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3607:             }  
1.977     amueller 3608: 	}
1.258     www      3609:     }
1.1152    raeburn  3610:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3611:         if (ref($mimetype)) {
                   3612:             if ($$mimetype eq '') {
                   3613:                 my $mm = new File::MMagic;
                   3614:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3615:                 $$mimetype = $type;
                   3616:             }
                   3617:         }
                   3618:     }
1.637     raeburn  3619:     if ($parser eq 'parse') {
1.1152    raeburn  3620:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3621:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3622:                                                        $allfiles,$codebase);
                   3623:             unless ($parse_result eq 'ok') {
                   3624:                 &logthis('Failed to parse '.$filepath.$file.
                   3625: 	   	         ' for embedded media: '.$parse_result); 
                   3626:             }
1.637     raeburn  3627:         }
                   3628:     }
1.860     raeburn  3629:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3630:         my $input = $filepath.'/'.$file;
                   3631:         my $output = $filepath.'/'.'tn-'.$file;
                   3632:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3633:         system("convert -sample $thumbsize $input $output");
                   3634:         if (-e $filepath.'/'.'tn-'.$file) {
                   3635:             $fetchthumb  = 1; 
                   3636:         }
                   3637:     }
1.858     raeburn  3638:  
1.259     www      3639: # Notify homeserver to grep it
                   3640: #
1.984     neumanie 3641:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3642:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3643:     if ($fetchresult eq 'ok') {
1.860     raeburn  3644:         if ($fetchthumb) {
                   3645:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3646:             if ($thumbresult ne 'ok') {
                   3647:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3648:                          $docuhome.': '.$thumbresult);
                   3649:             }
                   3650:         }
1.259     www      3651: #
1.258     www      3652: # Return the URL to it
1.494     albertel 3653:         return '/uploaded/'.$path.$file;
1.263     www      3654:     } else {
1.494     albertel 3655:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3656: 		 ': '.$fetchresult);
1.263     www      3657:         return '/adm/notfound.html';
1.858     raeburn  3658:     }
1.493     albertel 3659: }
                   3660: 
1.637     raeburn  3661: sub extract_embedded_items {
1.961     raeburn  3662:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3663:     my @state = ();
1.1164    raeburn  3664:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3665:     my %javafiles = (
                   3666:                       codebase => '',
                   3667:                       code => '',
                   3668:                       archive => ''
                   3669:                     );
                   3670:     my %mediafiles = (
                   3671:                       src => '',
                   3672:                       movie => '',
                   3673:                      );
1.648     raeburn  3674:     my $p;
                   3675:     if ($content) {
                   3676:         $p = HTML::LCParser->new($content);
                   3677:     } else {
1.961     raeburn  3678:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3679:     }
1.641     albertel 3680:     while (my $t=$p->get_token()) {
1.640     albertel 3681: 	if ($t->[0] eq 'S') {
                   3682: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3683: 	    push(@state, $tagname);
1.648     raeburn  3684:             if (lc($tagname) eq 'allow') {
                   3685:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3686:             }
1.640     albertel 3687: 	    if (lc($tagname) eq 'img') {
                   3688: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3689: 	    }
1.886     albertel 3690: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3691:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3692:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3693:                 }
1.886     albertel 3694: 	    }
1.645     raeburn  3695:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3696:                 my $src;
1.645     raeburn  3697:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3698:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3699:                 } else {
1.1164    raeburn  3700:                     if ($attr->{'src'} ne '') {
                   3701:                         $src = $attr->{'src'};
                   3702:                         &add_filetype($allfiles,$src,'src');
                   3703:                     }
                   3704:                 }
                   3705:                 my $text = $p->get_trimmed_text();
                   3706:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3707:                     my @swfargs = split(/,/,$1);
                   3708:                     foreach my $item (@swfargs) {
                   3709:                         $item =~ s/["']//g;
                   3710:                         $item =~ s/^\s+//;
                   3711:                         $item =~ s/\s+$//;
                   3712:                     }
                   3713:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3714:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3715:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3716:                         } else {
                   3717:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3718:                         }
                   3719:                     }
1.645     raeburn  3720:                 }
                   3721:             }
                   3722:             if (lc($tagname) eq 'link') {
                   3723:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3724:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3725:                 }
                   3726:             }
1.640     albertel 3727: 	    if (lc($tagname) eq 'object' ||
                   3728: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3729: 		foreach my $item (keys(%javafiles)) {
                   3730: 		    $javafiles{$item} = '';
                   3731: 		}
1.1164    raeburn  3732:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3733:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3734:                 }
1.640     albertel 3735: 	    }
                   3736: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3737: 		my $name = lc($attr->{'name'});
                   3738: 		foreach my $item (keys(%javafiles)) {
                   3739: 		    if ($name eq $item) {
                   3740: 			$javafiles{$item} = $attr->{'value'};
                   3741: 			last;
                   3742: 		    }
                   3743: 		}
1.1164    raeburn  3744:                 my $pathfrom;
1.640     albertel 3745: 		foreach my $item (keys(%mediafiles)) {
                   3746: 		    if ($name eq $item) {
1.1164    raeburn  3747:                         $pathfrom = $attr->{'value'};
                   3748:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3749: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3750: 			last;
                   3751: 		    }
                   3752: 		}
1.1164    raeburn  3753:                 if ($name eq 'flashvars') {
                   3754:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3755:                 }
                   3756:                 if ($pathfrom ne '') {
                   3757:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3758:                                          $pathfrom);
                   3759:                 }
1.640     albertel 3760: 	    }
                   3761: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3762: 		foreach my $item (keys(%javafiles)) {
                   3763: 		    if ($attr->{$item}) {
                   3764: 			$javafiles{$item} = $attr->{$item};
                   3765: 			last;
                   3766: 		    }
                   3767: 		}
                   3768: 		foreach my $item (keys(%mediafiles)) {
                   3769: 		    if ($attr->{$item}) {
                   3770: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3771: 			last;
                   3772: 		    }
                   3773: 		}
1.1164    raeburn  3774:                 if (lc($tagname) eq 'embed') {
                   3775:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3776:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3777:                                              $attr->{'src'});
                   3778:                     }
                   3779:                 }
1.640     albertel 3780: 	    }
1.1243    raeburn  3781:             if (lc($tagname) eq 'iframe') {
                   3782:                 my $src = $attr->{'src'} ;
                   3783:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3784:                     &add_filetype($allfiles,$src,'src');
                   3785:                 } elsif ($src =~ m{^/}) {
                   3786:                     if ($env{'request.course.id'}) {
                   3787:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3788:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3789:                         my $url = &hreflocation('',$fullpath);
                   3790:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3791:                             my $relpath = $1;
                   3792:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3793:                                 &add_filetype($allfiles,$1,'src');
                   3794:                             }
                   3795:                         }
                   3796:                     }
                   3797:                 }
                   3798:             }
1.1164    raeburn  3799:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3800:                 pop(@state);
1.1164    raeburn  3801:             }
1.640     albertel 3802: 	} elsif ($t->[0] eq 'E') {
                   3803: 	    my ($tagname) = ($t->[1]);
                   3804: 	    if ($javafiles{'codebase'} ne '') {
                   3805: 		$javafiles{'codebase'} .= '/';
                   3806: 	    }  
                   3807: 	    if (lc($tagname) eq 'applet' ||
                   3808: 		lc($tagname) eq 'object' ||
                   3809: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3810: 		) {
                   3811: 		foreach my $item (keys(%javafiles)) {
                   3812: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3813: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3814: 			&add_filetype($allfiles,$file,$item);
                   3815: 		    }
                   3816: 		}
                   3817: 	    } 
                   3818: 	    pop @state;
                   3819: 	}
                   3820:     }
1.1164    raeburn  3821:     foreach my $id (sort(keys(%flashvars))) {
                   3822:         if ($shockwave{$id} ne '') {
                   3823:             my @pairs = split(/\&/,$flashvars{$id});
                   3824:             foreach my $pair (@pairs) {
                   3825:                 my ($key,$value) = split(/\=/,$pair);
                   3826:                 if ($key eq 'thumb') {
                   3827:                     &add_filetype($allfiles,$value,$key);
                   3828:                 } elsif ($key eq 'content') {
                   3829:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3830:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3831:                     if ($ext ne '') {
                   3832:                         &add_filetype($allfiles,$path.$value,$ext);
                   3833:                     }
                   3834:                 }
                   3835:             }
                   3836:         }
                   3837:     }
1.637     raeburn  3838:     return 'ok';
                   3839: }
                   3840: 
1.639     albertel 3841: sub add_filetype {
                   3842:     my ($allfiles,$file,$type)=@_;
                   3843:     if (exists($allfiles->{$file})) {
                   3844: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3845: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3846: 	}
                   3847:     } else {
                   3848: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3849:     }
                   3850: }
                   3851: 
1.1164    raeburn  3852: sub embedded_dependency {
                   3853:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3854:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3855:         if (($identifier ne '') &&
                   3856:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3857:             ($pathfrom ne '')) {
                   3858:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3859:             foreach my $dep (@{$related->{$identifier}}) {
                   3860:                 &add_filetype($allfiles,$path.$dep,'object');
                   3861:             }
                   3862:         }
                   3863:     }
                   3864:     return;
                   3865: }
                   3866: 
1.493     albertel 3867: sub removeuploadedurl {
1.984     neumanie 3868:     my ($url)=@_;	
                   3869:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3870:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3871: }
                   3872: 
                   3873: sub removeuserfile {
                   3874:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3875:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3876:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3877:     if ($result eq 'ok') {	
1.798     raeburn  3878:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3879:             my $metafile = $fname.'.meta';
                   3880:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3881: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3882:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3883:             my $sqlresult = 
1.823     albertel 3884:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3885:                                         'portfolio_metadata',$group,
                   3886:                                         'delete');
1.798     raeburn  3887:         }
                   3888:     }
                   3889:     return $result;
1.257     www      3890: }
1.15      www      3891: 
1.530     albertel 3892: sub mkdiruserfile {
                   3893:     my ($docuname,$docudom,$dir)=@_;
                   3894:     my $home=&homeserver($docuname,$docudom);
                   3895:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3896: }
                   3897: 
1.531     albertel 3898: sub renameuserfile {
                   3899:     my ($docuname,$docudom,$old,$new)=@_;
                   3900:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3901:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3902:                         &escape("$old").':'.&escape("$new"),$home);
                   3903:     if ($result eq 'ok') {
                   3904:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3905:             my $oldmeta = $old.'.meta';
                   3906:             my $newmeta = $new.'.meta';
                   3907:             my $metaresult = 
                   3908:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3909: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3910:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3911:             my $sqlresult = 
1.823     albertel 3912:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3913:                                         'portfolio_metadata',$group,
                   3914:                                         'delete');
1.798     raeburn  3915:         }
                   3916:     }
                   3917:     return $result;
1.531     albertel 3918: }
                   3919: 
1.14      www      3920: # ------------------------------------------------------------------------- Log
                   3921: 
                   3922: sub log {
                   3923:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3924:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3925: }
                   3926: 
                   3927: # ------------------------------------------------------------------ Course Log
1.352     www      3928: #
                   3929: # This routine flushes several buffers of non-mission-critical nature
                   3930: #
1.157     www      3931: 
                   3932: sub flushcourselogs {
1.352     www      3933:     &logthis('Flushing log buffers');
                   3934: #
                   3935: # course logs
                   3936: # This is a log of all transactions in a course, which can be used
                   3937: # for data mining purposes
                   3938: #
                   3939: # It also collects the courseid database, which lists last transaction
                   3940: # times and course titles for all courseids
                   3941: #
                   3942:     my %courseidbuffer=();
1.921     raeburn  3943:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3944:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3945: 		          &escape($courselogs{$crsid}),
                   3946: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3947: 	    delete $courselogs{$crsid};
                   3948:         } else {
                   3949:             &logthis('Failed to flush log buffer for '.$crsid);
                   3950:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3951:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3952:                         " exceeded maximum size, deleting.</font>");
                   3953:                delete $courselogs{$crsid};
                   3954:             }
1.352     www      3955:         }
1.920     raeburn  3956:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3957:             'description' => $coursedescrbuf{$crsid},
                   3958:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3959:             'type'        => $coursetypebuf{$crsid},
                   3960:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3961:         };
1.191     harris41 3962:     }
1.352     www      3963: #
                   3964: # Write course id database (reverse lookup) to homeserver of courses 
                   3965: # Is used in pickcourse
                   3966: #
1.840     albertel 3967:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3968:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3969:                                     $courseidbuffer{$crs_home},
                   3970:                                     $crs_home,'timeonly');
1.352     www      3971:     }
                   3972: #
                   3973: # File accesses
                   3974: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3975: #
1.449     matthew  3976:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3977:         if ($entry =~ /___count$/) {
                   3978:             my ($dom,$name);
1.807     albertel 3979:             ($dom,$name,undef)=
1.811     albertel 3980: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3981:             if (! defined($dom) || $dom eq '' || 
                   3982:                 ! defined($name) || $name eq '') {
1.620     albertel 3983:                 my $cid = $env{'request.course.id'};
                   3984:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3985:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3986:             }
1.450     matthew  3987:             my $value = $accesshash{$entry};
                   3988:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3989:             my %temphash=($url => $value);
1.449     matthew  3990:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3991:             if ($result eq 'ok') {
                   3992:                 delete $accesshash{$entry};
                   3993:             }
                   3994:         } else {
1.811     albertel 3995:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3996:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3997:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3998:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3999:                 delete $accesshash{$entry};
                   4000:             }
1.185     www      4001:         }
1.191     harris41 4002:     }
1.352     www      4003: #
                   4004: # Roles
                   4005: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4006: #
1.800     albertel 4007:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4008:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4009: 	    split(/\:/,$entry);
                   4010:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4011:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4012:                 $rudom,$runame) eq 'ok') {
                   4013: 	    delete $userrolehash{$entry};
                   4014:         }
                   4015:     }
1.662     raeburn  4016: #
                   4017: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   4018: #
                   4019:     my %domrolebuffer = ();
1.1000    raeburn  4020:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4021:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4022:         if ($domrolebuffer{$rudom}) {
                   4023:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4024:                       '='.&escape($domainrolehash{$entry});
                   4025:         } else {
                   4026:             $domrolebuffer{$rudom}.=&escape($entry).
                   4027:                       '='.&escape($domainrolehash{$entry});
                   4028:         }
                   4029:         delete $domainrolehash{$entry};
                   4030:     }
                   4031:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 4032: 	my %servers = &get_servers($dom,'library');
                   4033: 	foreach my $tryserver (keys(%servers)) {
                   4034: 	    unless (&reply('domroleput:'.$dom.':'.
                   4035: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4036: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4037: 	    }
1.662     raeburn  4038:         }
                   4039:     }
1.186     www      4040:     $dumpcount++;
1.157     www      4041: }
                   4042: 
                   4043: sub courselog {
                   4044:     my $what=shift;
1.158     www      4045:     $what=time.':'.$what;
1.620     albertel 4046:     unless ($env{'request.course.id'}) { return ''; }
                   4047:     $coursedombuf{$env{'request.course.id'}}=
                   4048:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4049:     $coursenumbuf{$env{'request.course.id'}}=
                   4050:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4051:     $coursehombuf{$env{'request.course.id'}}=
                   4052:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4053:     $coursedescrbuf{$env{'request.course.id'}}=
                   4054:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4055:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4056:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4057:     $courseownerbuf{$env{'request.course.id'}}=
                   4058:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4059:     $coursetypebuf{$env{'request.course.id'}}=
                   4060:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4061:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4062: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4063:     } else {
1.620     albertel 4064: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4065:     }
1.620     albertel 4066:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4067: 	&flushcourselogs();
                   4068:     }
1.158     www      4069: }
                   4070: 
                   4071: sub courseacclog {
                   4072:     my $fnsymb=shift;
1.620     albertel 4073:     unless ($env{'request.course.id'}) { return ''; }
                   4074:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4075:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4076:         $what.=':POST';
1.583     matthew  4077:         # FIXME: Probably ought to escape things....
1.800     albertel 4078: 	foreach my $key (keys(%env)) {
                   4079:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4080:                 my $formitem = $1;
                   4081:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4082:                     $what.=':'.$formitem.'='.$env{$key};
                   4083:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4084:                     $what.=':'.$formitem.'='.$env{$key};
                   4085:                 }
1.158     www      4086:             }
1.191     harris41 4087:         }
1.583     matthew  4088:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4089:         # FIXME: We should not be depending on a form parameter that someone
                   4090:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4091:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4092:             $what.= ':POST';
                   4093:             # FIXME: Probably ought to escape things....
                   4094:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4095:                                  'crsdiscuss') {
1.620     albertel 4096:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4097:             }
                   4098:         }
1.158     www      4099:     }
                   4100:     &courselog($what);
1.149     www      4101: }
                   4102: 
1.185     www      4103: sub countacc {
                   4104:     my $url=&declutter(shift);
1.458     matthew  4105:     return if (! defined($url) || $url eq '');
1.620     albertel 4106:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4107: #
                   4108: # Mark that this url was used in this course
                   4109: #
1.620     albertel 4110:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4111: #
                   4112: # Increase the access count for this resource in this child process
                   4113: #
1.281     www      4114:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4115:     $accesshash{$key}++;
1.185     www      4116: }
1.349     www      4117: 
1.361     www      4118: sub linklog {
                   4119:     my ($from,$to)=@_;
                   4120:     $from=&declutter($from);
                   4121:     $to=&declutter($to);
                   4122:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4123:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4124: }
1.1160    www      4125: 
                   4126: sub statslog {
                   4127:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4128:     if ($users<2) { return; }
                   4129:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4130:             'course'       => $env{'request.course.id'},
                   4131:             'sections'     => '"all"',
                   4132:             'num_students' => $users,
                   4133:             'part'         => $part,
                   4134:             'symb'         => $symb,
                   4135:             'mean_tries'   => $av_attempts,
                   4136:             'deg_of_diff'  => $degdiff});
                   4137:     foreach my $key (keys(%dynstore)) {
                   4138:         $accesshash{$key}=$dynstore{$key};
                   4139:     }
                   4140: }
1.361     www      4141:   
1.349     www      4142: sub userrolelog {
                   4143:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4144:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4145:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4146:        $userrolehash
                   4147:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4148:                     =$tend.':'.$tstart;
1.662     raeburn  4149:     }
1.1169    droeschl 4150:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4151:        $userrolehash
                   4152:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4153:                     =$tend.':'.$tstart;
                   4154:     }
1.1169    droeschl 4155:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4156:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4157:        $domainrolehash
                   4158:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4159:                     = $tend.':'.$tstart;
                   4160:     }
1.351     www      4161: }
                   4162: 
1.957     raeburn  4163: sub courserolelog {
                   4164:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4165:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4166:         my $cdom = $1;
                   4167:         my $cnum = $2;
                   4168:         my $sec = $3;
                   4169:         my $namespace = 'rolelog';
                   4170:         my %storehash = (
                   4171:                            role    => $trole,
                   4172:                            start   => $tstart,
                   4173:                            end     => $tend,
                   4174:                            selfenroll => $selfenroll,
                   4175:                            context    => $context,
                   4176:                         );
                   4177:         if ($trole eq 'gr') {
                   4178:             $namespace = 'groupslog';
                   4179:             $storehash{'group'} = $sec;
                   4180:         } else {
                   4181:             $storehash{'section'} = $sec;
                   4182:         }
1.1188    raeburn  4183:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4184:                    $domain,$cnum,$cdom);
1.1184    raeburn  4185:         if (($trole ne 'st') || ($sec ne '')) {
                   4186:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4187:         }
                   4188:     }
                   4189:     return;
                   4190: }
                   4191: 
1.1184    raeburn  4192: sub domainrolelog {
                   4193:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4194:     if ($area =~ m{^/($match_domain)/$}) {
                   4195:         my $cdom = $1;
                   4196:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4197:         my $namespace = 'rolelog';
                   4198:         my %storehash = (
                   4199:                            role    => $trole,
                   4200:                            start   => $tstart,
                   4201:                            end     => $tend,
                   4202:                            context => $context,
                   4203:                         );
1.1188    raeburn  4204:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4205:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4206:     }
                   4207:     return;
                   4208: 
                   4209: }
                   4210: 
                   4211: sub coauthorrolelog {
                   4212:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4213:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4214:         my $audom = $1;
                   4215:         my $auname = $2;
                   4216:         my $namespace = 'rolelog';
                   4217:         my %storehash = (
                   4218:                            role    => $trole,
                   4219:                            start   => $tstart,
                   4220:                            end     => $tend,
                   4221:                            context => $context,
                   4222:                         );
1.1188    raeburn  4223:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4224:                    $domain,$auname,$audom);
1.1184    raeburn  4225:     }
                   4226:     return;
                   4227: }
                   4228: 
1.351     www      4229: sub get_course_adv_roles {
1.948     raeburn  4230:     my ($cid,$codes) = @_;
1.620     albertel 4231:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4232:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4233:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4234:     my %nothide=();
1.800     albertel 4235:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4236:         if ($user !~ /:/) {
                   4237: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4238:         } else {
                   4239:             $nothide{$user}=1;
                   4240:         }
1.470     www      4241:     }
1.1219    raeburn  4242:     my @possdoms = ($coursehash{'domain'});
                   4243:     if ($coursehash{'checkforpriv'}) {
                   4244:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4245:     }
1.351     www      4246:     my %returnhash=();
                   4247:     my %dumphash=
                   4248:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4249:     my $now=time;
1.997     raeburn  4250:     my %privileged;
1.1000    raeburn  4251:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4252: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4253:         if (($tstart) && ($tstart<0)) { next; }
                   4254:         if (($tend) && ($tend<$now)) { next; }
                   4255:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4256:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4257: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4258:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4259:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4260: 	if ($role eq 'cr') { next; }
1.948     raeburn  4261:         if ($codes) {
                   4262:             if ($section) { $role .= ':'.$section; }
                   4263:             if ($returnhash{$role}) {
                   4264:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4265:             } else {
                   4266:                 $returnhash{$role}=$username.':'.$domain;
                   4267:             }
1.351     www      4268:         } else {
1.988     raeburn  4269:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4270:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4271:             if ($returnhash{$key}) {
                   4272: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4273:             } else {
                   4274:                 $returnhash{$key}=$username.':'.$domain;
                   4275:             }
1.351     www      4276:         }
1.948     raeburn  4277:     }
1.400     www      4278:     return %returnhash;
                   4279: }
                   4280: 
                   4281: sub get_my_roles {
1.937     raeburn  4282:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4283:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4284:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4285:     my (%dumphash,%nothide);
1.1086    raeburn  4286:     if ($context eq 'userroles') {
1.1166    raeburn  4287:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4288:     } else {
1.1219    raeburn  4289:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4290:         if ($hidepriv) {
                   4291:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4292:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4293:                 if ($user !~ /:/) {
                   4294:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4295:                 } else {
                   4296:                     $nothide{$user} = 1;
                   4297:                 }
                   4298:             }
                   4299:         }
1.858     raeburn  4300:     }
1.400     www      4301:     my %returnhash=();
                   4302:     my $now=time;
1.999     raeburn  4303:     my %privileged;
1.800     albertel 4304:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4305:         my ($role,$tend,$tstart);
                   4306:         if ($context eq 'userroles') {
1.1149    raeburn  4307:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4308: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4309:         } else {
                   4310:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4311:         }
1.400     www      4312:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4313:         my $status = 'active';
1.939     raeburn  4314:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4315:             $status = 'previous';
                   4316:         } 
                   4317:         if (($tstart) && ($now<$tstart)) {
                   4318:             $status = 'future';
                   4319:         }
                   4320:         if (ref($types) eq 'ARRAY') {
                   4321:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4322:                 next;
                   4323:             } 
                   4324:         } else {
                   4325:             if ($status ne 'active') {
                   4326:                 next;
                   4327:             }
                   4328:         }
1.867     raeburn  4329:         my ($rolecode,$username,$domain,$section,$area);
                   4330:         if ($context eq 'userroles') {
1.1186    raeburn  4331:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4332:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4333:         } else {
                   4334:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4335:         }
1.832     raeburn  4336:         if (ref($roledoms) eq 'ARRAY') {
                   4337:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4338:                 next;
                   4339:             }
                   4340:         }
                   4341:         if (ref($roles) eq 'ARRAY') {
                   4342:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4343:                 if ($role =~ /^cr\//) {
                   4344:                     if (!grep(/^cr$/,@{$roles})) {
                   4345:                         next;
                   4346:                     }
1.1104    raeburn  4347:                 } elsif ($role =~ /^gr\//) {
                   4348:                     if (!grep(/^gr$/,@{$roles})) {
                   4349:                         next;
                   4350:                     }
1.922     raeburn  4351:                 } else {
                   4352:                     next;
                   4353:                 }
1.832     raeburn  4354:             }
1.867     raeburn  4355:         }
1.937     raeburn  4356:         if ($hidepriv) {
1.1219    raeburn  4357:             my @privroles = ('dc','su');
1.999     raeburn  4358:             if ($context eq 'userroles') {
1.1219    raeburn  4359:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4360:             } else {
1.1219    raeburn  4361:                 my $possdoms = [$domain];
                   4362:                 if (ref($roledoms) eq 'ARRAY') {
                   4363:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4364:                 }
1.1219    raeburn  4365:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4366:                     if (!$nothide{$username.':'.$domain}) {
                   4367:                         next;
                   4368:                     }
                   4369:                 }
1.937     raeburn  4370:             }
                   4371:         }
1.933     raeburn  4372:         if ($withsec) {
                   4373:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4374:                 $tstart.':'.$tend;
                   4375:         } else {
                   4376:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4377:         }
1.832     raeburn  4378:     }
1.373     www      4379:     return %returnhash;
1.399     www      4380: }
                   4381: 
                   4382: # ----------------------------------------------------- Frontpage Announcements
                   4383: #
                   4384: #
                   4385: 
                   4386: sub postannounce {
                   4387:     my ($server,$text)=@_;
1.844     albertel 4388:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4389:     unless ($text=~/\w/) { $text=''; }
                   4390:     return &reply('setannounce:'.&escape($text),$server);
                   4391: }
                   4392: 
                   4393: sub getannounce {
1.448     albertel 4394: 
                   4395:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4396: 	my $announcement='';
1.800     albertel 4397: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4398: 	close($fh);
1.399     www      4399: 	if ($announcement=~/\w/) { 
                   4400: 	    return 
                   4401:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4402:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4403: 	} else {
                   4404: 	    return '';
                   4405: 	}
                   4406:     } else {
                   4407: 	return '';
                   4408:     }
1.351     www      4409: }
1.353     www      4410: 
                   4411: # ---------------------------------------------------------- Course ID routines
                   4412: # Deal with domain's nohist_courseid.db files
                   4413: #
                   4414: 
                   4415: sub courseidput {
1.921     raeburn  4416:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4417:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4418:     my $outcome;
                   4419:     if ($caller eq 'timeonly') {
                   4420:         my $cids = '';
                   4421:         foreach my $item (keys(%$storehash)) {
                   4422:             $cids.=&escape($item).'&';
                   4423:         }
                   4424:         $cids=~s/\&$//;
                   4425:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4426:                           $coursehome);       
                   4427:     } else {
                   4428:         my $items = '';
                   4429:         foreach my $item (keys(%$storehash)) {
                   4430:             $items.= &escape($item).'='.
                   4431:                      &freeze_escape($$storehash{$item}).'&';
                   4432:         }
                   4433:         $items=~s/\&$//;
                   4434:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4435:                           $coursehome);
1.918     raeburn  4436:     }
                   4437:     if ($outcome eq 'unknown_cmd') {
                   4438:         my $what;
                   4439:         foreach my $cid (keys(%$storehash)) {
                   4440:             $what .= &escape($cid).'=';
1.921     raeburn  4441:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4442:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4443:             }
                   4444:             $what =~ s/\:$/&/;
                   4445:         }
                   4446:         $what =~ s/\&$//;  
                   4447:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4448:     } else {
                   4449:         return $outcome;
                   4450:     }
1.353     www      4451: }
                   4452: 
                   4453: sub courseiddump {
1.921     raeburn  4454:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4455:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4456:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4457:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4458:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4459:     my $as_hash = 1;
                   4460:     my %returnhash;
                   4461:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4462:     my %libserv = &all_library();
                   4463:     foreach my $tryserver (keys(%libserv)) {
                   4464:         if ( (  $hostidflag == 1 
                   4465: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4466: 	     || (!defined($hostidflag)) ) {
                   4467: 
1.918     raeburn  4468: 	    if (($domfilter eq '') ||
                   4469: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4470:                 my $rep;
                   4471:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4472:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4473:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4474:                                 &escape($descfilter), &escape($instcodefilter), 
                   4475:                                 &escape($ownerfilter), &escape($coursefilter),
                   4476:                                 &escape($typefilter), &escape($regexp_ok), 
                   4477:                                 $as_hash, &escape($selfenrollonly), 
                   4478:                                 &escape($catfilter), $showhidden, $caller, 
                   4479:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4480:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4481:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4482:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4483:                 } else {
                   4484:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4485:                              $sincefilter.':'.&escape($descfilter).':'.
                   4486:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4487:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4488:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4489:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4490:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4491:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4492:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4493:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4494:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4495:                 }
                   4496:                      
1.918     raeburn  4497:                 my @pairs=split(/\&/,$rep);
                   4498:                 foreach my $item (@pairs) {
                   4499:                     my ($key,$value)=split(/\=/,$item,2);
                   4500:                     $key = &unescape($key);
                   4501:                     next if ($key =~ /^error: 2 /);
                   4502:                     my $result = &thaw_unescape($value);
                   4503:                     if (ref($result) eq 'HASH') {
                   4504:                         $returnhash{$key}=$result;
                   4505:                     } else {
1.921     raeburn  4506:                         my @responses = split(/:/,$value);
                   4507:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4508:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4509:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4510:                         }
1.1008    raeburn  4511:                     }
1.353     www      4512:                 }
                   4513:             }
                   4514:         }
                   4515:     }
                   4516:     return %returnhash;
                   4517: }
                   4518: 
1.1055    raeburn  4519: sub courselastaccess {
                   4520:     my ($cdom,$cnum,$hostidref) = @_;
                   4521:     my %returnhash;
                   4522:     if ($cdom && $cnum) {
                   4523:         my $chome = &homeserver($cnum,$cdom);
                   4524:         if ($chome ne 'no_host') {
                   4525:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4526:             &extract_lastaccess(\%returnhash,$rep);
                   4527:         }
                   4528:     } else {
                   4529:         if (!$cdom) { $cdom=''; }
                   4530:         my %libserv = &all_library();
                   4531:         foreach my $tryserver (keys(%libserv)) {
                   4532:             if (ref($hostidref) eq 'ARRAY') {
                   4533:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4534:             } 
                   4535:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4536:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4537:                 &extract_lastaccess(\%returnhash,$rep);
                   4538:             }
                   4539:         }
                   4540:     }
                   4541:     return %returnhash;
                   4542: }
                   4543: 
                   4544: sub extract_lastaccess {
                   4545:     my ($returnhash,$rep) = @_;
                   4546:     if (ref($returnhash) eq 'HASH') {
                   4547:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4548:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4549:                  $rep eq '') {
                   4550:             my @pairs=split(/\&/,$rep);
                   4551:             foreach my $item (@pairs) {
                   4552:                 my ($key,$value)=split(/\=/,$item,2);
                   4553:                 $key = &unescape($key);
                   4554:                 next if ($key =~ /^error: 2 /);
                   4555:                 $returnhash->{$key} = &thaw_unescape($value);
                   4556:             }
                   4557:         }
                   4558:     }
                   4559:     return;
                   4560: }
                   4561: 
1.658     raeburn  4562: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4563: 
                   4564: sub dcmailput {
1.685     raeburn  4565:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4566:     my $status = &Apache::lonnet::critical(
1.740     www      4567:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4568:        &escape($message),$server);
1.662     raeburn  4569:     return $status;
                   4570: }
                   4571: 
1.658     raeburn  4572: sub dcmaildump {
                   4573:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4574:     my %returnhash=();
1.846     albertel 4575: 
                   4576:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4577:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4578:                                                          &escape($enddate).':';
                   4579: 	my @esc_senders=map { &escape($_)} @$senders;
                   4580: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4581: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4582:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4583:             if (($key) && ($value)) {
                   4584:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4585:             }
                   4586:         }
                   4587:     }
                   4588:     return %returnhash;
                   4589: }
1.662     raeburn  4590: # ---------------------------------------------------------- Domain roles
                   4591: 
                   4592: sub get_domain_roles {
                   4593:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4594:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4595:         $startdate = '.';
                   4596:     }
1.1018    raeburn  4597:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4598:         $enddate = '.';
                   4599:     }
1.922     raeburn  4600:     my $rolelist;
                   4601:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4602:         $rolelist = join('&',@{$roles});
1.922     raeburn  4603:     }
1.662     raeburn  4604:     my %personnel = ();
1.841     albertel 4605: 
                   4606:     my %servers = &get_servers($dom,'library');
                   4607:     foreach my $tryserver (keys(%servers)) {
                   4608: 	%{$personnel{$tryserver}}=();
                   4609: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4610: 					    &escape($startdate).':'.
                   4611: 					    &escape($enddate).':'.
                   4612: 					    &escape($rolelist), $tryserver))) {
                   4613: 	    my ($key,$value) = split(/\=/,$line,2);
                   4614: 	    if (($key) && ($value)) {
                   4615: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4616: 	    }
                   4617: 	}
1.662     raeburn  4618:     }
                   4619:     return %personnel;
                   4620: }
1.658     raeburn  4621: 
1.1057    www      4622: # ----------------------------------------------------------- Interval timing 
1.149     www      4623: 
1.1153    www      4624: {
                   4625: # Caches needed for speedup of navmaps
                   4626: # We don't want to cache this for very long at all (5 seconds at most)
                   4627: # 
                   4628: # The user for whom we cache
                   4629: my $cachedkey='';
                   4630: # The cached times for this user
                   4631: my %cachedtimes=();
                   4632: # When this was last done
1.1282    raeburn  4633: my $cachedtime='';
1.1153    www      4634: 
                   4635: sub load_all_first_access {
1.1154    raeburn  4636:     my ($uname,$udom)=@_;
1.1156    www      4637:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4638:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4639:         return;
                   4640:     }
                   4641:     $cachedtime=time;
                   4642:     $cachedkey=$uname.':'.$udom;
                   4643:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4644: }
                   4645: 
1.504     albertel 4646: sub get_first_access {
1.1162    raeburn  4647:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4648:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4649:     if ($argsymb) { $symb=$argsymb; }
                   4650:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4651:     if ($argmap) { $map = $argmap; }
1.926     albertel 4652:     if ($type eq 'course') {
                   4653: 	$res='course';
                   4654:     } elsif ($type eq 'map') {
1.588     albertel 4655: 	$res=&symbread($map);
                   4656:     } else {
                   4657: 	$res=$symb;
                   4658:     }
1.1153    www      4659:     &load_all_first_access($uname,$udom);
                   4660:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4661: }
                   4662: 
                   4663: sub set_first_access {
1.1162    raeburn  4664:     my ($type,$interval)=@_;
1.790     albertel 4665:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4666:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4667:     if ($type eq 'course') {
                   4668: 	$res='course';
                   4669:     } elsif ($type eq 'map') {
1.588     albertel 4670: 	$res=&symbread($map);
                   4671:     } else {
                   4672: 	$res=$symb;
                   4673:     }
1.1153    www      4674:     $cachedkey='';
1.1162    raeburn  4675:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4676:     if (!$firstaccess) {
1.1162    raeburn  4677:         my $start = time;
                   4678: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4679:                           $udom,$uname);
                   4680:         if ($putres eq 'ok') {
                   4681:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4682:                  $udom,$uname); 
                   4683:             &appenv(
                   4684:                      {
                   4685:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4686:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4687:                      }
                   4688:                   );
                   4689:         }
                   4690:         return $putres;
1.505     albertel 4691:     }
                   4692:     return 'already_set';
1.504     albertel 4693: }
1.1153    www      4694: }
1.1282    raeburn  4695: 
1.110     www      4696: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4697: 
                   4698: sub expirespread {
                   4699:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4700:     my $cid=$env{'request.course.id'}; 
1.110     www      4701:     if ($cid) {
                   4702:        my $now=time;
                   4703:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4704:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4705:                             $env{'course.'.$cid.'.num'}.
1.110     www      4706: 	        	    ':nohist_expirationdates:'.
                   4707:                             &escape($key).'='.$now,
1.620     albertel 4708:                             $env{'course.'.$cid.'.home'})
1.110     www      4709:     }
                   4710:     return 'ok';
1.14      www      4711: }
                   4712: 
1.109     www      4713: # ----------------------------------------------------- Devalidate Spreadsheets
                   4714: 
                   4715: sub devalidate {
1.325     www      4716:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4717:     my $cid=$env{'request.course.id'}; 
1.109     www      4718:     if ($cid) {
1.391     matthew  4719:         # delete the stored spreadsheets for
                   4720:         # - the student level sheet of this user in course's homespace
                   4721:         # - the assessment level sheet for this resource 
                   4722:         #   for this user in user's homespace
1.553     albertel 4723: 	# - current conditional state info
1.325     www      4724: 	my $key=$uname.':'.$udom.':';
1.109     www      4725:         my $status=
1.299     matthew  4726: 	    &del('nohist_calculatedsheets',
1.391     matthew  4727: 		 [$key.'studentcalc:'],
1.620     albertel 4728: 		 $env{'course.'.$cid.'.domain'},
                   4729: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4730: 		.' '.
                   4731: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4732: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4733:         unless ($status eq 'ok ok') {
                   4734:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4735:                     $uname.' at '.$udom.' for '.
1.109     www      4736: 		    $symb.': '.$status);
1.133     albertel 4737:         }
1.553     albertel 4738: 	&delenv('user.state.'.$cid);
1.109     www      4739:     }
                   4740: }
                   4741: 
1.265     albertel 4742: sub get_scalar {
                   4743:     my ($string,$end) = @_;
                   4744:     my $value;
                   4745:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4746: 	$value = $1;
                   4747:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4748: 	$value = $1;
                   4749:     }
                   4750:     return &unescape($value);
                   4751: }
                   4752: 
                   4753: sub array2str {
                   4754:   my (@array) = @_;
                   4755:   my $result=&arrayref2str(\@array);
                   4756:   $result=~s/^__ARRAY_REF__//;
                   4757:   $result=~s/__END_ARRAY_REF__$//;
                   4758:   return $result;
                   4759: }
                   4760: 
1.204     albertel 4761: sub arrayref2str {
                   4762:   my ($arrayref) = @_;
1.265     albertel 4763:   my $result='__ARRAY_REF__';
1.204     albertel 4764:   foreach my $elem (@$arrayref) {
1.265     albertel 4765:     if(ref($elem) eq 'ARRAY') {
                   4766:       $result.=&arrayref2str($elem).'&';
                   4767:     } elsif(ref($elem) eq 'HASH') {
                   4768:       $result.=&hashref2str($elem).'&';
                   4769:     } elsif(ref($elem)) {
                   4770:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4771:     } else {
                   4772:       $result.=&escape($elem).'&';
                   4773:     }
                   4774:   }
                   4775:   $result=~s/\&$//;
1.265     albertel 4776:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4777:   return $result;
                   4778: }
                   4779: 
1.168     albertel 4780: sub hash2str {
1.204     albertel 4781:   my (%hash) = @_;
                   4782:   my $result=&hashref2str(\%hash);
1.265     albertel 4783:   $result=~s/^__HASH_REF__//;
                   4784:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4785:   return $result;
                   4786: }
                   4787: 
                   4788: sub hashref2str {
                   4789:   my ($hashref)=@_;
1.265     albertel 4790:   my $result='__HASH_REF__';
1.800     albertel 4791:   foreach my $key (sort(keys(%$hashref))) {
                   4792:     if (ref($key) eq 'ARRAY') {
                   4793:       $result.=&arrayref2str($key).'=';
                   4794:     } elsif (ref($key) eq 'HASH') {
                   4795:       $result.=&hashref2str($key).'=';
                   4796:     } elsif (ref($key)) {
1.265     albertel 4797:       $result.='=';
1.800     albertel 4798:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4799:     } else {
1.1132    raeburn  4800: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4801:     }
                   4802: 
1.800     albertel 4803:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4804:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4805:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4806:       $result.=&hashref2str($hashref->{$key}).'&';
                   4807:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4808:        $result.='&';
1.800     albertel 4809:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4810:     } else {
1.800     albertel 4811:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4812:     }
                   4813:   }
1.168     albertel 4814:   $result=~s/\&$//;
1.265     albertel 4815:   $result .= '__END_HASH_REF__';
1.168     albertel 4816:   return $result;
                   4817: }
                   4818: 
                   4819: sub str2hash {
1.265     albertel 4820:     my ($string)=@_;
                   4821:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4822:     return %$hash;
                   4823: }
                   4824: 
                   4825: sub str2hashref {
1.168     albertel 4826:   my ($string) = @_;
1.265     albertel 4827: 
                   4828:   my %hash;
                   4829: 
                   4830:   if($string !~ /^__HASH_REF__/) {
                   4831:       if (! ($string eq '' || !defined($string))) {
                   4832: 	  $hash{'error'}='Not hash reference';
                   4833:       }
                   4834:       return (\%hash, $string);
                   4835:   }
                   4836: 
                   4837:   $string =~ s/^__HASH_REF__//;
                   4838: 
                   4839:   while($string !~ /^__END_HASH_REF__/) {
                   4840:       #key
                   4841:       my $key='';
                   4842:       if($string =~ /^__HASH_REF__/) {
                   4843:           ($key, $string)=&str2hashref($string);
                   4844:           if(defined($key->{'error'})) {
                   4845:               $hash{'error'}='Bad data';
                   4846:               return (\%hash, $string);
                   4847:           }
                   4848:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4849:           ($key, $string)=&str2arrayref($string);
                   4850:           if($key->[0] eq 'Array reference error') {
                   4851:               $hash{'error'}='Bad data';
                   4852:               return (\%hash, $string);
                   4853:           }
                   4854:       } else {
                   4855:           $string =~ s/^(.*?)=//;
1.267     albertel 4856: 	  $key=&unescape($1);
1.265     albertel 4857:       }
                   4858:       $string =~ s/^=//;
                   4859: 
                   4860:       #value
                   4861:       my $value='';
                   4862:       if($string =~ /^__HASH_REF__/) {
                   4863:           ($value, $string)=&str2hashref($string);
                   4864:           if(defined($value->{'error'})) {
                   4865:               $hash{'error'}='Bad data';
                   4866:               return (\%hash, $string);
                   4867:           }
                   4868:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4869:           ($value, $string)=&str2arrayref($string);
                   4870:           if($value->[0] eq 'Array reference error') {
                   4871:               $hash{'error'}='Bad data';
                   4872:               return (\%hash, $string);
                   4873:           }
                   4874:       } else {
                   4875: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4876:       }
                   4877:       $string =~ s/^&//;
                   4878: 
                   4879:       $hash{$key}=$value;
1.204     albertel 4880:   }
1.265     albertel 4881: 
                   4882:   $string =~ s/^__END_HASH_REF__//;
                   4883: 
                   4884:   return (\%hash, $string);
1.204     albertel 4885: }
                   4886: 
                   4887: sub str2array {
1.265     albertel 4888:     my ($string)=@_;
                   4889:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4890:     return @$array;
                   4891: }
                   4892: 
                   4893: sub str2arrayref {
1.204     albertel 4894:   my ($string) = @_;
1.265     albertel 4895:   my @array;
                   4896: 
                   4897:   if($string !~ /^__ARRAY_REF__/) {
                   4898:       if (! ($string eq '' || !defined($string))) {
                   4899: 	  $array[0]='Array reference error';
                   4900:       }
                   4901:       return (\@array, $string);
                   4902:   }
                   4903: 
                   4904:   $string =~ s/^__ARRAY_REF__//;
                   4905: 
                   4906:   while($string !~ /^__END_ARRAY_REF__/) {
                   4907:       my $value='';
                   4908:       if($string =~ /^__HASH_REF__/) {
                   4909:           ($value, $string)=&str2hashref($string);
                   4910:           if(defined($value->{'error'})) {
                   4911:               $array[0] ='Array reference error';
                   4912:               return (\@array, $string);
                   4913:           }
                   4914:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4915:           ($value, $string)=&str2arrayref($string);
                   4916:           if($value->[0] eq 'Array reference error') {
                   4917:               $array[0] ='Array reference error';
                   4918:               return (\@array, $string);
                   4919:           }
                   4920:       } else {
                   4921: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4922:       }
                   4923:       $string =~ s/^&//;
                   4924: 
                   4925:       push(@array, $value);
1.191     harris41 4926:   }
1.265     albertel 4927: 
                   4928:   $string =~ s/^__END_ARRAY_REF__//;
                   4929: 
                   4930:   return (\@array, $string);
1.168     albertel 4931: }
                   4932: 
1.167     albertel 4933: # -------------------------------------------------------------------Temp Store
                   4934: 
1.168     albertel 4935: sub tmpreset {
                   4936:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4937:   if (!$symb) {
                   4938:     $symb=&symbread();
1.620     albertel 4939:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4940:   }
                   4941:   $symb=escape($symb);
                   4942: 
1.620     albertel 4943:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4944:   $namespace=~s/\//\_/g;
                   4945:   $namespace=~s/\W//g;
                   4946: 
1.620     albertel 4947:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4948:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4949:   if ($domain eq 'public' && $stuname eq 'public') {
                   4950:       $stuname=$ENV{'REMOTE_ADDR'};
                   4951:   }
1.1117    foxr     4952:   my $path=LONCAPA::tempdir();
1.168     albertel 4953:   my %hash;
                   4954:   if (tie(%hash,'GDBM_File',
                   4955: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4956: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4957:     foreach my $key (keys(%hash)) {
1.180     albertel 4958:       if ($key=~ /:$symb/) {
1.168     albertel 4959: 	delete($hash{$key});
                   4960:       }
                   4961:     }
                   4962:   }
                   4963: }
                   4964: 
1.167     albertel 4965: sub tmpstore {
1.168     albertel 4966:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4967: 
                   4968:   if (!$symb) {
                   4969:     $symb=&symbread();
1.620     albertel 4970:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4971:   }
                   4972:   $symb=escape($symb);
                   4973: 
                   4974:   if (!$namespace) {
                   4975:     # I don't think we would ever want to store this for a course.
                   4976:     # it seems this will only be used if we don't have a course.
1.620     albertel 4977:     #$namespace=$env{'request.course.id'};
1.168     albertel 4978:     #if (!$namespace) {
1.620     albertel 4979:       $namespace=$env{'request.state'};
1.168     albertel 4980:     #}
                   4981:   }
                   4982:   $namespace=~s/\//\_/g;
                   4983:   $namespace=~s/\W//g;
1.620     albertel 4984:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4985:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4986:   if ($domain eq 'public' && $stuname eq 'public') {
                   4987:       $stuname=$ENV{'REMOTE_ADDR'};
                   4988:   }
1.168     albertel 4989:   my $now=time;
                   4990:   my %hash;
1.1117    foxr     4991:   my $path=LONCAPA::tempdir();
1.168     albertel 4992:   if (tie(%hash,'GDBM_File',
                   4993: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4994: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4995:     $hash{"version:$symb"}++;
                   4996:     my $version=$hash{"version:$symb"};
                   4997:     my $allkeys=''; 
                   4998:     foreach my $key (keys(%$storehash)) {
                   4999:       $allkeys.=$key.':';
1.591     albertel 5000:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5001:     }
                   5002:     $hash{"$version:$symb:timestamp"}=$now;
                   5003:     $allkeys.='timestamp';
                   5004:     $hash{"$version:keys:$symb"}=$allkeys;
                   5005:     if (untie(%hash)) {
                   5006:       return 'ok';
                   5007:     } else {
                   5008:       return "error:$!";
                   5009:     }
                   5010:   } else {
                   5011:     return "error:$!";
                   5012:   }
                   5013: }
1.167     albertel 5014: 
1.168     albertel 5015: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5016: 
1.168     albertel 5017: sub tmprestore {
                   5018:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5019: 
1.168     albertel 5020:   if (!$symb) {
                   5021:     $symb=&symbread();
1.620     albertel 5022:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5023:   }
                   5024:   $symb=escape($symb);
                   5025: 
1.620     albertel 5026:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5027: 
1.620     albertel 5028:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5029:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5030:   if ($domain eq 'public' && $stuname eq 'public') {
                   5031:       $stuname=$ENV{'REMOTE_ADDR'};
                   5032:   }
1.168     albertel 5033:   my %returnhash;
                   5034:   $namespace=~s/\//\_/g;
                   5035:   $namespace=~s/\W//g;
                   5036:   my %hash;
1.1117    foxr     5037:   my $path=LONCAPA::tempdir();
1.168     albertel 5038:   if (tie(%hash,'GDBM_File',
                   5039: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5040: 	  &GDBM_READER(),0640)) {
1.168     albertel 5041:     my $version=$hash{"version:$symb"};
                   5042:     $returnhash{'version'}=$version;
                   5043:     my $scope;
                   5044:     for ($scope=1;$scope<=$version;$scope++) {
                   5045:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5046:       my @keys=split(/:/,$vkeys);
                   5047:       my $key;
                   5048:       $returnhash{"$scope:keys"}=$vkeys;
                   5049:       foreach $key (@keys) {
1.591     albertel 5050: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5051: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5052:       }
                   5053:     }
1.168     albertel 5054:     if (!(untie(%hash))) {
                   5055:       return "error:$!";
                   5056:     }
                   5057:   } else {
                   5058:     return "error:$!";
                   5059:   }
                   5060:   return %returnhash;
1.167     albertel 5061: }
                   5062: 
1.9       www      5063: # ----------------------------------------------------------------------- Store
                   5064: 
                   5065: sub store {
1.1269    raeburn  5066:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5067:     my $home='';
                   5068: 
1.168     albertel 5069:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5070: 
1.213     www      5071:     $symb=&symbclean($symb);
1.122     albertel 5072:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5073: 
1.620     albertel 5074:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5075:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5076: 
                   5077:     &devalidate($symb,$stuname,$domain);
1.109     www      5078: 
                   5079:     $symb=escape($symb);
1.187     www      5080:     if (!$namespace) { 
1.620     albertel 5081:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5082:           return ''; 
                   5083:        } 
                   5084:     }
1.620     albertel 5085:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5086: 
                   5087:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5088:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5089: 
1.12      www      5090:     my $namevalue='';
1.800     albertel 5091:     foreach my $key (keys(%$storehash)) {
                   5092:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5093:     }
1.12      www      5094:     $namevalue=~s/\&$//;
1.187     www      5095:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5096:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5097: }
                   5098: 
1.47      www      5099: # -------------------------------------------------------------- Critical Store
                   5100: 
                   5101: sub cstore {
1.1269    raeburn  5102:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5103:     my $home='';
                   5104: 
1.168     albertel 5105:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5106: 
1.213     www      5107:     $symb=&symbclean($symb);
1.122     albertel 5108:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5109: 
1.620     albertel 5110:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5111:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5112: 
                   5113:     &devalidate($symb,$stuname,$domain);
1.109     www      5114: 
                   5115:     $symb=escape($symb);
1.187     www      5116:     if (!$namespace) { 
1.620     albertel 5117:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5118:           return ''; 
                   5119:        } 
                   5120:     }
1.620     albertel 5121:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5122: 
                   5123:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5124:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5125: 
1.47      www      5126:     my $namevalue='';
1.800     albertel 5127:     foreach my $key (keys(%$storehash)) {
                   5128:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5129:     }
1.47      www      5130:     $namevalue=~s/\&$//;
1.187     www      5131:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5132:     return critical
1.1269    raeburn  5133:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5134: }
                   5135: 
1.9       www      5136: # --------------------------------------------------------------------- Restore
                   5137: 
                   5138: sub restore {
1.124     www      5139:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5140:     my $home='';
                   5141: 
1.168     albertel 5142:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5143: 
1.122     albertel 5144:     if (!$symb) {
1.1224    raeburn  5145:         return if ($namespace eq 'courserequests');
                   5146:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5147:     } else {
1.1224    raeburn  5148:         unless ($namespace eq 'courserequests') {
                   5149:             $symb=&escape(&symbclean($symb));
                   5150:         }
1.122     albertel 5151:     }
1.188     www      5152:     if (!$namespace) { 
1.620     albertel 5153:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5154:           return ''; 
                   5155:        } 
                   5156:     }
1.620     albertel 5157:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5158:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5159:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5160:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5161: 
1.12      www      5162:     my %returnhash=();
1.800     albertel 5163:     foreach my $line (split(/\&/,$answer)) {
                   5164: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5165:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5166:     }
1.75      www      5167:     my $version;
                   5168:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5169:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5170:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5171:        }
1.75      www      5172:     }
1.13      www      5173:     return %returnhash;
1.34      www      5174: }
                   5175: 
                   5176: # ---------------------------------------------------------- Course Description
1.1118    foxr     5177: #
                   5178: #  
1.34      www      5179: 
                   5180: sub coursedescription {
1.731     albertel 5181:     my ($courseid,$args)=@_;
1.34      www      5182:     $courseid=~s/^\///;
1.49      www      5183:     $courseid=~s/\_/\//g;
1.34      www      5184:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5185:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5186:     my $normalid=$cdomain.'_'.$cnum;
                   5187:     # need to always cache even if we get errors otherwise we keep 
                   5188:     # trying and trying and trying to get the course description.
                   5189:     my %envhash=();
                   5190:     my %returnhash=();
1.731     albertel 5191:     
                   5192:     my $expiretime=600;
                   5193:     if ($env{'request.course.id'} eq $normalid) {
                   5194: 	$expiretime=120;
                   5195:     }
                   5196: 
                   5197:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5198:     if (!$args->{'freshen_cache'}
                   5199: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5200: 	foreach my $key (keys(%env)) {
                   5201: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5202: 	    my ($setting) = $1;
                   5203: 	    $returnhash{$setting} = $env{$key};
                   5204: 	}
                   5205: 	return %returnhash;
                   5206:     }
                   5207: 
1.1118    foxr     5208:     # get the data again
                   5209: 
1.731     albertel 5210:     if (!$args->{'one_time'}) {
                   5211: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5212:     }
1.811     albertel 5213: 
1.34      www      5214:     if ($chome ne 'no_host') {
1.302     albertel 5215:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5216:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5217: 	   my $username = $env{'user.name'}; # Defult username
                   5218: 	   if(defined $args->{'user'}) {
                   5219: 	       $username = $args->{'user'};
                   5220: 	   }
1.129     albertel 5221:            $returnhash{'home'}= $chome;
                   5222: 	   $returnhash{'domain'} = $cdomain;
                   5223: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5224:            if (!defined($returnhash{'type'})) {
                   5225:                $returnhash{'type'} = 'Course';
                   5226:            }
1.130     albertel 5227:            while (my ($name,$value) = each %returnhash) {
1.53      www      5228:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5229:            }
1.270     www      5230:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5231:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5232: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5233:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5234:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5235:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5236:        }
                   5237:     }
1.731     albertel 5238:     if (!$args->{'one_time'}) {
1.949     raeburn  5239: 	&appenv(\%envhash);
1.731     albertel 5240:     }
1.302     albertel 5241:     return %returnhash;
1.461     www      5242: }
                   5243: 
1.1080    raeburn  5244: sub update_released_required {
                   5245:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5246:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5247:         $cid = $env{'request.course.id'};
                   5248:         $cdom = $env{'course.'.$cid.'.domain'};
                   5249:         $cnum = $env{'course.'.$cid.'.num'};
                   5250:         $chome = $env{'course.'.$cid.'.home'};
                   5251:     }
                   5252:     if ($needsrelease) {
                   5253:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5254:         my $needsupdate;
                   5255:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5256:             $needsupdate = 1;
                   5257:         } else {
                   5258:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5259:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5260:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5261:                 $needsupdate = 1;
                   5262:             }
                   5263:         }
                   5264:         if ($needsupdate) {
                   5265:             my %needshash = (
                   5266:                              'internal.releaserequired' => $needsrelease,
                   5267:                             );
                   5268:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5269:             if ($putresult eq 'ok') {
                   5270:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5271:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5272:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5273:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5274:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5275:                 }
                   5276:             }
                   5277:         }
                   5278:     }
                   5279:     return;
                   5280: }
                   5281: 
1.461     www      5282: # -------------------------------------------------See if a user is privileged
                   5283: 
                   5284: sub privileged {
1.1219    raeburn  5285:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5286:     my $now = time;
1.1219    raeburn  5287:     my $roles;
                   5288:     if (ref($possroles) eq 'ARRAY') {
                   5289:         $roles = $possroles; 
                   5290:     } else {
                   5291:         $roles = ['dc','su'];
                   5292:     }
                   5293:     if (ref($possdomains) eq 'ARRAY') {
                   5294:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5295:         foreach my $dom (@{$possdomains}) {
                   5296:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5297:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5298:                 foreach my $role (@{$roles}) {
                   5299:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5300:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5301:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5302:                             return 1 unless (($end && $end < $now) ||
                   5303:                                              ($start && $start > $now));
                   5304:                         }
                   5305:                     }
                   5306:                 }
                   5307:             }
                   5308:         }
                   5309:     } else {
                   5310:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5311:         my $now = time;
1.1170    droeschl 5312: 
1.1275    musolffc 5313:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5314:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5315:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5316:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5317:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5318:             }
1.1219    raeburn  5319:         }
                   5320:     }
                   5321:     return 0;
                   5322: }
1.1170    droeschl 5323: 
1.1219    raeburn  5324: sub privileged_by_domain {
                   5325:     my ($domains,$roles) = @_;
                   5326:     my %privileged = ();
                   5327:     my $cachetime = 60*60*24;
                   5328:     my $now = time;
                   5329:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5330:         return %privileged;
                   5331:     }
                   5332:     foreach my $dom (@{$domains}) {
                   5333:         next if (ref($privileged{$dom}) eq 'HASH');
                   5334:         my $needroles;
                   5335:         foreach my $role (@{$roles}) {
                   5336:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5337:             if (defined($cached)) {
                   5338:                 if (ref($result) eq 'HASH') {
                   5339:                     $privileged{$dom}{$role} = $result;
                   5340:                 }
                   5341:             } else {
                   5342:                 $needroles = 1;
                   5343:             }
                   5344:         }
                   5345:         if ($needroles) {
                   5346:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5347:             $privileged{$dom} = {};
                   5348:             foreach my $server (keys(%dompersonnel)) {
                   5349:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5350:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5351:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5352:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5353:                         next if ($end && $end < $now);
                   5354:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5355:                             $dompersonnel{$server}{$item};
                   5356:                     }
                   5357:                 }
                   5358:             }
                   5359:             if (ref($privileged{$dom}) eq 'HASH') {
                   5360:                 foreach my $role (@{$roles}) {
                   5361:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5362:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5363:                     } else {
                   5364:                         my %hash = ();
                   5365:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5366:                     }
                   5367:                 }
                   5368:             }
                   5369:         }
                   5370:     }
                   5371:     return %privileged;
1.9       www      5372: }
1.1       albertel 5373: 
1.103     harris41 5374: # -------------------------------------------------------- Get user privileges
1.11      www      5375: 
                   5376: sub rolesinit {
1.1169    droeschl 5377:     my ($domain, $username) = @_;
                   5378:     my %userroles = ('user.login.time' => time);
                   5379:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5380: 
                   5381:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5382:     # also, blocking can be triggered by an activating timer
                   5383:     # it's saved in the user's %env.
                   5384:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5385:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5386:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5387:         %timerintchk, %timerintenv);
                   5388: 
1.1162    raeburn  5389:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5390:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5391:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5392:     }
1.1169    droeschl 5393: 
1.1162    raeburn  5394:     foreach my $key (keys(%timerinterval)) {
                   5395:         my ($cid,$rest) = split(/\0/,$key);
                   5396:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5397:     }
1.1169    droeschl 5398: 
1.11      www      5399:     my %allroles=();
1.1162    raeburn  5400:     my %allgroups=();
1.11      www      5401: 
1.1274    raeburn  5402:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5403:         my $role = $rolesdump{$area};
                   5404:         $area =~ s/\_\w\w$//;
                   5405: 
                   5406:         my ($trole, $tend, $tstart, $group_privs);
                   5407: 
                   5408:         if ($role =~ /^cr/) {
                   5409:         # Custom role, defined by a user 
                   5410:         # e.g., user.role.cr/msu/smith/mynewrole
                   5411:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5412:                 $trole = $1;
                   5413:                 ($tend, $tstart) = split('_', $2);
                   5414:             } else {
                   5415:                 $trole = $role;
                   5416:             }
                   5417:         } elsif ($role =~ m|^gr/|) {
                   5418:         # Role of member in a group, defined within a course/community
                   5419:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5420:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5421:             next if $tstart eq '-1';
                   5422:             ($trole, $group_privs) = split(/\//, $trole);
                   5423:             $group_privs = &unescape($group_privs);
                   5424:         } else {
                   5425:         # Just a normal role, defined in roles.tab
                   5426:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5427:         }
                   5428: 
                   5429:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5430:                  $username);
                   5431:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5432: 
                   5433:         # role expired or not available yet?
                   5434:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5435:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5436: 
                   5437:         next if $area eq '' or $trole eq '';
                   5438: 
                   5439:         my $spec = "$trole.$area";
                   5440:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5441: 
                   5442:         if ($trole =~ /^cr\//) {
                   5443:         # Custom role, defined by a user
                   5444:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5445:         } elsif ($trole eq 'gr') {
                   5446:         # Role of a member in a group, defined within a course/community
                   5447:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5448:             next;
                   5449:         } else {
                   5450:         # Normal role, defined in roles.tab
                   5451:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5452:         }
                   5453: 
                   5454:         my $cid = $tdomain.'_'.$trest;
                   5455:         unless ($firstaccchk{$cid}) {
                   5456:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5457:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5458:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5459:                         $coursetimerstarts{$cid}{$item}; 
                   5460:                 }
                   5461:             }
                   5462:             $firstaccchk{$cid} = 1;
                   5463:         }
                   5464:         unless ($timerintchk{$cid}) {
                   5465:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5466:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5467:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5468:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5469:                 }
1.12      www      5470:             }
1.1169    droeschl 5471:             $timerintchk{$cid} = 1;
1.191     harris41 5472:         }
1.11      www      5473:     }
1.1169    droeschl 5474: 
                   5475:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5476:         \%allroles, \%allgroups);
                   5477:     $env{'user.adv'} = $userroles{'user.adv'};
                   5478: 
1.1162    raeburn  5479:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5480: }
                   5481: 
1.567     raeburn  5482: sub set_arearole {
1.1215    raeburn  5483:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5484:     unless ($nolog) {
1.567     raeburn  5485: # log the associated role with the area
1.1215    raeburn  5486:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5487:     }
1.743     albertel 5488:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5489: }
                   5490: 
                   5491: sub custom_roleprivs {
                   5492:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5493:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5494:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5495:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5496:         my ($rdummy,$roledef)=
                   5497:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5498:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5499:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5500:             if (defined($syspriv)) {
1.1043    raeburn  5501:                 if ($trest =~ /^$match_community$/) {
                   5502:                     $syspriv =~ s/bre\&S//; 
                   5503:                 }
1.567     raeburn  5504:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5505:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5506:             }
                   5507:             if ($tdomain ne '') {
                   5508:                 if (defined($dompriv)) {
                   5509:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5510:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5511:                 }
                   5512:                 if (($trest ne '') && (defined($coursepriv))) {
                   5513:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5514:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5515:                 }
                   5516:             }
                   5517:         }
                   5518:     }
                   5519: }
                   5520: 
1.678     raeburn  5521: sub group_roleprivs {
                   5522:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5523:     my $access = 1;
                   5524:     my $now = time;
                   5525:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5526:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5527:     if ($access) {
1.811     albertel 5528:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5529:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5530:     }
                   5531: }
1.567     raeburn  5532: 
                   5533: sub standard_roleprivs {
                   5534:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5535:     if (defined($pr{$trole.':s'})) {
                   5536:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5537:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5538:     }
                   5539:     if ($tdomain ne '') {
                   5540:         if (defined($pr{$trole.':d'})) {
                   5541:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5542:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5543:         }
                   5544:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5545:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5546:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5547:         }
                   5548:     }
                   5549: }
                   5550: 
                   5551: sub set_userprivs {
1.1064    raeburn  5552:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5553:     my $author=0;
                   5554:     my $adv=0;
1.678     raeburn  5555:     my %grouproles = ();
                   5556:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5557:         my @groupkeys; 
1.1000    raeburn  5558:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5559:             push(@groupkeys,$role);
                   5560:         }
                   5561:         if (ref($groups_roles) eq 'HASH') {
                   5562:             foreach my $key (keys(%{$groups_roles})) {
                   5563:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5564:                     push(@groupkeys,$key);
                   5565:                 }
                   5566:             }
                   5567:         }
                   5568:         if (@groupkeys > 0) {
                   5569:             foreach my $role (@groupkeys) {
                   5570:                 my ($trole,$area,$sec,$extendedarea);
                   5571:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5572:                     $trole = $1;
                   5573:                     $area = $2;
                   5574:                     $sec = $3;
                   5575:                     $extendedarea = $area.$sec;
                   5576:                     if (exists($$allgroups{$area})) {
                   5577:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5578:                             my $spec = $trole.'.'.$extendedarea;
                   5579:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5580:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5581:                         }
1.678     raeburn  5582:                     }
                   5583:                 }
                   5584:             }
                   5585:         }
                   5586:     }
1.800     albertel 5587:     foreach my $group (keys(%grouproles)) {
                   5588:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5589:     }
1.800     albertel 5590:     foreach my $role (keys(%{$allroles})) {
                   5591:         my %thesepriv;
1.941     raeburn  5592:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5593:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5594:             if ($item ne '') {
                   5595:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5596:                 if ($restrictions eq '') {
                   5597:                     $thesepriv{$privilege}='F';
                   5598:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5599:                     $thesepriv{$privilege}.=$restrictions;
                   5600:                 }
                   5601:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5602:             }
                   5603:         }
                   5604:         my $thesestr='';
1.1104    raeburn  5605:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5606: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5607: 	}
                   5608:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5609:     }
                   5610:     return ($author,$adv);
                   5611: }
                   5612: 
1.994     raeburn  5613: sub role_status {
1.1104    raeburn  5614:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5615:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5616:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5617:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5618:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5619:             $$where = '/'.$two;
1.994     raeburn  5620:             $$trolecode=$$role.'.'.$$where;
                   5621:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5622:             $$tstatus='is';
1.1104    raeburn  5623:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5624:                 $$tstatus='future';
1.1034    raeburn  5625:                 if ($$tstart<$now) {
                   5626:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5627:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5628:                             my (%allroles,%allgroups,$group_privs,
                   5629:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5630:                             my %userroles = (
                   5631:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5632:                             );
1.1064    raeburn  5633:                             @rolecodes = ('cm'); 
1.1002    raeburn  5634:                             my $spec=$$role.'.'.$$where;
                   5635:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5636:                             if ($$role =~ /^cr\//) {
                   5637:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5638:                                 push(@rolecodes,'cr');
1.1002    raeburn  5639:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5640:                                 push(@rolecodes,$$role);
1.1002    raeburn  5641:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5642:                                                     $env{'user.name'});
1.1064    raeburn  5643:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5644:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5645:                                 $group_privs = &unescape($group_privs);
                   5646:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5647:                                 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  5648:                                 &get_groups_roles($tdomain,$trest,
                   5649:                                                   \%course_roles,\@rolecodes,
                   5650:                                                   \%groups_roles);
1.1002    raeburn  5651:                             } else {
1.1064    raeburn  5652:                                 push(@rolecodes,$$role);
1.1002    raeburn  5653:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5654:                             }
1.1064    raeburn  5655:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5656:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5657:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5658:                         }
                   5659:                     }
1.1034    raeburn  5660:                     $$tstatus = 'is';
1.1002    raeburn  5661:                 }
1.994     raeburn  5662:             }
                   5663:             if ($$tend) {
1.1104    raeburn  5664:                 if ($$tend<$update) {
1.994     raeburn  5665:                     $$tstatus='expired';
                   5666:                 } elsif ($$tend<$now) {
                   5667:                     $$tstatus='will_not';
                   5668:                 }
                   5669:             }
                   5670:         }
                   5671:     }
                   5672: }
                   5673: 
1.1104    raeburn  5674: sub get_groups_roles {
                   5675:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5676:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5677:                   (ref($rolecodes) eq 'ARRAY') && 
                   5678:                   (ref($groups_roles) eq 'HASH')); 
                   5679:     if (keys(%{$cdom_courseroles}) > 0) {
                   5680:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5681:         if ($cdom ne '' && $cnum ne '') {
                   5682:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5683:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5684:                     my $crsrole = $1;
                   5685:                     my $crssec = $2;
                   5686:                     if ($crsrole =~ /^cr/) {
                   5687:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5688:                             push(@{$rolecodes},'cr');
                   5689:                         }
                   5690:                     } else {
                   5691:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5692:                             push(@{$rolecodes},$crsrole);
                   5693:                         }
                   5694:                     }
                   5695:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5696:                     if ($crssec ne '') {
                   5697:                         $rolekey .= "/$crssec";
                   5698:                     }
                   5699:                     $rolekey .= './';
                   5700:                     $groups_roles->{$rolekey} = $rolecodes;
                   5701:                 }
                   5702:             }
                   5703:         }
                   5704:     }
                   5705:     return;
                   5706: }
                   5707: 
                   5708: sub delete_env_groupprivs {
                   5709:     my ($where,$courseroles,$possroles) = @_;
                   5710:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5711:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5712:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5713:         %{$courseroles->{$udom}} =
                   5714:             &get_my_roles('','','userroles',['active'],
                   5715:                           $possroles,[$udom],1);
                   5716:     }
                   5717:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5718:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5719:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5720:             my $area = '/'.$cdom.'/'.$cnum;
                   5721:             my $privkey = "user.priv.$crsrole.$area";
                   5722:             if ($crssec ne '') {
                   5723:                 $privkey .= '/'.$crssec;
                   5724:             }
                   5725:             $privkey .= ".$area/$group";
                   5726:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5727:         }
                   5728:     }
                   5729:     return;
                   5730: }
                   5731: 
1.994     raeburn  5732: sub check_adhoc_privs {
1.1104    raeburn  5733:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5734:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5735:     my $setprivs;
1.994     raeburn  5736:     if ($env{$cckey}) {
                   5737:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5738:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5739:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5740:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5741:             $setprivs = 1;
1.994     raeburn  5742:         }
                   5743:     } else {
1.1088    raeburn  5744:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5745:         $setprivs = 1;
1.994     raeburn  5746:     }
1.1185    raeburn  5747:     return $setprivs;
1.994     raeburn  5748: }
                   5749: 
                   5750: sub set_adhoc_privileges {
                   5751: # role can be cc or ca
1.1088    raeburn  5752:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5753:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5754:     my $spec = $role.'.'.$area;
                   5755:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5756:                                   $env{'user.name'},1);
1.994     raeburn  5757:     my %ccrole = ();
                   5758:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5759:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5760:     &appenv(\%userroles,[$role,'cm']);
                   5761:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5762:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5763:         &appenv( {'request.role'        => $spec,
                   5764:                   'request.role.domain' => $dcdom,
                   5765:                   'request.course.sec'  => ''
                   5766:                  }
                   5767:                );
                   5768:         my $tadv=0;
                   5769:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5770:         &appenv({'request.role.adv'    => $tadv});
                   5771:     }
1.994     raeburn  5772: }
                   5773: 
1.12      www      5774: # --------------------------------------------------------------- get interface
                   5775: 
                   5776: sub get {
1.131     albertel 5777:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5778:    my $items='';
1.800     albertel 5779:    foreach my $item (@$storearr) {
                   5780:        $items.=&escape($item).'&';
1.191     harris41 5781:    }
1.12      www      5782:    $items=~s/\&$//;
1.620     albertel 5783:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5784:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5785:    my $uhome=&homeserver($uname,$udomain);
                   5786: 
1.133     albertel 5787:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5788:    my @pairs=split(/\&/,$rep);
1.273     albertel 5789:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5790:      return @pairs;
                   5791:    }
1.15      www      5792:    my %returnhash=();
1.42      www      5793:    my $i=0;
1.800     albertel 5794:    foreach my $item (@$storearr) {
                   5795:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5796:       $i++;
1.191     harris41 5797:    }
1.15      www      5798:    return %returnhash;
1.27      www      5799: }
                   5800: 
                   5801: # --------------------------------------------------------------- del interface
                   5802: 
                   5803: sub del {
1.133     albertel 5804:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5805:    my $items='';
1.800     albertel 5806:    foreach my $item (@$storearr) {
                   5807:        $items.=&escape($item).'&';
1.191     harris41 5808:    }
1.984     neumanie 5809: 
1.27      www      5810:    $items=~s/\&$//;
1.620     albertel 5811:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5812:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5813:    my $uhome=&homeserver($uname,$udomain);
                   5814:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5815: }
                   5816: 
                   5817: # -------------------------------------------------------------- dump interface
                   5818: 
1.1180    droeschl 5819: sub unserialize {
                   5820:     my ($rep, $escapedkeys) = @_;
                   5821: 
                   5822:     return {} if $rep =~ /^error/;
                   5823: 
                   5824:     my %returnhash=();
1.1252    raeburn  5825: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5826: 	    my ($key, $value) = split(/=/, $item, 2);
                   5827: 	    $key = unescape($key) unless $escapedkeys;
                   5828: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5829: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5830: 	}
                   5831:     #return %returnhash;
                   5832:     return \%returnhash;
                   5833: }        
                   5834: 
                   5835: # see Lond::dump_with_regexp
                   5836: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5837: sub dump {
1.1180    droeschl 5838:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5839:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5840:     if (!$uname) { $uname=$env{'user.name'}; }
                   5841:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5842: 
1.1266    raeburn  5843:     if ($regexp) {
                   5844:         $regexp=&escape($regexp);
                   5845:     } else {
                   5846:         $regexp='.';
                   5847:     }
1.1180    droeschl 5848:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5849:         # user is hosted on this machine
1.1266    raeburn  5850:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5851:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5852:         return %{unserialize($reply, $escapedkeys)};
                   5853:     }
1.1166    raeburn  5854:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5855:     my @pairs=split(/\&/,$rep);
                   5856:     my %returnhash=();
1.1098    foxr     5857:     if (!($rep =~ /^error/ )) {
                   5858: 	foreach my $item (@pairs) {
                   5859: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5860:         $key = unescape($key) unless $escapedkeys;
                   5861:         #$key = &unescape($key);
1.1098    foxr     5862: 	    next if ($key =~ /^error: 2 /);
                   5863: 	    $returnhash{$key}=&thaw_unescape($value);
                   5864: 	}
1.755     albertel 5865:     }
                   5866:     return %returnhash;
1.407     www      5867: }
                   5868: 
1.1098    foxr     5869: 
1.717     albertel 5870: # --------------------------------------------------------- dumpstore interface
                   5871: 
                   5872: sub dumpstore {
                   5873:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5874:    # same as dump but keys must be escaped. They may contain colon separated
                   5875:    # lists of values that may themself contain colons (e.g. symbs).
                   5876:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5877: }
                   5878: 
1.407     www      5879: # -------------------------------------------------------------- keys interface
                   5880: 
                   5881: sub getkeys {
                   5882:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5883:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5884:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5885:    my $uhome=&homeserver($uname,$udomain);
                   5886:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5887:    my @keyarray=();
1.800     albertel 5888:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5889:       next if ($key =~ /^error: 2 /);
1.800     albertel 5890:       push(@keyarray,&unescape($key));
1.407     www      5891:    }
                   5892:    return @keyarray;
1.318     matthew  5893: }
                   5894: 
1.319     matthew  5895: # --------------------------------------------------------------- currentdump
                   5896: sub currentdump {
1.328     matthew  5897:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5898:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5899:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5900:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5901:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5902:    my $rep;
                   5903: 
                   5904:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5905:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5906:                    $courseid)));
                   5907:    } else {
                   5908:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5909:    }
                   5910: 
1.318     matthew  5911:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5912:    #
1.318     matthew  5913:    my %returnhash=();
1.319     matthew  5914:    #
                   5915:    if ($rep eq "unknown_cmd") { 
                   5916:        # an old lond will not know currentdump
                   5917:        # Do a dump and make it look like a currentdump
1.822     albertel 5918:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5919:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5920:        my %hash = @tmp;
                   5921:        @tmp=();
1.424     matthew  5922:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5923:    } else {
                   5924:        my @pairs=split(/\&/,$rep);
1.800     albertel 5925:        foreach my $pair (@pairs) {
                   5926:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5927:            my ($symb,$param) = split(/:/,$key);
                   5928:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5929:                                                         &thaw_unescape($value);
1.319     matthew  5930:        }
1.191     harris41 5931:    }
1.12      www      5932:    return %returnhash;
1.424     matthew  5933: }
                   5934: 
                   5935: sub convert_dump_to_currentdump{
                   5936:     my %hash = %{shift()};
                   5937:     my %returnhash;
                   5938:     # Code ripped from lond, essentially.  The only difference
                   5939:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5940:     # we might run in to problems with parameter names =~ /^v\./
                   5941:     while (my ($key,$value) = each(%hash)) {
                   5942:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5943: 	$symb  = &unescape($symb);
                   5944: 	$param = &unescape($param);
1.424     matthew  5945:         next if ($v eq 'version' || $symb eq 'keys');
                   5946:         next if (exists($returnhash{$symb}) &&
                   5947:                  exists($returnhash{$symb}->{$param}) &&
                   5948:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5949:         $returnhash{$symb}->{$param}=$value;
                   5950:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5951:     }
                   5952:     #
                   5953:     # Remove all of the keys in the hashes which keep track of
                   5954:     # the version of the parameter.
                   5955:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5956:         # use a foreach because we are going to delete from the hash.
                   5957:         foreach my $key (keys(%$param_hash)) {
                   5958:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5959:         }
                   5960:     }
                   5961:     return \%returnhash;
1.12      www      5962: }
                   5963: 
1.627     albertel 5964: # ------------------------------------------------------ critical inc interface
                   5965: 
                   5966: sub cinc {
                   5967:     return &inc(@_,'critical');
                   5968: }
                   5969: 
1.449     matthew  5970: # --------------------------------------------------------------- inc interface
                   5971: 
                   5972: sub inc {
1.627     albertel 5973:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5974:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5975:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5976:     my $uhome=&homeserver($uname,$udomain);
                   5977:     my $items='';
                   5978:     if (! ref($store)) {
                   5979:         # got a single value, so use that instead
                   5980:         $items = &escape($store).'=&';
                   5981:     } elsif (ref($store) eq 'SCALAR') {
                   5982:         $items = &escape($$store).'=&';        
                   5983:     } elsif (ref($store) eq 'ARRAY') {
                   5984:         $items = join('=&',map {&escape($_);} @{$store});
                   5985:     } elsif (ref($store) eq 'HASH') {
                   5986:         while (my($key,$value) = each(%{$store})) {
                   5987:             $items.= &escape($key).'='.&escape($value).'&';
                   5988:         }
                   5989:     }
                   5990:     $items=~s/\&$//;
1.627     albertel 5991:     if ($critical) {
                   5992: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5993:     } else {
                   5994: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5995:     }
1.449     matthew  5996: }
                   5997: 
1.12      www      5998: # --------------------------------------------------------------- put interface
                   5999: 
                   6000: sub put {
1.134     albertel 6001:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6002:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6003:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6004:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6005:    my $items='';
1.800     albertel 6006:    foreach my $item (keys(%$storehash)) {
                   6007:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6008:    }
1.12      www      6009:    $items=~s/\&$//;
1.134     albertel 6010:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6011: }
                   6012: 
1.631     albertel 6013: # ------------------------------------------------------------ newput interface
                   6014: 
                   6015: sub newput {
                   6016:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6017:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6018:    if (!$uname) { $uname=$env{'user.name'}; }
                   6019:    my $uhome=&homeserver($uname,$udomain);
                   6020:    my $items='';
                   6021:    foreach my $key (keys(%$storehash)) {
                   6022:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6023:    }
                   6024:    $items=~s/\&$//;
                   6025:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6026: }
                   6027: 
                   6028: # ---------------------------------------------------------  putstore interface
                   6029: 
1.524     raeburn  6030: sub putstore {
1.1269    raeburn  6031:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6032:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6033:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6034:    my $uhome=&homeserver($uname,$udomain);
                   6035:    my $items='';
1.715     albertel 6036:    foreach my $key (keys(%$storehash)) {
                   6037:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6038:    }
1.715     albertel 6039:    $items=~s/\&$//;
1.716     albertel 6040:    my $esc_symb=&escape($symb);
                   6041:    my $esc_v=&escape($version);
1.715     albertel 6042:    my $reply =
1.716     albertel 6043:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6044: 	      $uhome);
1.1269    raeburn  6045:    if (($tolog) && ($reply eq 'ok')) {
                   6046:        my $namevalue='';
                   6047:        foreach my $key (keys(%{$storehash})) {
                   6048:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6049:        }
                   6050:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6051:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6052:                      '&version='.$esc_v.
                   6053:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6054:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6055:    }
1.715     albertel 6056:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6057:        # gfall back to way things use to be done
1.715     albertel 6058:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6059: 			    $uname);
1.524     raeburn  6060:    }
1.715     albertel 6061:    return $reply;
                   6062: }
                   6063: 
                   6064: sub old_putstore {
1.716     albertel 6065:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6066:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6067:     if (!$uname) { $uname=$env{'user.name'}; }
                   6068:     my $uhome=&homeserver($uname,$udomain);
                   6069:     my %newstorehash;
1.800     albertel 6070:     foreach my $item (keys(%$storehash)) {
                   6071: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6072: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6073:     }
                   6074:     my $items='';
                   6075:     my %allitems = ();
1.800     albertel 6076:     foreach my $item (keys(%newstorehash)) {
                   6077: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6078: 	    my $key = $1.':keys:'.$2;
                   6079: 	    $allitems{$key} .= $3.':';
                   6080: 	}
1.800     albertel 6081: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6082:     }
1.800     albertel 6083:     foreach my $item (keys(%allitems)) {
                   6084: 	$allitems{$item} =~ s/\:$//;
                   6085: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6086:     }
                   6087:     $items=~s/\&$//;
                   6088:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6089: }
                   6090: 
1.47      www      6091: # ------------------------------------------------------ critical put interface
                   6092: 
                   6093: sub cput {
1.134     albertel 6094:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6095:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6096:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6097:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6098:    my $items='';
1.800     albertel 6099:    foreach my $item (keys(%$storehash)) {
                   6100:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6101:    }
1.47      www      6102:    $items=~s/\&$//;
1.134     albertel 6103:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6104: }
                   6105: 
                   6106: # -------------------------------------------------------------- eget interface
                   6107: 
                   6108: sub eget {
1.133     albertel 6109:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6110:    my $items='';
1.800     albertel 6111:    foreach my $item (@$storearr) {
                   6112:        $items.=&escape($item).'&';
1.191     harris41 6113:    }
1.12      www      6114:    $items=~s/\&$//;
1.620     albertel 6115:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6116:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6117:    my $uhome=&homeserver($uname,$udomain);
                   6118:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6119:    my @pairs=split(/\&/,$rep);
                   6120:    my %returnhash=();
1.42      www      6121:    my $i=0;
1.800     albertel 6122:    foreach my $item (@$storearr) {
                   6123:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6124:       $i++;
1.191     harris41 6125:    }
1.12      www      6126:    return %returnhash;
                   6127: }
                   6128: 
1.667     albertel 6129: # ------------------------------------------------------------ tmpput interface
                   6130: sub tmpput {
1.802     raeburn  6131:     my ($storehash,$server,$context)=@_;
1.667     albertel 6132:     my $items='';
1.800     albertel 6133:     foreach my $item (keys(%$storehash)) {
                   6134: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6135:     }
                   6136:     $items=~s/\&$//;
1.802     raeburn  6137:     if (defined($context)) {
                   6138:         $items .= ':'.&escape($context);
                   6139:     }
1.667     albertel 6140:     return &reply("tmpput:$items",$server);
                   6141: }
                   6142: 
                   6143: # ------------------------------------------------------------ tmpget interface
                   6144: sub tmpget {
1.688     albertel 6145:     my ($token,$server)=@_;
                   6146:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6147:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6148:     my %returnhash;
                   6149:     foreach my $item (split(/\&/,$rep)) {
                   6150: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6151:         next if ($key =~ /^error: 2 /);
1.667     albertel 6152: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6153:     }
                   6154:     return %returnhash;
                   6155: }
                   6156: 
1.1113    raeburn  6157: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6158: sub tmpdel {
                   6159:     my ($token,$server)=@_;
                   6160:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6161:     return &reply("tmpdel:$token",$server);
                   6162: }
                   6163: 
1.1198    raeburn  6164: # ------------------------------------------------------------ get_timebased_id 
                   6165: 
                   6166: sub get_timebased_id {
                   6167:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6168:         $maxtries) = @_;
                   6169:     my ($newid,$error,$dellock);
                   6170:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6171:         return ('','ok','invalid call to get suffix');
                   6172:     }
                   6173: 
                   6174: # set defaults for any optional args for which values were not supplied
                   6175:     if ($who eq '') {
                   6176:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6177:     }
                   6178:     if (!$locktries) {
                   6179:         $locktries = 3;
                   6180:     }
                   6181:     if (!$maxtries) {
                   6182:         $maxtries = 10;
                   6183:     }
                   6184:     
                   6185:     if (($cdom eq '') || ($cnum eq '')) {
                   6186:         if ($env{'request.course.id'}) {
                   6187:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6188:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6189:         }
                   6190:         if (($cdom eq '') || ($cnum eq '')) {
                   6191:             return ('','ok','call to get suffix not in course context');
                   6192:         }
                   6193:     }
                   6194: 
                   6195: # construct locking item
                   6196:     my $lockhash = {
                   6197:                       $prefix."\0".'locked_'.$keyid => $who,
                   6198:                    };
                   6199:     my $tries = 0;
                   6200: 
                   6201: # attempt to get lock on nohist_$namespace file
                   6202:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6203:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6204:         $tries ++;
                   6205:         sleep 1;
                   6206:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6207:     }
                   6208: 
                   6209: # attempt to get unique identifier, based on current timestamp
                   6210:     if ($gotlock eq 'ok') {
                   6211:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6212:         my $id = time;
                   6213:         $newid = $id;
1.1268    raeburn  6214:         if ($idtype eq 'addcode') {
                   6215:             $newid .= &sixnum_code();
                   6216:         }
1.1198    raeburn  6217:         my $idtries = 0;
                   6218:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6219:             if ($idtype eq 'concat') {
                   6220:                 $newid = $id.$idtries;
1.1268    raeburn  6221:             } elsif ($idtype eq 'addcode') {
                   6222:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6223:             } else {
                   6224:                 $newid ++;
                   6225:             }
                   6226:             $idtries ++;
                   6227:         }
                   6228:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6229:             my %new_item =  (
                   6230:                               $prefix."\0".$newid => $who,
                   6231:                             );
                   6232:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6233:                                                  $cdom,$cnum);
                   6234:             if ($putresult ne 'ok') {
                   6235:                 undef($newid);
                   6236:                 $error = 'error saving new item: '.$putresult;
                   6237:             }
                   6238:         } else {
1.1268    raeburn  6239:              undef($newid);
1.1198    raeburn  6240:              $error = ('error: no unique suffix available for the new item ');
                   6241:         }
                   6242: #  remove lock
                   6243:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6244:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6245:     } else {
                   6246:         $error = "error: could not obtain lockfile\n";
                   6247:         $dellock = 'ok';
1.1276    raeburn  6248:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6249:             $dellock = 'nolock';
                   6250:         }
1.1198    raeburn  6251:     }
                   6252:     return ($newid,$dellock,$error);
                   6253: }
                   6254: 
1.1268    raeburn  6255: sub sixnum_code {
                   6256:     my $code;
                   6257:     for (0..6) {
                   6258:         $code .= int( rand(9) );
                   6259:     }
                   6260:     return $code;
                   6261: }
                   6262: 
1.765     albertel 6263: # -------------------------------------------------- portfolio access checking
                   6264: 
                   6265: sub portfolio_access {
1.1270    raeburn  6266:     my ($requrl,$clientip) = @_;
1.765     albertel 6267:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6268:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6269:     if ($result) {
                   6270:         my %setters;
                   6271:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6272:             my ($startblock,$endblock) =
                   6273:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6274:             if ($startblock && $endblock) {
                   6275:                 return 'B';
                   6276:             }
                   6277:         } else {
                   6278:             my ($startblock,$endblock) =
                   6279:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6280:             if ($startblock && $endblock) {
                   6281:                 return 'B';
                   6282:             }
                   6283:         }
                   6284:     }
1.765     albertel 6285:     if ($result eq 'ok') {
1.766     albertel 6286:        return 'F';
1.765     albertel 6287:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6288:        return 'A';
1.765     albertel 6289:     }
1.766     albertel 6290:     return '';
1.765     albertel 6291: }
                   6292: 
                   6293: sub get_portfolio_access {
1.1270    raeburn  6294:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6295: 
                   6296:     if (!ref($access_hash)) {
                   6297: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6298: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6299: 						   $file_name);
                   6300: 	$access_hash = $access_controls{$file_name};
                   6301:     }
                   6302: 
1.1270    raeburn  6303:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6304:     my $now = time;
                   6305:     if (ref($access_hash) eq 'HASH') {
                   6306:         foreach my $key (keys(%{$access_hash})) {
                   6307:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6308:             if ($start > $now) {
                   6309:                 next;
                   6310:             }
                   6311:             if ($end && $end<$now) {
                   6312:                 next;
                   6313:             }
                   6314:             if ($scope eq 'public') {
                   6315:                 $public = $key;
                   6316:                 last;
                   6317:             } elsif ($scope eq 'guest') {
                   6318:                 $guest = $key;
                   6319:             } elsif ($scope eq 'domains') {
                   6320:                 push(@domains,$key);
                   6321:             } elsif ($scope eq 'users') {
                   6322:                 push(@users,$key);
                   6323:             } elsif ($scope eq 'course') {
                   6324:                 push(@courses,$key);
                   6325:             } elsif ($scope eq 'group') {
                   6326:                 push(@groups,$key);
1.1270    raeburn  6327:             } elsif ($scope eq 'ip') {
                   6328:                 push(@ips,$key);
1.765     albertel 6329:             }
                   6330:         }
                   6331:         if ($public) {
                   6332:             return 'ok';
1.1270    raeburn  6333:         } elsif (@ips > 0) {
                   6334:             my $allowed;
                   6335:             foreach my $ipkey (@ips) {
                   6336:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6337:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6338:                         $allowed = 1;
                   6339:                         last; 
                   6340:                     }
                   6341:                 }
                   6342:             }
                   6343:             if ($allowed) {
                   6344:                 return 'ok';
                   6345:             }
1.765     albertel 6346:         }
                   6347:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6348:             if ($guest) {
                   6349:                 return $guest;
                   6350:             }
                   6351:         } else {
                   6352:             if (@domains > 0) {
                   6353:                 foreach my $domkey (@domains) {
                   6354:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6355:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6356:                             return 'ok';
                   6357:                         }
                   6358:                     }
                   6359:                 }
                   6360:             }
                   6361:             if (@users > 0) {
                   6362:                 foreach my $userkey (@users) {
1.865     raeburn  6363:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6364:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6365:                             if (ref($item) eq 'HASH') {
                   6366:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6367:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6368:                                     return 'ok';
                   6369:                                 }
                   6370:                             }
                   6371:                         }
                   6372:                     } 
1.765     albertel 6373:                 }
                   6374:             }
                   6375:             my %roleshash;
                   6376:             my @courses_and_groups = @courses;
                   6377:             push(@courses_and_groups,@groups); 
                   6378:             if (@courses_and_groups > 0) {
                   6379:                 my (%allgroups,%allroles); 
                   6380:                 my ($start,$end,$role,$sec,$group);
                   6381:                 foreach my $envkey (%env) {
1.1060    raeburn  6382:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6383:                         my $cid = $2.'_'.$3; 
                   6384:                         if ($1 eq 'gr') {
                   6385:                             $group = $4;
                   6386:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6387:                         } else {
                   6388:                             if ($4 eq '') {
                   6389:                                 $sec = 'none';
                   6390:                             } else {
                   6391:                                 $sec = $4;
                   6392:                             }
                   6393:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6394:                         }
1.811     albertel 6395:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6396:                         my $cid = $2.'_'.$3;
                   6397:                         if ($4 eq '') {
                   6398:                             $sec = 'none';
                   6399:                         } else {
                   6400:                             $sec = $4;
                   6401:                         }
                   6402:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6403:                     }
                   6404:                 }
                   6405:                 if (keys(%allroles) == 0) {
                   6406:                     return;
                   6407:                 }
                   6408:                 foreach my $key (@courses_and_groups) {
                   6409:                     my %content = %{$$access_hash{$key}};
                   6410:                     my $cnum = $content{'number'};
                   6411:                     my $cdom = $content{'domain'};
                   6412:                     my $cid = $cdom.'_'.$cnum;
                   6413:                     if (!exists($allroles{$cid})) {
                   6414:                         next;
                   6415:                     }    
                   6416:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6417:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6418:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6419:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6420:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6421:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6422:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6423:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6424:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6425:                                         if (grep/^all$/,@sections) {
                   6426:                                             return 'ok';
                   6427:                                         } else {
                   6428:                                             if (grep/^$sec$/,@sections) {
                   6429:                                                 return 'ok';
                   6430:                                             }
                   6431:                                         }
                   6432:                                     }
                   6433:                                 }
                   6434:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6435:                                     if (grep/^none$/,@groups) {
                   6436:                                         return 'ok';
                   6437:                                     }
                   6438:                                 } else {
                   6439:                                     if (grep/^all$/,@groups) {
                   6440:                                         return 'ok';
                   6441:                                     } 
                   6442:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6443:                                         if (grep/^$group$/,@groups) {
                   6444:                                             return 'ok';
                   6445:                                         }
                   6446:                                     }
                   6447:                                 } 
                   6448:                             }
                   6449:                         }
                   6450:                     }
                   6451:                 }
                   6452:             }
                   6453:             if ($guest) {
                   6454:                 return $guest;
                   6455:             }
                   6456:         }
                   6457:     }
                   6458:     return;
                   6459: }
                   6460: 
                   6461: sub course_group_datechecker {
                   6462:     my ($dates,$now,$status) = @_;
                   6463:     my ($start,$end) = split(/\./,$dates);
                   6464:     if (!$start && !$end) {
                   6465:         return 'ok';
                   6466:     }
                   6467:     if (grep/^active$/,@{$status}) {
                   6468:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6469:             return 'ok';
                   6470:         }
                   6471:     }
                   6472:     if (grep/^previous$/,@{$status}) {
                   6473:         if ($end > $now ) {
                   6474:             return 'ok';
                   6475:         }
                   6476:     }
                   6477:     if (grep/^future$/,@{$status}) {
                   6478:         if ($start > $now) {
                   6479:             return 'ok';
                   6480:         }
                   6481:     }
                   6482:     return; 
                   6483: }
                   6484: 
                   6485: sub parse_portfolio_url {
                   6486:     my ($url) = @_;
                   6487: 
                   6488:     my ($type,$udom,$unum,$group,$file_name);
                   6489:     
1.823     albertel 6490:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6491: 	$type = 1;
                   6492:         $udom = $1;
                   6493:         $unum = $2;
                   6494:         $file_name = $3;
1.823     albertel 6495:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6496: 	$type = 2;
                   6497:         $udom = $1;
                   6498:         $unum = $2;
                   6499:         $group = $3;
                   6500:         $file_name = $3.'/'.$4;
                   6501:     }
                   6502:     if (wantarray) {
                   6503: 	return ($type,$udom,$unum,$file_name,$group);
                   6504:     }
                   6505:     return $type;
                   6506: }
                   6507: 
                   6508: sub is_portfolio_url {
                   6509:     my ($url) = @_;
                   6510:     return scalar(&parse_portfolio_url($url));
                   6511: }
                   6512: 
1.798     raeburn  6513: sub is_portfolio_file {
                   6514:     my ($file) = @_;
1.820     raeburn  6515:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6516:         return 1;
                   6517:     }
                   6518:     return;
                   6519: }
                   6520: 
1.976     raeburn  6521: sub usertools_access {
1.1084    raeburn  6522:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6523:     my ($access,%tools);
                   6524:     if ($context eq '') {
                   6525:         $context = 'tools';
                   6526:     }
                   6527:     if ($context eq 'requestcourses') {
                   6528:         %tools = (
                   6529:                       official   => 1,
                   6530:                       unofficial => 1,
1.1006    raeburn  6531:                       community  => 1,
1.1246    raeburn  6532:                       textbook   => 1,
1.985     raeburn  6533:                  );
1.1183    raeburn  6534:     } elsif ($context eq 'requestauthor') {
                   6535:         %tools = (
                   6536:                       requestauthor => 1,
                   6537:                  );
1.985     raeburn  6538:     } else {
                   6539:         %tools = (
                   6540:                       aboutme   => 1,
                   6541:                       blog      => 1,
1.1177    raeburn  6542:                       webdav    => 1,
1.985     raeburn  6543:                       portfolio => 1,
                   6544:                  );
                   6545:     }
1.976     raeburn  6546:     return if (!defined($tools{$tool}));
                   6547: 
1.1242    raeburn  6548:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6549:         $udom = $env{'user.domain'};
                   6550:         $uname = $env{'user.name'};
                   6551:     }
                   6552: 
1.978     raeburn  6553:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6554:         if ($action ne 'reload') {
1.985     raeburn  6555:             if ($context eq 'requestcourses') {
                   6556:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6557:             } elsif ($context eq 'requestauthor') {
                   6558:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6559:             } else {
                   6560:                 return $env{'environment.availabletools.'.$tool};
                   6561:             }
                   6562:         }
1.976     raeburn  6563:     }
                   6564: 
1.1183    raeburn  6565:     my ($toolstatus,$inststatus,$envkey);
                   6566:     if ($context eq 'requestauthor') {
                   6567:         $envkey = $context; 
                   6568:     } else {
                   6569:         $envkey = $context.'.'.$tool;
                   6570:     }
1.976     raeburn  6571: 
1.985     raeburn  6572:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6573:          ($action ne 'reload')) {
1.1183    raeburn  6574:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6575:         $inststatus = $env{'environment.inststatus'};
                   6576:     } else {
1.1084    raeburn  6577:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6578:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6579:             $inststatus = $userenvref->{'inststatus'};
                   6580:         } else {
1.1183    raeburn  6581:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6582:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6583:             $inststatus = $userenv{'inststatus'};
                   6584:         }
1.976     raeburn  6585:     }
                   6586: 
                   6587:     if ($toolstatus ne '') {
                   6588:         if ($toolstatus) {
                   6589:             $access = 1;
                   6590:         } else {
                   6591:             $access = 0;
                   6592:         }
                   6593:         return $access;
                   6594:     }
                   6595: 
1.1084    raeburn  6596:     my ($is_adv,%domdef);
                   6597:     if (ref($is_advref) eq 'HASH') {
                   6598:         $is_adv = $is_advref->{'is_adv'};
                   6599:     } else {
                   6600:         $is_adv = &is_advanced_user($udom,$uname);
                   6601:     }
                   6602:     if (ref($domdefref) eq 'HASH') {
                   6603:         %domdef = %{$domdefref};
                   6604:     } else {
                   6605:         %domdef = &get_domain_defaults($udom);
                   6606:     }
1.976     raeburn  6607:     if (ref($domdef{$tool}) eq 'HASH') {
                   6608:         if ($is_adv) {
                   6609:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6610:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6611:                     $access = 1;
                   6612:                 } else {
                   6613:                     $access = 0;
                   6614:                 }
                   6615:                 return $access;
                   6616:             }
                   6617:         }
                   6618:         if ($inststatus ne '') {
                   6619:             my ($hasaccess,$hasnoaccess);
                   6620:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6621:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6622:                     if ($domdef{$tool}{$affiliation}) {
                   6623:                         $hasaccess = 1;
                   6624:                     } else {
                   6625:                         $hasnoaccess = 1;
                   6626:                     }
                   6627:                 }
                   6628:             }
                   6629:             if ($hasaccess || $hasnoaccess) {
                   6630:                 if ($hasaccess) {
                   6631:                     $access = 1;
                   6632:                 } elsif ($hasnoaccess) {
                   6633:                     $access = 0; 
                   6634:                 }
                   6635:                 return $access;
                   6636:             }
                   6637:         } else {
                   6638:             if ($domdef{$tool}{'default'} ne '') {
                   6639:                 if ($domdef{$tool}{'default'}) {
                   6640:                     $access = 1;
                   6641:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6642:                     $access = 0;
                   6643:                 }
                   6644:                 return $access;
                   6645:             }
                   6646:         }
                   6647:     } else {
1.1177    raeburn  6648:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6649:             $access = 1;
                   6650:         } else {
                   6651:             $access = 0;
                   6652:         }
1.976     raeburn  6653:         return $access;
                   6654:     }
                   6655: }
                   6656: 
1.1050    raeburn  6657: sub is_course_owner {
                   6658:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6659:     if (($udom eq '') || ($uname eq '')) {
                   6660:         $udom = $env{'user.domain'};
                   6661:         $uname = $env{'user.name'};
                   6662:     }
                   6663:     unless (($udom eq '') || ($uname eq '')) {
                   6664:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6665:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6666:                 return 1;
                   6667:             } else {
                   6668:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6669:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6670:                     return 1;
                   6671:                 }
                   6672:             }
                   6673:         }
                   6674:     }
                   6675:     return;
                   6676: }
                   6677: 
1.976     raeburn  6678: sub is_advanced_user {
                   6679:     my ($udom,$uname) = @_;
1.1085    raeburn  6680:     if ($udom ne '' && $uname ne '') {
                   6681:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6682:             if (wantarray) {
                   6683:                 return ($env{'user.adv'},$env{'user.author'});
                   6684:             } else {
                   6685:                 return $env{'user.adv'};
                   6686:             }
1.1085    raeburn  6687:         }
                   6688:     }
1.976     raeburn  6689:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6690:     my %allroles;
1.1128    raeburn  6691:     my ($is_adv,$is_author);
1.976     raeburn  6692:     foreach my $role (keys(%roleshash)) {
                   6693:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6694:         my $area = '/'.$tdomain.'/'.$trest;
                   6695:         if ($sec ne '') {
                   6696:             $area .= '/'.$sec;
                   6697:         }
                   6698:         if (($area ne '') && ($trole ne '')) {
                   6699:             my $spec=$trole.'.'.$area;
                   6700:             if ($trole =~ /^cr\//) {
                   6701:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6702:             } elsif ($trole ne 'gr') {
                   6703:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6704:             }
1.1128    raeburn  6705:             if ($trole eq 'au') {
                   6706:                 $is_author = 1;
                   6707:             }
1.976     raeburn  6708:         }
                   6709:     }
                   6710:     foreach my $role (keys(%allroles)) {
                   6711:         last if ($is_adv);
                   6712:         foreach my $item (split(/:/,$allroles{$role})) {
                   6713:             if ($item ne '') {
                   6714:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6715:                 if ($privilege eq 'adv') {
                   6716:                     $is_adv = 1;
                   6717:                     last;
                   6718:                 }
                   6719:             }
                   6720:         }
                   6721:     }
1.1128    raeburn  6722:     if (wantarray) {
                   6723:         return ($is_adv,$is_author);
                   6724:     }
1.976     raeburn  6725:     return $is_adv;
                   6726: }
1.798     raeburn  6727: 
1.1035    raeburn  6728: sub check_can_request {
1.1036    raeburn  6729:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6730:     my $canreq = 0;
                   6731:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6732:     my @options = ('approval','validate','autolimit');
                   6733:     my $optregex = join('|',@options);
                   6734:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6735:         foreach my $type (@{$types}) {
                   6736:             if (&usertools_access($env{'user.name'},
                   6737:                                   $env{'user.domain'},
                   6738:                                   $type,undef,'requestcourses')) {
                   6739:                 $canreq ++;
1.1036    raeburn  6740:                 if (ref($request_domains) eq 'HASH') {
                   6741:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6742:                 }
1.1035    raeburn  6743:                 if ($dom eq $env{'user.domain'}) {
                   6744:                     $can_request->{$type} = 1;
                   6745:                 }
                   6746:             }
                   6747:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6748:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6749:                 if (@curr > 0) {
1.1036    raeburn  6750:                     foreach my $item (@curr) {
                   6751:                         if (ref($request_domains) eq 'HASH') {
                   6752:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6753:                             if ($otherdom ne '') {
                   6754:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6755:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6756:                                         push(@{$request_domains->{$type}},$otherdom);
                   6757:                                     }
                   6758:                                 } else {
                   6759:                                     push(@{$request_domains->{$type}},$otherdom);
                   6760:                                 }
                   6761:                             }
                   6762:                         }
                   6763:                     }
                   6764:                     unless($dom eq $env{'user.domain'}) {
                   6765:                         $canreq ++;
1.1035    raeburn  6766:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6767:                             $can_request->{$type} = 1;
                   6768:                         }
                   6769:                     }
                   6770:                 }
                   6771:             }
                   6772:         }
                   6773:     }
                   6774:     return $canreq;
                   6775: }
                   6776: 
1.341     www      6777: # ---------------------------------------------- Custom access rule evaluation
                   6778: 
                   6779: sub customaccess {
                   6780:     my ($priv,$uri)=@_;
1.807     albertel 6781:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6782:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6783:     $udom = &LONCAPA::clean_domain($udom);
                   6784:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6785:     my $access=0;
1.800     albertel 6786:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6787: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6788: 	if ($type eq 'user') {
                   6789: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6790: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6791: 		if ($tdom) {
                   6792: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6793: 		}
1.896     albertel 6794: 		if ($tuname) {
                   6795: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6796: 		}
                   6797: 		$access=($effect eq 'allow');
                   6798: 		last;
                   6799: 	    }
                   6800: 	} else {
                   6801: 	    if ($role) {
                   6802: 		if ($role ne $urole) { next; }
                   6803: 	    }
                   6804: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6805: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6806: 		if ($tdom) {
                   6807: 		    if ($tdom ne $udom) { next; }
                   6808: 		}
                   6809: 		if ($tcrs) {
                   6810: 		    if ($tcrs ne $ucrs) { next; }
                   6811: 		}
                   6812: 		if ($tsec) {
                   6813: 		    if ($tsec ne $usec) { next; }
                   6814: 		}
                   6815: 		$access=($effect eq 'allow');
                   6816: 		last;
                   6817: 	    }
                   6818: 	    if ($realm eq '' && $role eq '') {
                   6819: 		$access=($effect eq 'allow');
                   6820: 	    }
1.402     bowersj2 6821: 	}
1.341     www      6822:     }
                   6823:     return $access;
                   6824: }
                   6825: 
1.103     harris41 6826: # ------------------------------------------------- Check for a user privilege
1.12      www      6827: 
                   6828: sub allowed {
1.1281    raeburn  6829:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6830:     my $ver_orguri=$uri;
1.439     www      6831:     $uri=&deversion($uri);
1.152     www      6832:     my $orguri=$uri;
1.52      www      6833:     $uri=&declutter($uri);
1.809     raeburn  6834: 
1.810     raeburn  6835:     if ($priv eq 'evb') {
                   6836: # Evade communication block restrictions for specified role in a course
                   6837:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6838:             return $1;
                   6839:         } else {
                   6840:             return;
                   6841:         }
                   6842:     }
                   6843: 
1.620     albertel 6844:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6845: # Free bre access to adm and meta resources
1.775     albertel 6846:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6847: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6848: 	&& ($priv eq 'bre')) {
1.14      www      6849: 	return 'F';
1.159     www      6850:     }
                   6851: 
1.545     banghart 6852: # Free bre access to user's own portfolio contents
1.714     raeburn  6853:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6854:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6855: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6856:         my %setters;
                   6857:         my ($startblock,$endblock) = 
                   6858:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6859:         if ($startblock && $endblock) {
                   6860:             return 'B';
                   6861:         } else {
                   6862:             return 'F';
                   6863:         }
1.545     banghart 6864:     }
                   6865: 
1.762     raeburn  6866: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6867:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6868:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6869:         if (exists($env{'request.course.id'})) {
                   6870:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6871:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6872:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6873:                 my $courseprivid=$env{'request.course.id'};
                   6874:                 $courseprivid=~s/\_/\//;
                   6875:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6876:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6877:                     return $1; 
1.762     raeburn  6878:                 } else {
                   6879:                     if ($env{'request.course.sec'}) {
                   6880:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6881:                     }
                   6882:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6883:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6884:                         return $2;
                   6885:                     }
1.714     raeburn  6886:                 }
                   6887:             }
                   6888:         }
                   6889:     }
                   6890: 
1.159     www      6891: # Free bre to public access
                   6892: 
                   6893:     if ($priv eq 'bre') {
1.238     www      6894:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6895: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6896:            return 'F'; 
                   6897:         }
1.238     www      6898:         if ($copyright eq 'priv') {
                   6899:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6900: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6901: 		return '';
                   6902:             }
                   6903:         }
                   6904:         if ($copyright eq 'domain') {
                   6905:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6906: 	    unless (($env{'user.domain'} eq $1) ||
                   6907:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6908: 		return '';
                   6909:             }
1.262     matthew  6910:         }
1.620     albertel 6911:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6912:             # Library role, so allow browsing of resources in this domain.
                   6913:             return 'F';
1.238     www      6914:         }
1.341     www      6915:         if ($copyright eq 'custom') {
                   6916: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6917:         }
1.14      www      6918:     }
1.264     matthew  6919:     # Domain coordinator is trying to create a course
1.620     albertel 6920:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6921:         # uri is the requested domain in this case.
                   6922:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6923:         # a role of dc for the domain in question.
1.620     albertel 6924:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6925:     }
1.29      www      6926: 
1.52      www      6927:     my $thisallowed='';
                   6928:     my $statecond=0;
                   6929:     my $courseprivid='';
                   6930: 
1.1039    raeburn  6931:     my $ownaccess;
1.1043    raeburn  6932:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6933:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6934:         if ($uri eq '') {
                   6935:             $ownaccess = 1;
                   6936:         } else {
                   6937:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6938:                 my $udom = $env{'user.domain'};
                   6939:                 my $uname = $env{'user.name'};
                   6940:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6941:                     $ownaccess = 1;
1.1040    raeburn  6942:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6943:                     unless ($uri =~ m{\.\./}) {
                   6944:                         $ownaccess = 1;
                   6945:                     }
                   6946:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6947:                     my $now = time;
                   6948:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6949:                         my $adom = $1;
                   6950:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6951:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6952:                                 my ($start,$end) = split('.',$env{$key});
                   6953:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6954:                                     $ownaccess = 1;
                   6955:                                     last;
                   6956:                                 }
                   6957:                             }
                   6958:                         }
                   6959:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6960:                         my $adom = $1;
                   6961:                         my $aname = $2;
1.1042    raeburn  6962:                         foreach my $role ('ca','aa') { 
                   6963:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6964:                                 my ($start,$end) =
                   6965:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6966:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6967:                                     $ownaccess = 1;
                   6968:                                     last;
                   6969:                                 }
1.1039    raeburn  6970:                             }
                   6971:                         }
                   6972:                     }
                   6973:                 }
                   6974:             }
                   6975:         }
                   6976:     }
                   6977: 
1.52      www      6978: # Course
                   6979: 
1.620     albertel 6980:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6981:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6982:             $thisallowed.=$1;
                   6983:         }
1.52      www      6984:     }
1.29      www      6985: 
1.52      www      6986: # Domain
                   6987: 
1.620     albertel 6988:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6989:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6990:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6991:             $thisallowed.=$1;
                   6992:         }
1.12      www      6993:     }
1.52      www      6994: 
1.1141    raeburn  6995: # User who is not author or co-author might still be able to edit
                   6996: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6997:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6998:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6999:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7000:             $thisallowed.=$1;
                   7001:         }
                   7002:     }
                   7003: 
1.52      www      7004: # Course: uri itself is a course
1.66      www      7005:     my $courseuri=$uri;
                   7006:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7007:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7008: 
1.620     albertel 7009:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7010:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7011:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7012:             $thisallowed.=$1;
                   7013:         }
1.12      www      7014:     }
1.29      www      7015: 
1.665     albertel 7016: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7017: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7018:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7019: 	$thisallowed='';
1.671     raeburn  7020:         my ($match)=&is_on_map($uri);
                   7021:         if ($match) {
                   7022:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7023:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7024:                 my $value = $1;
                   7025:                 if ($noblockcheck) {
                   7026:                     $thisallowed.=$value;
1.1162    raeburn  7027:                 } else {
1.1281    raeburn  7028:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7029:                     if (@blockers > 0) {
                   7030:                         $thisallowed = 'B';
                   7031:                     } else {
                   7032:                         $thisallowed.=$value;
                   7033:                     }
1.1162    raeburn  7034:                 }
1.671     raeburn  7035:             }
                   7036:         } else {
1.705     albertel 7037:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7038:             if ($refuri) {
                   7039:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7040:                     $thisallowed='F';
1.671     raeburn  7041:                 } else {
                   7042:                     $refuri=&declutter($refuri);
                   7043:                     my ($match) = &is_on_map($refuri);
                   7044:                     if ($match) {
1.1281    raeburn  7045:                         if ($noblockcheck) {
                   7046:                             $thisallowed='F';
1.1162    raeburn  7047:                         } else {
1.1281    raeburn  7048:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7049:                             if (@blockers > 0) {
                   7050:                                 $thisallowed = 'B';
                   7051:                             } else {
                   7052:                                 $thisallowed='F';
                   7053:                             }
1.1162    raeburn  7054:                         }
1.671     raeburn  7055:                     }
1.669     raeburn  7056:                 }
1.671     raeburn  7057:             }
                   7058:         }
1.314     www      7059:     }
1.492     albertel 7060: 
1.766     albertel 7061:     if ($priv eq 'bre'
                   7062: 	&& $thisallowed ne 'F' 
                   7063: 	&& $thisallowed ne '2'
                   7064: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7065: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7066:     }
1.1250    raeburn  7067: 
1.52      www      7068: # Full access at system, domain or course-wide level? Exit.
1.29      www      7069:     if ($thisallowed=~/F/) {
                   7070: 	return 'F';
                   7071:     }
                   7072: 
1.52      www      7073: # If this is generating or modifying users, exit with special codes
1.29      www      7074: 
1.643     www      7075:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7076: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7077: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7078: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7079: 	    unless ($auname) { return $thisallowed; }
                   7080: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7081: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7082: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7083: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7084: 	}
1.52      www      7085: 	return $thisallowed;
                   7086:     }
                   7087: #
1.103     harris41 7088: # Gathered so far: system, domain and course wide privileges
1.52      www      7089: #
                   7090: # Course: See if uri or referer is an individual resource that is part of 
                   7091: # the course
                   7092: 
1.620     albertel 7093:     if ($env{'request.course.id'}) {
1.232     www      7094: 
1.620     albertel 7095:        $courseprivid=$env{'request.course.id'};
                   7096:        if ($env{'request.course.sec'}) {
                   7097:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7098:        }
                   7099:        $courseprivid=~s/\_/\//;
                   7100:        my $checkreferer=1;
1.232     www      7101:        my ($match,$cond)=&is_on_map($uri);
                   7102:        if ($match) {
                   7103:            $statecond=$cond;
1.620     albertel 7104:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7105:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7106:                my $value = $1;
                   7107:                if ($priv eq 'bre') {
1.1281    raeburn  7108:                    if ($noblockcheck) {
                   7109:                        $thisallowed.=$value;
1.1162    raeburn  7110:                    } else {
1.1281    raeburn  7111:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7112:                        if (@blockers > 0) {
                   7113:                            $thisallowed = 'B';
                   7114:                        } else {
                   7115:                            $thisallowed.=$value;
                   7116:                        }
1.1162    raeburn  7117:                    }
                   7118:                } else {
                   7119:                    $thisallowed.=$value;
                   7120:                }
1.52      www      7121:                $checkreferer=0;
                   7122:            }
1.29      www      7123:        }
1.83      www      7124:        
1.148     www      7125:        if ($checkreferer) {
1.620     albertel 7126: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7127:             unless ($refuri) {
1.800     albertel 7128:                 foreach my $key (keys(%env)) {
                   7129: 		    if ($key=~/^httpref\..*\*/) {
                   7130: 			my $pattern=$key;
1.156     www      7131:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7132:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7133:                         $pattern=~s/\//\\\//g;
1.152     www      7134:                         if ($orguri=~/$pattern/) {
1.800     albertel 7135: 			    $refuri=$env{$key};
1.148     www      7136:                         }
                   7137:                     }
1.191     harris41 7138:                 }
1.148     www      7139:             }
1.232     www      7140: 
1.148     www      7141:          if ($refuri) { 
1.152     www      7142: 	  $refuri=&declutter($refuri);
1.232     www      7143:           my ($match,$cond)=&is_on_map($refuri);
                   7144:             if ($match) {
                   7145:               my $refstatecond=$cond;
1.620     albertel 7146:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7147:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7148:                   my $value = $1;
                   7149:                   if ($priv eq 'bre') {
1.1281    raeburn  7150:                       if ($noblockcheck) {
                   7151:                           $thisallowed.=$value;
1.1162    raeburn  7152:                       } else {
1.1281    raeburn  7153:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7154:                           if (@blockers > 0) {
                   7155:                               $thisallowed = 'B';
                   7156:                           } else {
                   7157:                               $thisallowed.=$value;
                   7158:                           }
1.1162    raeburn  7159:                       }
                   7160:                   } else {
                   7161:                       $thisallowed.=$value;
                   7162:                   }
1.53      www      7163:                   $uri=$refuri;
                   7164:                   $statecond=$refstatecond;
1.52      www      7165:               }
                   7166:           }
1.148     www      7167:         }
1.29      www      7168:        }
1.52      www      7169:    }
1.29      www      7170: 
1.52      www      7171: #
1.103     harris41 7172: # Gathered now: all privileges that could apply, and condition number
1.52      www      7173: # 
                   7174: #
                   7175: # Full or no access?
                   7176: #
1.29      www      7177: 
1.52      www      7178:     if ($thisallowed=~/F/) {
                   7179: 	return 'F';
                   7180:     }
1.29      www      7181: 
1.52      www      7182:     unless ($thisallowed) {
                   7183:         return '';
                   7184:     }
1.29      www      7185: 
1.52      www      7186: # Restrictions exist, deal with them
                   7187: #
                   7188: #   C:according to course preferences
                   7189: #   R:according to resource settings
                   7190: #   L:unless locked
                   7191: #   X:according to user session state
                   7192: #
                   7193: 
                   7194: # Possibly locked functionality, check all courses
1.54      www      7195: # Locks might take effect only after 10 minutes cache expiration for other
                   7196: # courses, and 2 minutes for current course
1.52      www      7197: 
                   7198:     my $envkey;
                   7199:     if ($thisallowed=~/L/) {
1.1000    raeburn  7200:         foreach $envkey (keys(%env)) {
1.54      www      7201:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7202:                my $courseid=$2;
                   7203:                my $roleid=$1.'.'.$2;
1.92      www      7204:                $courseid=~s/^\///;
1.54      www      7205:                my $expiretime=600;
1.620     albertel 7206:                if ($env{'request.role'} eq $roleid) {
1.54      www      7207: 		  $expiretime=120;
                   7208:                }
                   7209: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7210:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7211:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7212: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7213:                }
1.620     albertel 7214:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7215:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7216: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7217:                        &log($env{'user.domain'},$env{'user.name'},
                   7218:                             $env{'user.home'},
1.57      www      7219:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7220:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7221:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7222: 		       return '';
                   7223:                    }
                   7224:                }
1.620     albertel 7225:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7226:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7227: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7228:                        &log($env{'user.domain'},$env{'user.name'},
                   7229:                             $env{'user.home'},
1.57      www      7230:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7231:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7232:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7233: 		       return '';
                   7234:                    }
                   7235:                }
                   7236: 	   }
1.29      www      7237:        }
1.52      www      7238:     }
                   7239:    
                   7240: #
                   7241: # Rest of the restrictions depend on selected course
                   7242: #
                   7243: 
1.620     albertel 7244:     unless ($env{'request.course.id'}) {
1.766     albertel 7245: 	if ($thisallowed eq 'A') {
                   7246: 	    return 'A';
1.814     raeburn  7247:         } elsif ($thisallowed eq 'B') {
                   7248:             return 'B';
1.766     albertel 7249: 	} else {
                   7250: 	    return '1';
                   7251: 	}
1.52      www      7252:     }
1.29      www      7253: 
1.52      www      7254: #
                   7255: # Now user is definitely in a course
                   7256: #
1.53      www      7257: 
                   7258: 
                   7259: # Course preferences
                   7260: 
                   7261:    if ($thisallowed=~/C/) {
1.620     albertel 7262:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7263:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7264:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7265: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7266: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7267: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7268: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7269: 			$env{'request.course.id'});
                   7270: 	   }
1.237     www      7271:            return '';
                   7272:        }
                   7273: 
1.620     albertel 7274:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7275: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7276: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7277: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7278: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7279: 			$env{'request.course.id'});
                   7280: 	   }
1.54      www      7281:            return '';
                   7282:        }
1.53      www      7283:    }
                   7284: 
                   7285: # Resource preferences
                   7286: 
                   7287:    if ($thisallowed=~/R/) {
1.620     albertel 7288:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7289:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7290: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7291: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7292: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7293: 	   }
                   7294: 	   return '';
1.54      www      7295:        }
1.53      www      7296:    }
1.30      www      7297: 
1.246     www      7298: # Restricted by state or randomout?
1.30      www      7299: 
1.52      www      7300:    if ($thisallowed=~/X/) {
1.620     albertel 7301:       if ($env{'acc.randomout'}) {
1.579     albertel 7302: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7303:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7304:             return ''; 
                   7305:          }
1.247     www      7306:       }
                   7307:       if (&condval($statecond)) {
1.52      www      7308: 	 return '2';
                   7309:       } else {
                   7310:          return '';
                   7311:       }
                   7312:    }
1.30      www      7313: 
1.766     albertel 7314:     if ($thisallowed eq 'A') {
                   7315: 	return 'A';
1.814     raeburn  7316:     } elsif ($thisallowed eq 'B') {
                   7317:         return 'B';
1.766     albertel 7318:     }
1.52      www      7319:    return 'F';
1.232     www      7320: }
1.1162    raeburn  7321: 
1.1192    raeburn  7322: # ------------------------------------------- Check construction space access
                   7323: 
                   7324: sub constructaccess {
                   7325:     my ($url,$setpriv)=@_;
                   7326: 
                   7327: # We do not allow editing of previous versions of files
                   7328:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7329: 
                   7330: # Get username and domain from URL
                   7331:     my ($ownername,$ownerdomain,$ownerhome);
                   7332: 
                   7333:     ($ownerdomain,$ownername) =
1.1297    damieng  7334:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7335: 
                   7336: # The URL does not really point to any authorspace, forget it
                   7337:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7338: 
                   7339: # Now we need to see if the user has access to the authorspace of
                   7340: # $ownername at $ownerdomain
                   7341: 
                   7342:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7343: # Real author for this?
                   7344:        $ownerhome = $env{'user.home'};
                   7345:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7346:           return ($ownername,$ownerdomain,$ownerhome);
                   7347:        }
                   7348:     } else {
                   7349: # Co-author for this?
                   7350:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7351:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7352:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7353:             return ($ownername,$ownerdomain,$ownerhome);
                   7354:         }
                   7355:     }
                   7356: 
                   7357: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7358: # we might as well leave
                   7359:    unless ($setpriv) { return ''; }
                   7360: 
                   7361: # Backdoor access?
                   7362:     my $allowed=&allowed('eco',$ownerdomain);
                   7363: # Nope
                   7364:     unless ($allowed) { return ''; }
                   7365: # Looks like we may have access, but could be locked by the owner of the construction space
                   7366:     if ($allowed eq 'U') {
                   7367:         my %blocked=&get('environment',['domcoord.author'],
                   7368:                          $ownerdomain,$ownername);
                   7369: # Is blocked by owner
                   7370:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7371:     }
                   7372:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7373: # Grant temporary access
                   7374:         my $then=$env{'user.login.time'};
1.1209    raeburn  7375:         my $update=$env{'user.update.time'};
1.1192    raeburn  7376:         if (!$update) { $update = $then; }
                   7377:         my $refresh=$env{'user.refresh.time'};
                   7378:         if (!$refresh) { $refresh = $update; }
                   7379:         my $now = time;
                   7380:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7381:                            $now,'ca','constructaccess');
                   7382:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7383:         return($ownername,$ownerdomain,$ownerhome);
                   7384:     }
                   7385: # No business here
                   7386:     return '';
                   7387: }
                   7388: 
1.1282    raeburn  7389: # ----------------------------------------------------------- Content Blocking
                   7390: 
                   7391: {
                   7392: # Caches for faster Course Contents display where content blocking
                   7393: # is in operation (i.e., interval param set) for timed quiz.
                   7394: #
                   7395: # User for whom data are being temporarily cached.
                   7396: my $cacheduser='';
                   7397: # Cached blockers for this user (a hash of blocking items). 
                   7398: my %cachedblockers=();
                   7399: # When the data were last cached.
                   7400: my $cachedlast='';
                   7401: 
                   7402: sub load_all_blockers {
                   7403:     my ($uname,$udom,$blocks)=@_;
                   7404:     if (($uname ne '') && ($udom ne '')) { 
                   7405:         if (($cacheduser eq $uname.':'.$udom) &&
                   7406:             (abs($cachedlast-time)<5)) {
                   7407:             return;
                   7408:         }
                   7409:     }
                   7410:     $cachedlast=time;
                   7411:     $cacheduser=$uname.':'.$udom;
                   7412:     %cachedblockers = &get_commblock_resources($blocks);
                   7413: }
                   7414: 
1.1162    raeburn  7415: sub get_comm_blocks {
                   7416:     my ($cdom,$cnum) = @_;
                   7417:     if ($cdom eq '' || $cnum eq '') {
                   7418:         return unless ($env{'request.course.id'});
                   7419:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7420:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7421:     }
                   7422:     my %commblocks;
                   7423:     my $hashid=$cdom.'_'.$cnum;
                   7424:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7425:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7426:         %commblocks = %{$blocksref};
                   7427:     } else {
                   7428:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7429:         my $cachetime = 600;
                   7430:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7431:     }
                   7432:     return %commblocks;
                   7433: }
                   7434: 
1.1282    raeburn  7435: sub get_commblock_resources {
                   7436:     my ($blocks) = @_;
                   7437:     my %blockers = ();
                   7438:     return %blockers unless ($env{'request.course.id'});
                   7439:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7440:     my %commblocks;
                   7441:     if (ref($blocks) eq 'HASH') {
                   7442:         %commblocks = %{$blocks};
                   7443:     } else {
                   7444:         %commblocks = &get_comm_blocks();
                   7445:     }
1.1282    raeburn  7446:     return %blockers unless (keys(%commblocks) > 0); 
                   7447:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7448:     return %blockers unless (ref($navmap));
1.1162    raeburn  7449:     my $now = time;
                   7450:     foreach my $block (keys(%commblocks)) {
                   7451:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7452:             my ($start,$end) = ($1,$2);
                   7453:             if ($start <= $now && $end >= $now) {
                   7454:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7455:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7456:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7457:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7458:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7459:                             }
                   7460:                         }
                   7461:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7462:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7463:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7464:                             }
                   7465:                         }
                   7466:                     }
                   7467:                 }
                   7468:             }
                   7469:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7470:             my $item = $1;
1.1163    raeburn  7471:             my @to_test;
1.1162    raeburn  7472:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7473:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7474:                     my @interval;
                   7475:                     my $type = 'map';
                   7476:                     if ($item eq 'course') {
                   7477:                         $type = 'course';
                   7478:                         @interval=&EXT("resource.0.interval");
                   7479:                     } else {
                   7480:                         if ($item =~ /___\d+___/) {
                   7481:                             $type = 'resource';
                   7482:                             @interval=&EXT("resource.0.interval",$item);
                   7483:                             if (ref($navmap)) {                        
                   7484:                                 my $res = $navmap->getBySymb($item); 
                   7485:                                 push(@to_test,$res);
                   7486:                             }
1.1162    raeburn  7487:                         } else {
1.1282    raeburn  7488:                             my $mapsymb = &symbread($item,1);
                   7489:                             if ($mapsymb) {
                   7490:                                 if (ref($navmap)) {
                   7491:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7492:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7493:                                     foreach my $res (@to_test) {
                   7494:                                         my $symb = $res->symb();
                   7495:                                         next if ($symb eq $mapsymb);
                   7496:                                         if ($symb ne '') {
                   7497:                                             @interval=&EXT("resource.0.interval",$symb);
                   7498:                                             if ($interval[1] eq 'map') {
                   7499:                                                 last;
1.1162    raeburn  7500:                                             }
                   7501:                                         }
                   7502:                                     }
                   7503:                                 }
                   7504:                             }
                   7505:                         }
1.1282    raeburn  7506:                     }
1.1292    raeburn  7507:                     if ($interval[0] =~ /^\d+/) {
                   7508:                         my ($timelimit) = split(/_/,$interval[0]);
1.1282    raeburn  7509:                         my $first_access;
                   7510:                         if ($type eq 'resource') {
                   7511:                             $first_access=&get_first_access($interval[1],$item);
                   7512:                         } elsif ($type eq 'map') {
                   7513:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7514:                         } else {
                   7515:                             $first_access=&get_first_access($interval[1]);
                   7516:                         }
                   7517:                         if ($first_access) {
1.1292    raeburn  7518:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7519:                             if ($timesup > $now) {
                   7520:                                 my $activeblock;
                   7521:                                 foreach my $res (@to_test) {
1.1283    raeburn  7522:                                     if ($res->answerable()) {
1.1282    raeburn  7523:                                         $activeblock = 1;
                   7524:                                         last;
                   7525:                                     }
                   7526:                                 }
                   7527:                                 if ($activeblock) {
                   7528:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7529:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7530:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7531:                                          }
                   7532:                                     }
                   7533:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7534:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7535:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7536:                                         }
1.1162    raeburn  7537:                                     }
                   7538:                                 }
                   7539:                             }
                   7540:                         }
                   7541:                     }
                   7542:                 }
                   7543:             }
                   7544:         }
                   7545:     }
1.1282    raeburn  7546:     return %blockers;
1.1162    raeburn  7547: }
                   7548: 
1.1282    raeburn  7549: sub has_comm_blocking {
                   7550:     my ($priv,$symb,$uri,$blocks) = @_;
                   7551:     my @blockers;
                   7552:     return unless ($env{'request.course.id'});
                   7553:     return unless ($priv eq 'bre');
                   7554:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7555:     return if ($env{'request.state'} eq 'construct');
                   7556:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7557:     return unless (keys(%cachedblockers) > 0);
                   7558:     my (%possibles,@symbs);
                   7559:     if (!$symb) {
                   7560:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7561:     }
1.1282    raeburn  7562:     if ($symb) {
                   7563:         @symbs = ($symb);
                   7564:     } elsif (keys(%possibles)) { 
                   7565:         @symbs = keys(%possibles);
                   7566:     }
                   7567:     my $noblock;
                   7568:     foreach my $symb (@symbs) {
                   7569:         last if ($noblock);
                   7570:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7571:         foreach my $block (keys(%cachedblockers)) {
                   7572:             if ($block =~ /^firstaccess____(.+)$/) {
                   7573:                 my $item = $1;
                   7574:                 if (($item eq $map) || ($item eq $symb)) {
                   7575:                     $noblock = 1;
                   7576:                     last;
                   7577:                 }
                   7578:             }
                   7579:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7580:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7581:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7582:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7583:                             push(@blockers,$block);
                   7584:                         }
                   7585:                     }
                   7586:                 }
1.1162    raeburn  7587:             }
1.1282    raeburn  7588:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7589:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7590:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7591:                         push(@blockers,$block);
                   7592:                     }
                   7593:                 }
1.1162    raeburn  7594:             }
                   7595:         }
                   7596:     }
1.1282    raeburn  7597:     return if ($noblock);
                   7598:     return @blockers;
                   7599: }
1.1162    raeburn  7600: }
                   7601: 
1.1282    raeburn  7602: # -------------------------------- Deversion and split uri into path an filename   
                   7603: 
1.1133    foxr     7604: #
1.1282    raeburn  7605: #   Removes the version from a URI and
1.1133    foxr     7606: #   splits it in to its filename and path to the filename.
                   7607: #   Seems like File::Basename could have done this more clearly.
                   7608: #   Parameters:
                   7609: #      $uri   - input URI
                   7610: #   Returns:
                   7611: #     Two element list consisting of 
                   7612: #     $pathname  - the URI up to and excluding the trailing /
                   7613: #     $filename  - The part of the URI following the last /
                   7614: #  NOTE:
                   7615: #    Another realization of this is simply:
                   7616: #    use File::Basename;
                   7617: #    ...
                   7618: #    $uri = shift;
                   7619: #    $filename = basename($uri);
                   7620: #    $path     = dirname($uri);
                   7621: #    return ($filename, $path);
                   7622: #
                   7623: #     The implementation below is probably faster however.
                   7624: #
1.710     albertel 7625: sub split_uri_for_cond {
                   7626:     my $uri=&deversion(&declutter(shift));
                   7627:     my @uriparts=split(/\//,$uri);
                   7628:     my $filename=pop(@uriparts);
                   7629:     my $pathname=join('/',@uriparts);
                   7630:     return ($pathname,$filename);
                   7631: }
1.232     www      7632: # --------------------------------------------------- Is a resource on the map?
                   7633: 
                   7634: sub is_on_map {
1.710     albertel 7635:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7636:     #Trying to find the conditional for the file
1.620     albertel 7637:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7638: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7639:     if ($match) {
1.289     bowersj2 7640: 	return (1,$1);
                   7641:     } else {
1.434     www      7642: 	return (0,0);
1.289     bowersj2 7643:     }
1.12      www      7644: }
                   7645: 
1.427     www      7646: # --------------------------------------------------------- Get symb from alias
                   7647: 
                   7648: sub get_symb_from_alias {
                   7649:     my $symb=shift;
                   7650:     my ($map,$resid,$url)=&decode_symb($symb);
                   7651: # Already is a symb
                   7652:     if ($url) { return $symb; }
                   7653: # Must be an alias
                   7654:     my $aliassymb='';
                   7655:     my %bighash;
1.620     albertel 7656:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7657:                             &GDBM_READER(),0640)) {
                   7658:         my $rid=$bighash{'mapalias_'.$symb};
                   7659: 	if ($rid) {
                   7660: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7661: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7662: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7663: 	}
                   7664:         untie %bighash;
                   7665:     }
                   7666:     return $aliassymb;
                   7667: }
                   7668: 
1.12      www      7669: # ----------------------------------------------------------------- Define Role
                   7670: 
                   7671: sub definerole {
                   7672:   if (allowed('mcr','/')) {
                   7673:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7674:     foreach my $role (split(':',$sysrole)) {
                   7675: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7676:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7677:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7678: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7679:                return "refused:s:$crole&$cqual"; 
                   7680:             }
                   7681:         }
1.191     harris41 7682:     }
1.800     albertel 7683:     foreach my $role (split(':',$domrole)) {
                   7684: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7685:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7686:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7687: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7688:                return "refused:d:$crole&$cqual"; 
                   7689:             }
                   7690:         }
1.191     harris41 7691:     }
1.800     albertel 7692:     foreach my $role (split(':',$courole)) {
                   7693: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7694:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7695:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7696: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7697:                return "refused:c:$crole&$cqual"; 
                   7698:             }
                   7699:         }
1.191     harris41 7700:     }
1.620     albertel 7701:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7702:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7703: 	        "rolesdef_$rolename=".
                   7704:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7705:     return reply($command,$env{'user.home'});
1.12      www      7706:   } else {
                   7707:     return 'refused';
                   7708:   }
1.105     harris41 7709: }
                   7710: 
                   7711: # ---------------- Make a metadata query against the network of library servers
                   7712: 
                   7713: sub metadata_query {
1.1237    raeburn  7714:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7715:     my %rhash;
1.845     albertel 7716:     my %libserv = &all_library();
1.244     matthew  7717:     my @server_list = (defined($server_array) ? @$server_array
                   7718:                                               : keys(%libserv) );
                   7719:     for my $server (@server_list) {
1.1237    raeburn  7720:         my $domains = ''; 
                   7721:         if (ref($domains_hash) eq 'HASH') {
                   7722:             $domains = $domains_hash->{$server}; 
                   7723:         }
1.118     harris41 7724: 	unless ($custom or $customshow) {
1.1237    raeburn  7725: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7726: 	    $rhash{$server}=$reply;
                   7727: 	}
                   7728: 	else {
                   7729: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7730: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7731: 			     $server);
                   7732: 	    $rhash{$server}=$reply;
                   7733: 	}
1.112     harris41 7734:     }
1.118     harris41 7735:     return \%rhash;
1.240     www      7736: }
                   7737: 
                   7738: # ----------------------------------------- Send log queries and wait for reply
                   7739: 
                   7740: sub log_query {
                   7741:     my ($uname,$udom,$query,%filters)=@_;
                   7742:     my $uhome=&homeserver($uname,$udom);
                   7743:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7744:     my $uhost=&hostname($uhome);
1.800     albertel 7745:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7746:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7747:                        $uhome);
1.479     albertel 7748:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7749:     return get_query_reply($queryid);
                   7750: }
                   7751: 
1.818     raeburn  7752: # -------------------------- Update MySQL table for portfolio file
                   7753: 
                   7754: sub update_portfolio_table {
1.821     raeburn  7755:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7756:     if ($group ne '') {
                   7757:         $file_name =~s /^\Q$group\E//;
                   7758:     }
1.818     raeburn  7759:     my $homeserver = &homeserver($uname,$udom);
                   7760:     my $queryid=
1.821     raeburn  7761:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7762:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7763:     my $reply = &get_query_reply($queryid);
                   7764:     return $reply;
                   7765: }
                   7766: 
1.899     raeburn  7767: # -------------------------- Update MySQL allusers table
                   7768: 
                   7769: sub update_allusers_table {
                   7770:     my ($uname,$udom,$names) = @_;
                   7771:     my $homeserver = &homeserver($uname,$udom);
                   7772:     my $queryid=
                   7773:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7774:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7775:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7776:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7777:                'generation='.&escape($names->{'generation'}).'%%'.
                   7778:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7779:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7780:     return;
1.899     raeburn  7781: }
                   7782: 
1.508     raeburn  7783: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7784: 
                   7785: sub fetch_enrollment_query {
1.511     raeburn  7786:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7787:     my $homeserver;
1.547     raeburn  7788:     my $maxtries = 1;
1.508     raeburn  7789:     if ($context eq 'automated') {
                   7790:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7791:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7792:     } else {
                   7793:         $homeserver = &homeserver($cnum,$dom);
                   7794:     }
1.838     albertel 7795:     my $host=&hostname($homeserver);
1.506     raeburn  7796:     my $cmd = '';
1.1000    raeburn  7797:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7798:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7799:     }
                   7800:     $cmd =~ s/%%$//;
                   7801:     $cmd = &escape($cmd);
                   7802:     my $query = 'fetchenrollment';
1.620     albertel 7803:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7804:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7805:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7806:         return 'error: '.$queryid;
                   7807:     }
1.506     raeburn  7808:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7809:     my $tries = 1;
                   7810:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7811:         $reply = &get_query_reply($queryid);
                   7812:         $tries ++;
                   7813:     }
1.526     raeburn  7814:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7815:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7816:     } else {
1.901     albertel 7817:         my @responses = split(/:/,$reply);
1.515     raeburn  7818:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7819:             foreach my $line (@responses) {
                   7820:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7821:                 $$replyref{$key} = $value;
                   7822:             }
                   7823:         } else {
1.1117    foxr     7824:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7825:             foreach my $line (@responses) {
                   7826:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7827:                 $$replyref{$key} = $value;
                   7828:                 if ($value > 0) {
1.800     albertel 7829:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7830:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7831:                         my $destname = $pathname.'/'.$filename;
                   7832:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7833:                         if ($xml_classlist =~ /^error/) {
                   7834:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7835:                         } else {
1.506     raeburn  7836:                             if ( open(FILE,">$destname") ) {
                   7837:                                 print FILE &unescape($xml_classlist);
                   7838:                                 close(FILE);
1.526     raeburn  7839:                             } else {
                   7840:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7841:                             }
                   7842:                         }
                   7843:                     }
                   7844:                 }
                   7845:             }
                   7846:         }
                   7847:         return 'ok';
                   7848:     }
                   7849:     return 'error';
                   7850: }
                   7851: 
1.242     www      7852: sub get_query_reply {
                   7853:     my $queryid=shift;
1.1117    foxr     7854:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7855:     my $reply='';
                   7856:     for (1..100) {
1.1289    damieng  7857: 	sleep(0.2);
1.240     www      7858:         if (-e $replyfile.'.end') {
1.448     albertel 7859: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7860: 		$reply = join('',<$fh>);
                   7861: 		close($fh);
1.240     www      7862: 	   } else { return 'error: reply_file_error'; }
1.242     www      7863:            return &unescape($reply);
                   7864: 	}
1.240     www      7865:     }
1.242     www      7866:     return 'timeout:'.$queryid;
1.240     www      7867: }
                   7868: 
                   7869: sub courselog_query {
1.241     www      7870: #
                   7871: # possible filters:
                   7872: # url: url or symb
                   7873: # username
                   7874: # domain
                   7875: # action: view, submit, grade
                   7876: # start: timestamp
                   7877: # end: timestamp
                   7878: #
1.240     www      7879:     my (%filters)=@_;
1.620     albertel 7880:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7881:     if ($filters{'url'}) {
                   7882: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7883:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7884:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7885:     }
1.620     albertel 7886:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7887:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7888:     return &log_query($cname,$cdom,'courselog',%filters);
                   7889: }
                   7890: 
                   7891: sub userlog_query {
1.858     raeburn  7892: #
                   7893: # possible filters:
                   7894: # action: log check role
                   7895: # start: timestamp
                   7896: # end: timestamp
                   7897: #
1.240     www      7898:     my ($uname,$udom,%filters)=@_;
                   7899:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7900: }
                   7901: 
1.506     raeburn  7902: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7903: 
                   7904: sub auto_run {
1.508     raeburn  7905:     my ($cnum,$cdom) = @_;
1.876     raeburn  7906:     my $response = 0;
                   7907:     my $settings;
                   7908:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7909:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7910:         $settings = $domconfig{'autoenroll'};
                   7911:         if ($settings->{'run'} eq '1') {
                   7912:             $response = 1;
                   7913:         }
                   7914:     } else {
1.934     raeburn  7915:         my $homeserver;
                   7916:         if (&is_course($cdom,$cnum)) {
                   7917:             $homeserver = &homeserver($cnum,$cdom);
                   7918:         } else {
                   7919:             $homeserver = &domain($cdom,'primary');
                   7920:         }
                   7921:         if ($homeserver ne 'no_host') {
                   7922:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7923:         }
1.876     raeburn  7924:     }
1.506     raeburn  7925:     return $response;
                   7926: }
1.776     albertel 7927: 
1.506     raeburn  7928: sub auto_get_sections {
1.508     raeburn  7929:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7930:     my $homeserver;
                   7931:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7932:         $homeserver = &homeserver($cnum,$cdom);
                   7933:     }
                   7934:     if (!defined($homeserver)) { 
                   7935:         if ($cdom =~ /^$match_domain$/) {
                   7936:             $homeserver = &domain($cdom,'primary');
                   7937:         }
                   7938:     }
                   7939:     my @secs;
                   7940:     if (defined($homeserver)) {
                   7941:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7942:         unless ($response eq 'refused') {
                   7943:             @secs = split(/:/,$response);
                   7944:         }
1.506     raeburn  7945:     }
                   7946:     return @secs;
                   7947: }
1.776     albertel 7948: 
1.506     raeburn  7949: sub auto_new_course {
1.1099    raeburn  7950:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7951:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7952:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7953:     return $response;
                   7954: }
1.776     albertel 7955: 
1.506     raeburn  7956: sub auto_validate_courseID {
1.508     raeburn  7957:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7958:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7959:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7960:     return $response;
                   7961: }
1.776     albertel 7962: 
1.1007    raeburn  7963: sub auto_validate_instcode {
1.1020    raeburn  7964:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7965:     my ($homeserver,$response);
                   7966:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7967:         $homeserver = &homeserver($cnum,$cdom);
                   7968:     }
                   7969:     if (!defined($homeserver)) {
                   7970:         if ($cdom =~ /^$match_domain$/) {
                   7971:             $homeserver = &domain($cdom,'primary');
                   7972:         }
                   7973:     }
1.1065    raeburn  7974:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7975:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7976:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7977:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7978: }
                   7979: 
1.506     raeburn  7980: sub auto_create_password {
1.873     raeburn  7981:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7982:     my ($homeserver,$response);
1.506     raeburn  7983:     my $create_passwd = 0;
                   7984:     my $authchk = '';
1.873     raeburn  7985:     if ($udom =~ /^$match_domain$/) {
                   7986:         $homeserver = &domain($udom,'primary');
                   7987:     }
                   7988:     if ($homeserver eq '') {
                   7989:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7990:             $homeserver = &homeserver($cnum,$cdom);
                   7991:         }
                   7992:     }
                   7993:     if ($homeserver eq '') {
                   7994:         $authchk = 'nodomain';
1.506     raeburn  7995:     } else {
1.873     raeburn  7996:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7997:         if ($response eq 'refused') {
                   7998:             $authchk = 'refused';
                   7999:         } else {
1.901     albertel 8000:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8001:         }
1.506     raeburn  8002:     }
                   8003:     return ($authparam,$create_passwd,$authchk);
                   8004: }
                   8005: 
1.706     raeburn  8006: sub auto_photo_permission {
                   8007:     my ($cnum,$cdom,$students) = @_;
                   8008:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8009:     my ($outcome,$perm_reqd,$conditions) = 
                   8010: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8011:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8012: 	return (undef,undef);
                   8013:     }
1.706     raeburn  8014:     return ($outcome,$perm_reqd,$conditions);
                   8015: }
                   8016: 
                   8017: sub auto_checkphotos {
                   8018:     my ($uname,$udom,$pid) = @_;
                   8019:     my $homeserver = &homeserver($uname,$udom);
                   8020:     my ($result,$resulttype);
                   8021:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8022: 				   &escape($uname).':'.&escape($pid),
                   8023: 				   $homeserver));
1.709     albertel 8024:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8025: 	return (undef,undef);
                   8026:     }
1.706     raeburn  8027:     if ($outcome) {
                   8028:         ($result,$resulttype) = split(/:/,$outcome);
                   8029:     } 
                   8030:     return ($result,$resulttype);
                   8031: }
                   8032: 
                   8033: sub auto_photochoice {
                   8034:     my ($cnum,$cdom) = @_;
                   8035:     my $homeserver = &homeserver($cnum,$cdom);
                   8036:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8037: 						       &escape($cdom),
                   8038: 						       $homeserver)));
1.709     albertel 8039:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8040: 	return (undef,undef);
                   8041:     }
1.706     raeburn  8042:     return ($update,$comment);
                   8043: }
                   8044: 
                   8045: sub auto_photoupdate {
                   8046:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8047:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8048:     my $host=&hostname($homeserver);
1.706     raeburn  8049:     my $cmd = '';
                   8050:     my $maxtries = 1;
1.800     albertel 8051:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8052:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8053:     }
                   8054:     $cmd =~ s/%%$//;
                   8055:     $cmd = &escape($cmd);
                   8056:     my $query = 'institutionalphotos';
                   8057:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8058:     unless ($queryid=~/^\Q$host\E\_/) {
                   8059:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8060:         return 'error: '.$queryid;
                   8061:     }
                   8062:     my $reply = &get_query_reply($queryid);
                   8063:     my $tries = 1;
                   8064:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8065:         $reply = &get_query_reply($queryid);
                   8066:         $tries ++;
                   8067:     }
                   8068:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8069:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8070:     } else {
                   8071:         my @responses = split(/:/,$reply);
                   8072:         my $outcome = shift(@responses); 
                   8073:         foreach my $item (@responses) {
                   8074:             my ($key,$value) = split(/=/,$item);
                   8075:             $$photo{$key} = $value;
                   8076:         }
                   8077:         return $outcome;
                   8078:     }
                   8079:     return 'error';
                   8080: }
                   8081: 
1.521     raeburn  8082: sub auto_instcode_format {
1.793     albertel 8083:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8084: 	$cat_order) = @_;
1.521     raeburn  8085:     my $courses = '';
1.772     raeburn  8086:     my @homeservers;
1.521     raeburn  8087:     if ($caller eq 'global') {
1.841     albertel 8088: 	my %servers = &get_servers($codedom,'library');
                   8089: 	foreach my $tryserver (keys(%servers)) {
                   8090: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8091: 		push(@homeservers,$tryserver);
                   8092: 	    }
1.584     raeburn  8093:         }
1.1022    raeburn  8094:     } elsif ($caller eq 'requests') {
                   8095:         if ($codedom =~ /^$match_domain$/) {
                   8096:             my $chome = &domain($codedom,'primary');
                   8097:             unless ($chome eq 'no_host') {
                   8098:                 push(@homeservers,$chome);
                   8099:             }
                   8100:         }
1.521     raeburn  8101:     } else {
1.772     raeburn  8102:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8103:     }
1.793     albertel 8104:     foreach my $code (keys(%{$instcodes})) {
                   8105:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8106:     }
                   8107:     chop($courses);
1.772     raeburn  8108:     my $ok_response = 0;
                   8109:     my $response;
                   8110:     while (@homeservers > 0 && $ok_response == 0) {
                   8111:         my $server = shift(@homeservers); 
                   8112:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8113:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8114:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8115: 		split(/:/,$response);
1.772     raeburn  8116:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8117:             push(@{$codetitles},&str2array($codetitles_str));
                   8118:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8119:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8120:             $ok_response = 1;
                   8121:         }
                   8122:     }
                   8123:     if ($ok_response) {
1.521     raeburn  8124:         return 'ok';
1.772     raeburn  8125:     } else {
                   8126:         return $response;
1.521     raeburn  8127:     }
                   8128: }
                   8129: 
1.792     raeburn  8130: sub auto_instcode_defaults {
                   8131:     my ($domain,$returnhash,$code_order) = @_;
                   8132:     my @homeservers;
1.841     albertel 8133: 
                   8134:     my %servers = &get_servers($domain,'library');
                   8135:     foreach my $tryserver (keys(%servers)) {
                   8136: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8137: 	    push(@homeservers,$tryserver);
                   8138: 	}
1.792     raeburn  8139:     }
1.841     albertel 8140: 
1.792     raeburn  8141:     my $response;
1.841     albertel 8142:     foreach my $server (@homeservers) {
1.792     raeburn  8143:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8144:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8145: 	
                   8146: 	foreach my $pair (split(/\&/,$response)) {
                   8147: 	    my ($name,$value)=split(/\=/,$pair);
                   8148: 	    if ($name eq 'code_order') {
                   8149: 		@{$code_order} = split(/\&/,&unescape($value));
                   8150: 	    } else {
                   8151: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8152: 	    }
                   8153: 	}
                   8154: 	return 'ok';
1.792     raeburn  8155:     }
1.841     albertel 8156: 
                   8157:     return $response;
1.1003    raeburn  8158: }
                   8159: 
                   8160: sub auto_possible_instcodes {
1.1007    raeburn  8161:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8162:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8163:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8164:         return;
                   8165:     }
1.1003    raeburn  8166:     my (@homeservers,$uhome);
                   8167:     if (defined(&domain($domain,'primary'))) {
                   8168:         $uhome=&domain($domain,'primary');
                   8169:         push(@homeservers,&domain($domain,'primary'));
                   8170:     } else {
                   8171:         my %servers = &get_servers($domain,'library');
                   8172:         foreach my $tryserver (keys(%servers)) {
                   8173:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8174:                 push(@homeservers,$tryserver);
                   8175:             }
                   8176:         }
                   8177:     }
                   8178:     my $response;
                   8179:     foreach my $server (@homeservers) {
                   8180:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8181:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8182:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8183:             split(':',$response);
                   8184:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8185:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8186:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8187:             my ($name,$value)=split('=',$item);
                   8188:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8189:         }
                   8190:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8191:             my ($name,$value)=split('=',$item);
                   8192:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8193:         }
                   8194:         return 'ok';
                   8195:     }
                   8196:     return $response;
                   8197: }
1.792     raeburn  8198: 
1.1010    raeburn  8199: sub auto_courserequest_checks {
                   8200:     my ($dom) = @_;
1.1020    raeburn  8201:     my ($homeserver,%validations);
                   8202:     if ($dom =~ /^$match_domain$/) {
                   8203:         $homeserver = &domain($dom,'primary');
                   8204:     }
                   8205:     unless ($homeserver eq 'no_host') {
                   8206:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8207:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8208:             my @items = split(/&/,$response);
                   8209:             foreach my $item (@items) {
                   8210:                 my ($key,$value) = split('=',$item);
                   8211:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8212:             }
                   8213:         }
                   8214:     }
1.1010    raeburn  8215:     return %validations; 
                   8216: }
                   8217: 
1.1020    raeburn  8218: sub auto_courserequest_validation {
1.1255    raeburn  8219:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8220:     my ($homeserver,$response);
                   8221:     if ($dom =~ /^$match_domain$/) {
                   8222:         $homeserver = &domain($dom,'primary');
                   8223:     }
1.1255    raeburn  8224:     unless ($homeserver eq 'no_host') {
                   8225:         my $customdata;
                   8226:         if (ref($custominfo) eq 'HASH') {
                   8227:             $customdata = &freeze_escape($custominfo);
                   8228:         }
1.1020    raeburn  8229:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8230:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8231:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8232:                                     $customdata,$homeserver));
1.1020    raeburn  8233:     }
                   8234:     return $response;
                   8235: }
                   8236: 
1.777     albertel 8237: sub auto_validate_class_sec {
1.918     raeburn  8238:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8239:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8240:     my $ownerlist;
                   8241:     if (ref($owners) eq 'ARRAY') {
                   8242:         $ownerlist = join(',',@{$owners});
                   8243:     } else {
                   8244:         $ownerlist = $owners;
                   8245:     }
1.773     raeburn  8246:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8247:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8248:     return $response;
                   8249: }
                   8250: 
1.1248    raeburn  8251: sub auto_crsreq_update {
                   8252:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8253:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8254:     my ($homeserver,%crsreqresponse);
                   8255:     if ($cdom =~ /^$match_domain$/) {
                   8256:         $homeserver = &domain($cdom,'primary');
                   8257:     }
                   8258:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8259:         my $info;
                   8260:         if (ref($inbound) eq 'HASH') {
                   8261:             $info = &freeze_escape($inbound);
                   8262:         }
                   8263:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8264:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8265:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8266:                             &escape($title).':'.&escape($code).':'.
                   8267:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8268:                             $homeserver);
1.1248    raeburn  8269:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8270:             my @items = split(/&/,$response);
                   8271:             foreach my $item (@items) {
                   8272:                 my ($key,$value) = split('=',$item);
                   8273:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8274:             }
                   8275:         }
                   8276:     }
                   8277:     return \%crsreqresponse;
                   8278: }
                   8279: 
1.1287    raeburn  8280: sub check_instcode_cloning {
                   8281:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8282:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8283:         return;
                   8284:     }
                   8285:     my $canclone;
                   8286:     if (@{$code_order} > 0) {
                   8287:         my $instcoderegexp ='^';
                   8288:         my @clonecodes = split(/\&/,$cloner);
                   8289:         foreach my $item (@{$code_order}) {
                   8290:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8291:                 foreach my $pair (@clonecodes) {
                   8292:                     my ($key,$val) = split(/\=/,$pair,2);
                   8293:                     $val = &unescape($val);
                   8294:                     if ($key eq $item) {
                   8295:                         $instcoderegexp .= '('.$val.')';
                   8296:                         last;
                   8297:                     }
                   8298:                 }
                   8299:             } else {
                   8300:                 $instcoderegexp .= $codedefaults->{$item};
                   8301:             }
                   8302:         }
                   8303:         $instcoderegexp .= '$';
                   8304:         my (@from,@to);
                   8305:         eval {
                   8306:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8307:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8308:         };
                   8309:         if ((@from > 0) && (@to > 0)) {
                   8310:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8311:             if (!@diffs) {
                   8312:                 $canclone = 1;
                   8313:             }
                   8314:         }
                   8315:     }
                   8316:     return $canclone;
                   8317: }
                   8318: 
                   8319: sub default_instcode_cloning {
                   8320:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8321:     my (%codedefaults,@code_order,$canclone);
                   8322:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8323:         %codedefaults = %{$codedefaultsref};
                   8324:         @code_order = @{$codeorderref};
                   8325:     } elsif ($clonedom) {
                   8326:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8327:     }
                   8328:     if (($domdefclone) && (@code_order)) {
                   8329:         my @clonecodes = split(/\+/,$domdefclone);
                   8330:         my $instcoderegexp ='^';
                   8331:         foreach my $item (@code_order) {
                   8332:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8333:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8334:             } else {
                   8335:                 $instcoderegexp .= $codedefaults{$item};
                   8336:             }
                   8337:         }
                   8338:         $instcoderegexp .= '$';
                   8339:         my (@from,@to);
                   8340:         eval {
                   8341:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8342:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8343:         };
                   8344:         if ((@from > 0) && (@to > 0)) {
                   8345:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8346:             if (!@diffs) {
                   8347:                 $canclone = 1;
                   8348:             }
                   8349:         }
                   8350:     }
                   8351:     return $canclone;
                   8352: }
                   8353: 
1.679     raeburn  8354: # ------------------------------------------------------- Course Group routines
                   8355: 
                   8356: sub get_coursegroups {
1.809     raeburn  8357:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8358:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8359: }
                   8360: 
1.679     raeburn  8361: sub modify_coursegroup {
                   8362:     my ($cdom,$cnum,$groupsettings) = @_;
                   8363:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8364: }
                   8365: 
1.809     raeburn  8366: sub toggle_coursegroup_status {
                   8367:     my ($cdom,$cnum,$group,$action) = @_;
                   8368:     my ($from_namespace,$to_namespace);
                   8369:     if ($action eq 'delete') {
                   8370:         $from_namespace = 'coursegroups';
                   8371:         $to_namespace = 'deleted_groups';
                   8372:     } else {
                   8373:         $from_namespace = 'deleted_groups';
                   8374:         $to_namespace = 'coursegroups';
                   8375:     }
                   8376:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8377:     if (my $tmp = &error(%curr_group)) {
                   8378:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8379:         return ('read error',$tmp);
                   8380:     } else {
                   8381:         my %savedsettings = %curr_group; 
1.809     raeburn  8382:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8383:         my $deloutcome;
                   8384:         if ($result eq 'ok') {
1.809     raeburn  8385:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8386:         } else {
                   8387:             return ('write error',$result);
                   8388:         }
                   8389:         if ($deloutcome eq 'ok') {
                   8390:             return 'ok';
                   8391:         } else {
                   8392:             return ('delete error',$deloutcome);
                   8393:         }
                   8394:     }
                   8395: }
                   8396: 
1.679     raeburn  8397: sub modify_group_roles {
1.957     raeburn  8398:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8399:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8400:     my $role = 'gr/'.&escape($userprivs);
                   8401:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8402:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8403:     if ($result eq 'ok') {
                   8404:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8405:     }
1.679     raeburn  8406:     return $result;
                   8407: }
                   8408: 
                   8409: sub modify_coursegroup_membership {
                   8410:     my ($cdom,$cnum,$membership) = @_;
                   8411:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8412:     return $result;
                   8413: }
                   8414: 
1.682     raeburn  8415: sub get_active_groups {
                   8416:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8417:     my $now = time;
                   8418:     my %groups = ();
                   8419:     foreach my $key (keys(%env)) {
1.811     albertel 8420:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8421:             my ($start,$end) = split(/\./,$env{$key});
                   8422:             if (($end!=0) && ($end<$now)) { next; }
                   8423:             if (($start!=0) && ($start>$now)) { next; }
                   8424:             if ($1 eq $cdom && $2 eq $cnum) {
                   8425:                 $groups{$3} = $env{$key} ;
                   8426:             }
                   8427:         }
                   8428:     }
                   8429:     return %groups;
                   8430: }
                   8431: 
1.683     raeburn  8432: sub get_group_membership {
                   8433:     my ($cdom,$cnum,$group) = @_;
                   8434:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8435: }
                   8436: 
                   8437: sub get_users_groups {
                   8438:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8439:     my @usersgroups;
1.683     raeburn  8440:     my $cachetime=1800;
                   8441: 
                   8442:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8443:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8444:     if (defined($cached)) {
1.734     albertel 8445:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8446:     } else {  
                   8447:         $grouplist = '';
1.816     raeburn  8448:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8449:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8450:         my $access_end = $env{'course.'.$courseid.
                   8451:                               '.default_enrollment_end_date'};
                   8452:         my $now = time;
                   8453:         foreach my $key (keys(%roleshash)) {
                   8454:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8455:                 my $group = $1;
                   8456:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8457:                     my $start = $2;
                   8458:                     my $end = $1;
                   8459:                     if ($start == -1) { next; } # deleted from group
                   8460:                     if (($start!=0) && ($start>$now)) { next; }
                   8461:                     if (($end!=0) && ($end<$now)) {
                   8462:                         if ($access_end && $access_end < $now) {
                   8463:                             if ($access_end - $end < 86400) {
                   8464:                                 push(@usersgroups,$group);
1.733     raeburn  8465:                             }
                   8466:                         }
1.817     raeburn  8467:                         next;
1.733     raeburn  8468:                     }
1.817     raeburn  8469:                     push(@usersgroups,$group);
1.683     raeburn  8470:                 }
                   8471:             }
                   8472:         }
1.817     raeburn  8473:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8474:         $grouplist = join(':',@usersgroups);
                   8475:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8476:     }
1.733     raeburn  8477:     return @usersgroups;
1.683     raeburn  8478: }
                   8479: 
                   8480: sub devalidate_getgroups_cache {
                   8481:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8482:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8483: 
1.683     raeburn  8484:     my $hashid="$udom:$uname:$courseid";
                   8485:     &devalidate_cache_new('getgroups',$hashid);
                   8486: }
                   8487: 
1.12      www      8488: # ------------------------------------------------------------------ Plain Text
                   8489: 
                   8490: sub plaintext {
1.988     raeburn  8491:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8492:     if ($short =~ m{^cr/}) {
1.758     albertel 8493: 	return (split('/',$short))[-1];
                   8494:     }
1.742     raeburn  8495:     if (!defined($cid)) {
                   8496:         $cid = $env{'request.course.id'};
                   8497:     }
                   8498:     my %rolenames = (
1.1008    raeburn  8499:                       Course    => 'std',
                   8500:                       Community => 'alt1',
1.742     raeburn  8501:                     );
1.1037    raeburn  8502:     if ($cid ne '') {
                   8503:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8504:             unless ($forcedefault) {
                   8505:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8506:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8507:                 return &Apache::lonlocal::mt($roletext);
                   8508:             }
                   8509:         }
                   8510:     }
                   8511:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8512:         (defined($rolenames{$type})) && 
                   8513:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8514:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8515:     } elsif ($cid ne '') {
                   8516:         my $crstype = $env{'course.'.$cid.'.type'};
                   8517:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8518:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8519:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8520:         }
1.742     raeburn  8521:     }
1.1037    raeburn  8522:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8523: }
                   8524: 
                   8525: # ----------------------------------------------------------------- Assign Role
                   8526: 
                   8527: sub assignrole {
1.957     raeburn  8528:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8529:         $context)=@_;
1.21      www      8530:     my $mrole;
                   8531:     if ($role =~ /^cr\//) {
1.393     www      8532:         my $cwosec=$url;
1.811     albertel 8533:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8534: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8535:            my $refused = 1;
                   8536:            if ($context eq 'requestcourses') {
                   8537:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8538:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8539:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8540:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8541:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8542:                            if ($crsenv{'internal.courseowner'} eq
                   8543:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8544:                                $refused = '';
                   8545:                            }
                   8546:                        }
                   8547:                    }
                   8548:                }
                   8549:            }
                   8550:            if ($refused) {
                   8551:                &logthis('Refused custom assignrole: '.
                   8552:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8553:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8554:                return 'refused';
                   8555:            }
1.104     www      8556:         }
1.21      www      8557:         $mrole='cr';
1.678     raeburn  8558:     } elsif ($role =~ /^gr\//) {
                   8559:         my $cwogrp=$url;
1.811     albertel 8560:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8561:         unless (&allowed('mdg',$cwogrp)) {
                   8562:             &logthis('Refused group assignrole: '.
                   8563:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8564:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8565:             return 'refused';
                   8566:         }
                   8567:         $mrole='gr';
1.21      www      8568:     } else {
1.82      www      8569:         my $cwosec=$url;
1.811     albertel 8570:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8571:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8572:             my $refused;
                   8573:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8574:                 if (!(&allowed('c'.$role,$url))) {
                   8575:                     $refused = 1;
                   8576:                 }
                   8577:             } else {
                   8578:                 $refused = 1;
                   8579:             }
1.947     raeburn  8580:             if ($refused) {
1.1045    raeburn  8581:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8582:                 if (!$selfenroll && $context eq 'course') {
                   8583:                     my %crsenv;
                   8584:                     if ($role eq 'cc' || $role eq 'co') {
                   8585:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8586:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8587:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8588:                                 if ($crsenv{'internal.courseowner'} eq 
                   8589:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8590:                                     $refused = '';
                   8591:                                 }
                   8592:                             }
                   8593:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8594:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8595:                                 if ($crsenv{'internal.courseowner'} eq 
                   8596:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8597:                                     $refused = '';
                   8598:                                 }
                   8599:                             }
                   8600:                         }
                   8601:                     }
                   8602:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8603:                     $refused = '';
1.1017    raeburn  8604:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8605:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8606:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8607:                         my $wrongcc;
                   8608:                         if ($cnum =~ /^$match_community$/) {
                   8609:                             $wrongcc = 1 if ($role eq 'cc');
                   8610:                         } else {
                   8611:                             $wrongcc = 1 if ($role eq 'co');
                   8612:                         }
                   8613:                         unless ($wrongcc) {
                   8614:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8615:                             if ($crsenv{'internal.courseowner'} eq 
                   8616:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8617:                                 $refused = '';
                   8618:                             }
1.1017    raeburn  8619:                         }
                   8620:                     }
1.1183    raeburn  8621:                 } elsif ($context eq 'requestauthor') {
                   8622:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8623:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8624:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8625:                             $refused = '';
                   8626:                         } else {
                   8627:                             my %domdefaults = &get_domain_defaults($udom);
                   8628:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8629:                                 my $checkbystatus;
                   8630:                                 if ($env{'user.adv'}) { 
                   8631:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8632:                                     if ($disposition eq 'automatic') {
                   8633:                                         $refused = '';
                   8634:                                     } elsif ($disposition eq '') {
                   8635:                                         $checkbystatus = 1;
                   8636:                                     } 
                   8637:                                 } else {
                   8638:                                     $checkbystatus = 1;
                   8639:                                 }
                   8640:                                 if ($checkbystatus) {
                   8641:                                     if ($env{'environment.inststatus'}) {
                   8642:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8643:                                         foreach my $type (@inststatuses) {
                   8644:                                             if (($type ne '') &&
                   8645:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8646:                                                 $refused = '';
                   8647:                                             }
                   8648:                                         }
                   8649:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8650:                                         $refused = '';
                   8651:                                     }
                   8652:                                 }
                   8653:                             }
                   8654:                         }
                   8655:                     }
1.1017    raeburn  8656:                 }
                   8657:                 if ($refused) {
1.947     raeburn  8658:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8659:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8660: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8661:                     return 'refused';
                   8662:                 }
1.932     raeburn  8663:             }
1.1131    raeburn  8664:         } elsif ($role eq 'au') {
                   8665:             if ($url ne '/'.$udom.'/') {
                   8666:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8667:                          ' to assign author role for '.$uname.':'.$udom.
                   8668:                          ' in domain: '.$url.' refused (wrong domain).');
                   8669:                 return 'refused';
                   8670:             }
1.104     www      8671:         }
1.21      www      8672:         $mrole=$role;
                   8673:     }
1.620     albertel 8674:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8675:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8676:     if ($end) { $command.='_'.$end; }
1.21      www      8677:     if ($start) {
                   8678: 	if ($end) { 
1.81      www      8679:            $command.='_'.$start; 
1.21      www      8680:         } else {
1.81      www      8681:            $command.='_0_'.$start;
1.21      www      8682:         }
                   8683:     }
1.739     raeburn  8684:     my $origstart = $start;
                   8685:     my $origend = $end;
1.957     raeburn  8686:     my $delflag;
1.357     www      8687: # actually delete
                   8688:     if ($deleteflag) {
1.373     www      8689: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8690: # modify command to delete the role
1.620     albertel 8691:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8692:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8693: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8694: # set start and finish to negative values for userrolelog
                   8695:            $start=-1;
                   8696:            $end=-1;
1.957     raeburn  8697:            $delflag = 1;
1.357     www      8698:         }
                   8699:     }
                   8700: # send command
1.349     www      8701:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8702: # log new user role if status is ok
1.349     www      8703:     if ($answer eq 'ok') {
1.663     raeburn  8704: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8705:         if (($role eq 'cc') || ($role eq 'in') ||
                   8706:             ($role eq 'ep') || ($role eq 'ad') ||
                   8707:             ($role eq 'ta') || ($role eq 'st') ||
                   8708:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8709:             ($role eq 'co')) {
1.1200    raeburn  8710: # for course roles, perform group memberships changes triggered by role change.
                   8711:             unless ($role =~ /^gr/) {
                   8712:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8713:                                                  $origstart,$selfenroll,$context);
                   8714:             }
1.1184    raeburn  8715:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8716:                            $selfenroll,$context);
                   8717:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8718:                  ($role eq 'au') || ($role eq 'dc')) {
                   8719:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8720:                            $context);
                   8721:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8722:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8723:                              $context); 
                   8724:         }
1.1053    raeburn  8725:         if ($role eq 'cc') {
                   8726:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8727:         }
1.349     www      8728:     }
                   8729:     return $answer;
1.169     harris41 8730: }
                   8731: 
1.1053    raeburn  8732: sub autoupdate_coowners {
                   8733:     my ($url,$end,$start,$uname,$udom) = @_;
                   8734:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8735:     if (($cdom ne '') && ($cnum ne '')) {
                   8736:         my $now = time;
                   8737:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8738:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8739:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8740:             my $instcode = $coursehash{'internal.coursecode'};
                   8741:             if ($instcode ne '') {
1.1056    raeburn  8742:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8743:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8744:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8745:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8746:                         if ($result eq 'valid') {
                   8747:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8748:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8749:                                     push(@newcoowners,$coowner);
                   8750:                                 }
                   8751:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8752:                                     push(@newcoowners,$uname.':'.$udom);
                   8753:                                 }
                   8754:                                 @newcoowners = sort(@newcoowners);
                   8755:                             } else {
                   8756:                                 push(@newcoowners,$uname.':'.$udom);
                   8757:                             }
                   8758:                         } else {
                   8759:                             if ($coursehash{'internal.co-owners'}) {
                   8760:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8761:                                     unless ($coowner eq $uname.':'.$udom) {
                   8762:                                         push(@newcoowners,$coowner);
                   8763:                                     }
                   8764:                                 }
                   8765:                                 unless (@newcoowners > 0) {
                   8766:                                     $delcoowners = 1;
                   8767:                                     $coowners = '';
                   8768:                                 }
                   8769:                             }
                   8770:                         }
                   8771:                         if (@newcoowners || $delcoowners) {
                   8772:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8773:                                             $delcoowners,@newcoowners);
                   8774:                         }
                   8775:                     }
                   8776:                 }
                   8777:             }
                   8778:         }
                   8779:     }
                   8780: }
                   8781: 
                   8782: sub store_coowners {
                   8783:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8784:     my $cid = $cdom.'_'.$cnum;
                   8785:     my ($coowners,$delresult,$putresult);
                   8786:     if (@newcoowners) {
                   8787:         $coowners = join(',',@newcoowners);
                   8788:         my %coownershash = (
                   8789:                             'internal.co-owners' => $coowners,
                   8790:                            );
                   8791:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8792:         if ($putresult eq 'ok') {
                   8793:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8794:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8795:             }
                   8796:         }
                   8797:     }
                   8798:     if ($delcoowners) {
                   8799:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8800:         if ($delresult eq 'ok') {
                   8801:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8802:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8803:             }
                   8804:         }
                   8805:     }
                   8806:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8807:         my %crsinfo =
                   8808:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8809:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8810:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8811:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8812:         }
                   8813:     }
                   8814: }
                   8815: 
1.169     harris41 8816: # -------------------------------------------------- Modify user authentication
1.197     www      8817: # Overrides without validation
                   8818: 
1.169     harris41 8819: sub modifyuserauth {
                   8820:     my ($udom,$uname,$umode,$upass)=@_;
                   8821:     my $uhome=&homeserver($uname,$udom);
1.197     www      8822:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8823:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8824:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8825:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8826:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8827: 		     &escape($upass),$uhome);
1.620     albertel 8828:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8829:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8830:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8831:     &log($udom,,$uname,$uhome,
1.620     albertel 8832:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8833:                                      $env{'user.name'}.', '.$umode.
1.197     www      8834:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8835:     unless ($reply eq 'ok') {
1.197     www      8836:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8837: 	return 'error: '.$reply;
                   8838:     }   
1.170     harris41 8839:     return 'ok';
1.80      www      8840: }
                   8841: 
1.81      www      8842: # --------------------------------------------------------------- Modify a user
1.80      www      8843: 
1.81      www      8844: sub modifyuser {
1.206     matthew  8845:     my ($udom,    $uname, $uid,
                   8846:         $umode,   $upass, $first,
                   8847:         $middle,  $last,  $gene,
1.1058    raeburn  8848:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8849:     $udom= &LONCAPA::clean_domain($udom);
                   8850:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8851:     my $showcandelete = 'none';
                   8852:     if (ref($candelete) eq 'ARRAY') {
                   8853:         if (@{$candelete} > 0) {
                   8854:             $showcandelete = join(', ',@{$candelete});
                   8855:         }
                   8856:     }
1.81      www      8857:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8858:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8859: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8860:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8861:                                      ' desiredhome not specified'). 
1.620     albertel 8862:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8863:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8864:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8865:     my $newuser;
                   8866:     if ($uhome eq 'no_host') {
                   8867:         $newuser = 1;
                   8868:     }
1.80      www      8869: # ----------------------------------------------------------------- Create User
1.406     albertel 8870:     if (($uhome eq 'no_host') && 
                   8871: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8872:         my $unhome='';
1.844     albertel 8873:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8874:             $unhome = $desiredhome;
1.620     albertel 8875: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8876: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8877:         } else { # load balancing routine for determining $unhome
1.81      www      8878:             my $loadm=10000000;
1.841     albertel 8879: 	    my %servers = &get_servers($udom,'library');
                   8880: 	    foreach my $tryserver (keys(%servers)) {
                   8881: 		my $answer=reply('load',$tryserver);
                   8882: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8883: 		    $loadm=$answer;
                   8884: 		    $unhome=$tryserver;
                   8885: 		}
1.80      www      8886: 	    }
                   8887:         }
                   8888:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8889: 	    return 'error: unable to find a home server for '.$uname.
                   8890:                    ' in domain '.$udom;
1.80      www      8891:         }
                   8892:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8893:                          &escape($upass),$unhome);
                   8894: 	unless ($reply eq 'ok') {
                   8895:             return 'error: '.$reply;
                   8896:         }   
1.230     stredwic 8897:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8898:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8899: 	    return 'error: unable verify users home machine.';
1.80      www      8900:         }
1.209     matthew  8901:     }   # End of creation of new user
1.80      www      8902: # ---------------------------------------------------------------------- Add ID
                   8903:     if ($uid) {
                   8904:        $uid=~tr/A-Z/a-z/;
                   8905:        my %uidhash=&idrget($udom,$uname);
1.196     www      8906:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8907:          && (!$forceid)) {
1.80      www      8908: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8909: 	      return 'error: user id "'.$uid.'" does not match '.
                   8910:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8911:           }
                   8912:        } else {
1.1300    raeburn  8913: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      8914:        }
                   8915:     }
                   8916: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8917:     my @tmp=&get('environment',
1.899     raeburn  8918: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8919:                     'permanentemail','inststatus'],
1.134     albertel 8920: 		   $udom,$uname);
1.1075    raeburn  8921:     my (%names,%oldnames);
1.313     matthew  8922:     if ($tmp[0] =~ m/^error:.*/) { 
                   8923:         %names=(); 
                   8924:     } else {
                   8925:         %names = @tmp;
1.1075    raeburn  8926:         %oldnames = %names;
1.313     matthew  8927:     }
1.388     www      8928: #
1.1058    raeburn  8929: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8930: # of users did not contain them), do not overwrite existing values
                   8931: # unless field is in $candelete array ref.  
                   8932: #
                   8933: 
                   8934:     my @fields = ('firstname','middlename','lastname','generation',
                   8935:                   'permanentemail','id');
                   8936:     my %newvalues;
                   8937:     if (ref($candelete) eq 'ARRAY') {
                   8938:         foreach my $field (@fields) {
                   8939:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8940:                 if ($field eq 'firstname') {
                   8941:                     $names{$field} = $first;
                   8942:                 } elsif ($field eq 'middlename') {
                   8943:                     $names{$field} = $middle;
                   8944:                 } elsif ($field eq 'lastname') {
                   8945:                     $names{$field} = $last;
                   8946:                 } elsif ($field eq 'generation') { 
                   8947:                     $names{$field} = $gene;
                   8948:                 } elsif ($field eq 'permanentemail') {
                   8949:                     $names{$field} = $email;
                   8950:                 } elsif ($field eq 'id') {
                   8951:                     $names{$field}  = $uid;
                   8952:                 }
                   8953:             }
                   8954:         }
                   8955:     }
1.388     www      8956:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8957:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8958:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8959:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8960:     if ($email) {
                   8961:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8962:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8963:     }
1.899     raeburn  8964:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8965:     if (defined($inststatus)) {
                   8966:         $names{'inststatus'} = '';
                   8967:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8968:         if (ref($usertypes) eq 'HASH') {
                   8969:             my @okstatuses; 
                   8970:             foreach my $item (split(/:/,$inststatus)) {
                   8971:                 if (defined($usertypes->{$item})) {
                   8972:                     push(@okstatuses,$item);  
                   8973:                 }
                   8974:             }
                   8975:             if (@okstatuses) {
                   8976:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8977:             }
                   8978:         }
                   8979:     }
1.1075    raeburn  8980:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8981:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8982:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8983:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8984:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8985:     } else {
                   8986:         $logmsg .= ' during self creation';
                   8987:     }
1.1075    raeburn  8988:     my $changed;
                   8989:     if ($newuser) {
                   8990:         $changed = 1;
                   8991:     } else {
                   8992:         foreach my $field (@fields) {
                   8993:             if ($names{$field} ne $oldnames{$field}) {
                   8994:                 $changed = 1;
                   8995:                 last;
                   8996:             }
                   8997:         }
                   8998:     }
                   8999:     unless ($changed) {
                   9000:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9001:         &logthis($logmsg);
                   9002:         return 'ok';
                   9003:     }
                   9004:     my $reply = &put('environment', \%names, $udom,$uname);
                   9005:     if ($reply ne 'ok') { 
                   9006:         return 'error: '.$reply;
                   9007:     }
1.1087    raeburn  9008:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9009:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9010:     }
1.1075    raeburn  9011:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9012:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9013:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9014:     &logthis($logmsg);
1.134     albertel 9015:     return 'ok';
1.80      www      9016: }
                   9017: 
1.81      www      9018: # -------------------------------------------------------------- Modify student
1.80      www      9019: 
1.81      www      9020: sub modifystudent {
                   9021:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9022:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  9023:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 9024:     if (!$cid) {
1.620     albertel 9025: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9026: 	    return 'not_in_class';
                   9027: 	}
1.80      www      9028:     }
                   9029: # --------------------------------------------------------------- Make the user
1.81      www      9030:     my $reply=&modifyuser
1.209     matthew  9031: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9032:          $desiredhome,$email,$inststatus);
1.80      www      9033:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9034:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9035:     # student's environment
1.297     matthew  9036:     $uid = undef if (!$forceid);
1.455     albertel 9037:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9038:                                         $gene,$usec,$end,$start,$type,$locktype,
                   9039:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  9040:     return $reply;
                   9041: }
                   9042: 
                   9043: sub modify_student_enrollment {
1.1216    raeburn  9044:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   9045:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 9046:     my ($cdom,$cnum,$chome);
                   9047:     if (!$cid) {
1.620     albertel 9048: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9049: 	    return 'not_in_class';
                   9050: 	}
1.620     albertel 9051: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9052: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9053:     } else {
                   9054: 	($cdom,$cnum)=split(/_/,$cid);
                   9055:     }
1.620     albertel 9056:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9057:     if (!$chome) {
1.457     raeburn  9058: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9059:     }
1.455     albertel 9060:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9061:     # Make sure the user exists
1.81      www      9062:     my $uhome=&homeserver($uname,$udom);
                   9063:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9064: 	return 'error: no such user';
                   9065:     }
1.297     matthew  9066:     # Get student data if we were not given enough information
                   9067:     if (!defined($first)  || $first  eq '' || 
                   9068:         !defined($last)   || $last   eq '' || 
                   9069:         !defined($uid)    || $uid    eq '' || 
                   9070:         !defined($middle) || $middle eq '' || 
                   9071:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9072:         # They did not supply us with enough data to enroll the student, so
                   9073:         # we need to pick up more information.
1.297     matthew  9074:         my %tmp = &get('environment',
1.294     matthew  9075:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9076:                        ,$udom,$uname);
                   9077: 
1.800     albertel 9078:         #foreach my $key (keys(%tmp)) {
                   9079:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9080:         #}
1.294     matthew  9081:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9082:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9083:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9084:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9085:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9086:     }
1.556     albertel 9087:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9088:     my $user = "$uname:$udom";
                   9089:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9090:     my $reply=cput('classlist',
1.1148    raeburn  9091: 		   {$user => 
1.1216    raeburn  9092: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 9093: 		   $cdom,$cnum);
1.1148    raeburn  9094:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9095:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9096:     } else { 
1.81      www      9097: 	return 'error: '.$reply;
                   9098:     }
1.297     matthew  9099:     # Add student role to user
1.83      www      9100:     my $uurl='/'.$cid;
1.81      www      9101:     $uurl=~s/\_/\//g;
                   9102:     if ($usec) {
                   9103: 	$uurl.='/'.$usec;
                   9104:     }
1.1148    raeburn  9105:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9106:                              $selfenroll,$context);
                   9107:     if ($result ne 'ok') {
                   9108:         if ($old_entry{$user} ne '') {
                   9109:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9110:         } else {
                   9111:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9112:         }
                   9113:     }
                   9114:     return $result; 
1.21      www      9115: }
                   9116: 
1.556     albertel 9117: sub format_name {
                   9118:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9119:     my $name;
                   9120:     if ($first ne 'lastname') {
                   9121: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9122:     } else {
                   9123: 	if ($lastname=~/\S/) {
                   9124: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9125: 	    $name=~s/\s+,/,/;
                   9126: 	} else {
                   9127: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9128: 	}
                   9129:     }
                   9130:     $name=~s/^\s+//;
                   9131:     $name=~s/\s+$//;
                   9132:     $name=~s/\s+/ /g;
                   9133:     return $name;
                   9134: }
                   9135: 
1.84      www      9136: # ------------------------------------------------- Write to course preferences
                   9137: 
                   9138: sub writecoursepref {
                   9139:     my ($courseid,%prefs)=@_;
                   9140:     $courseid=~s/^\///;
                   9141:     $courseid=~s/\_/\//g;
                   9142:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9143:     my $chome=homeserver($cnum,$cdomain);
                   9144:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9145: 	return 'error: no such course';
                   9146:     }
                   9147:     my $cstring='';
1.800     albertel 9148:     foreach my $pref (keys(%prefs)) {
                   9149: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9150:     }
1.84      www      9151:     $cstring=~s/\&$//;
                   9152:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9153: }
                   9154: 
                   9155: # ---------------------------------------------------------- Make/modify course
                   9156: 
                   9157: sub createcourse {
1.741     raeburn  9158:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9159:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9160:     $url=&declutter($url);
                   9161:     my $cid='';
1.1028    raeburn  9162:     if ($context eq 'requestcourses') {
                   9163:         my $can_create = 0;
                   9164:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9165:         if ($udom eq $ownerdom) {
                   9166:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9167:                                   $context)) {
                   9168:                 $can_create = 1;
                   9169:             }
                   9170:         } else {
                   9171:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9172:                                            $category);
                   9173:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9174:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9175:                 if (@curr > 0) {
                   9176:                     my @options = qw(approval validate autolimit);
                   9177:                     my $optregex = join('|',@options);
                   9178:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9179:                         $can_create = 1;
                   9180:                     }
                   9181:                 }
                   9182:             }
                   9183:         }
                   9184:         if ($can_create) {
                   9185:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9186:                 unless (&allowed('ccc',$udom)) {
                   9187:                     return 'refused'; 
                   9188:                 }
1.1017    raeburn  9189:             }
                   9190:         } else {
                   9191:             return 'refused';
                   9192:         }
1.1028    raeburn  9193:     } elsif (!&allowed('ccc',$udom)) {
                   9194:         return 'refused';
1.84      www      9195:     }
1.1011    raeburn  9196: # --------------------------------------------------------------- Get Unique ID
                   9197:     my $uname;
                   9198:     if ($cnum =~ /^$match_courseid$/) {
                   9199:         my $chome=&homeserver($cnum,$udom,'true');
                   9200:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9201:             $uname = $cnum;
                   9202:         } else {
1.1038    raeburn  9203:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9204:         }
                   9205:     } else {
1.1038    raeburn  9206:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9207:     }
                   9208:     return $uname if ($uname =~ /^error/);
                   9209: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9210:     if (!defined($course_server)) {
                   9211:         if (defined(&domain($udom,'primary'))) {
                   9212:             $course_server = &domain($udom,'primary');
                   9213:         } else {
                   9214:             $course_server = $env{'user.home'}; 
                   9215:         }
                   9216:     }
                   9217:     my %host_servers =
                   9218:         &Apache::lonnet::get_servers($udom,'library');
                   9219:     unless ($host_servers{$course_server}) {
                   9220:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9221:     }
1.84      www      9222: # ------------------------------------------------------------- Make the course
                   9223:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9224:                       $course_server);
1.84      www      9225:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9226:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9227:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9228: 	return 'error: no such course';
                   9229:     }
1.271     www      9230: # ----------------------------------------------------------------- Course made
1.516     raeburn  9231: # log existence
1.1029    raeburn  9232:     my $now = time;
1.918     raeburn  9233:     my $newcourse = {
                   9234:                     $udom.'_'.$uname => {
1.921     raeburn  9235:                                      description => $description,
                   9236:                                      inst_code   => $inst_code,
                   9237:                                      owner       => $course_owner,
                   9238:                                      type        => $crstype,
1.1029    raeburn  9239:                                      creator     => $env{'user.name'}.':'.
                   9240:                                                     $env{'user.domain'},
                   9241:                                      created     => $now,
                   9242:                                      context     => $context,
1.918     raeburn  9243:                                                 },
                   9244:                     };
1.921     raeburn  9245:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9246: # set toplevel url
1.271     www      9247:     my $topurl=$url;
                   9248:     unless ($nonstandard) {
                   9249: # ------------------------------------------ For standard courses, make top url
                   9250:         my $mapurl=&clutter($url);
1.278     www      9251:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9252:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9253: <map>
                   9254: <resource id="1" type="start"></resource>
                   9255: <resource id="2" src="$mapurl"></resource>
                   9256: <resource id="3" type="finish"></resource>
                   9257: <link index="1" from="1" to="2"></link>
                   9258: <link index="2" from="2" to="3"></link>
                   9259: </map>
                   9260: ENDINITMAP
                   9261:         $topurl=&declutter(
1.638     albertel 9262:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9263:                           );
                   9264:     }
                   9265: # ----------------------------------------------------------- Write preferences
1.84      www      9266:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9267:                      ('description'              => $description,
                   9268:                       'url'                      => $topurl,
                   9269:                       'internal.creator'         => $env{'user.name'}.':'.
                   9270:                                                     $env{'user.domain'},
                   9271:                       'internal.created'         => $now,
                   9272:                       'internal.creationcontext' => $context)
                   9273:                     );
1.84      www      9274:     return '/'.$udom.'/'.$uname;
                   9275: }
                   9276: 
1.1011    raeburn  9277: # ------------------------------------------------------------------- Create ID
                   9278: sub generate_coursenum {
1.1038    raeburn  9279:     my ($udom,$crstype) = @_;
1.1011    raeburn  9280:     my $domdesc = &domain($udom);
                   9281:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9282:     my $first;
                   9283:     if ($crstype eq 'Community') {
                   9284:         $first = '0';
                   9285:     } else {
                   9286:         $first = int(1+rand(9)); 
                   9287:     } 
                   9288:     my $uname=$first.
1.1011    raeburn  9289:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9290:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9291:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9292: # ----------------------------------------------- Make sure that does not exist
                   9293:     my $uhome=&homeserver($uname,$udom,'true');
                   9294:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9295:         if ($crstype eq 'Community') {
                   9296:             $first = '0';
                   9297:         } else {
                   9298:             $first = int(1+rand(9));
                   9299:         }
                   9300:         $uname=$first.
1.1011    raeburn  9301:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9302:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9303:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9304:         $uhome=&homeserver($uname,$udom,'true');
                   9305:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9306:             return 'error: unable to generate unique course-ID';
                   9307:         }
                   9308:     }
                   9309:     return $uname;
                   9310: }
                   9311: 
1.813     albertel 9312: sub is_course {
1.1167    droeschl 9313:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9314:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9315: 
                   9316:     return unless $cdom and $cnum;
                   9317: 
                   9318:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9319:         '.');
                   9320: 
1.1219    raeburn  9321:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9322:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9323: }
                   9324: 
1.1015    raeburn  9325: sub store_userdata {
                   9326:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9327:     my $result;
1.1016    raeburn  9328:     if ($datakey ne '') {
1.1013    raeburn  9329:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9330:             if ($udom eq '' || $uname eq '') {
                   9331:                 $udom = $env{'user.domain'};
                   9332:                 $uname = $env{'user.name'};
                   9333:             }
                   9334:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9335:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9336:                 $result = 'error: no_host';
                   9337:             } else {
                   9338:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9339:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9340: 
                   9341:                 my $namevalue='';
                   9342:                 foreach my $key (keys(%{$storehash})) {
                   9343:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9344:                 }
                   9345:                 $namevalue=~s/\&$//;
1.1224    raeburn  9346:                 unless ($namespace eq 'courserequests') {
                   9347:                     $datakey = &escape($datakey);
                   9348:                 }
1.1105    raeburn  9349:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9350:                                   $namevalue,$uhome);
1.1013    raeburn  9351:             }
                   9352:         } else {
                   9353:             $result = 'error: data to store was not a hash reference'; 
                   9354:         }
                   9355:     } else {
                   9356:         $result= 'error: invalid requestkey'; 
                   9357:     }
                   9358:     return $result;
                   9359: }
                   9360: 
1.21      www      9361: # ---------------------------------------------------------- Assign Custom Role
                   9362: 
                   9363: sub assigncustomrole {
1.957     raeburn  9364:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9365:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9366:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9367: }
                   9368: 
                   9369: # ----------------------------------------------------------------- Revoke Role
                   9370: 
                   9371: sub revokerole {
1.957     raeburn  9372:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9373:     my $now=time;
1.965     raeburn  9374:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9375: }
                   9376: 
                   9377: # ---------------------------------------------------------- Revoke Custom Role
                   9378: 
                   9379: sub revokecustomrole {
1.957     raeburn  9380:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9381:     my $now=time;
1.357     www      9382:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9383:            $deleteflag,$selfenroll,$context);
1.17      www      9384: }
                   9385: 
1.533     banghart 9386: # ------------------------------------------------------------ Disk usage
1.535     albertel 9387: sub diskusage {
1.955     raeburn  9388:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9389:     $directorypath =~ s/\/$//;
                   9390:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9391:                        .&escape($getpropath).':'.&escape($uname).':'
                   9392:                        .&escape($udom),homeserver($uname,$udom));
                   9393:     if ($listing eq 'unknown_cmd') {
                   9394:         if ($getpropath) {
                   9395:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9396:         }
                   9397:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9398:     }
1.514     albertel 9399:     return $listing;
1.512     banghart 9400: }
                   9401: 
1.566     banghart 9402: sub is_locked {
1.1096    raeburn  9403:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9404:     my @check;
                   9405:     my $is_locked;
1.1093    raeburn  9406:     push (@check,$file_name);
1.613     albertel 9407:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9408: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9409:     my ($tmp)=keys(%locked);
                   9410:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9411:     
1.566     banghart 9412:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9413:         $is_locked = 'false';
                   9414:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9415:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9416:                $is_locked = 'true';
1.1096    raeburn  9417:                if (ref($which) eq 'ARRAY') {
                   9418:                    push(@{$which},$entry);
                   9419:                } else {
                   9420:                    last;
                   9421:                }
1.745     raeburn  9422:            }
                   9423:        }
1.566     banghart 9424:     } else {
                   9425:         $is_locked = 'false';
                   9426:     }
1.1093    raeburn  9427:     return $is_locked;
1.566     banghart 9428: }
                   9429: 
1.759     albertel 9430: sub declutter_portfile {
                   9431:     my ($file) = @_;
1.833     albertel 9432:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9433:     return $file;
                   9434: }
                   9435: 
1.559     banghart 9436: # ------------------------------------------------------------- Mark as Read Only
                   9437: 
                   9438: sub mark_as_readonly {
                   9439:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9440:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9441:     my ($tmp)=keys(%current_permissions);
                   9442:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9443:     foreach my $file (@{$files}) {
1.759     albertel 9444: 	$file = &declutter_portfile($file);
1.561     banghart 9445:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9446:     }
1.613     albertel 9447:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9448:     return;
                   9449: }
                   9450: 
1.572     banghart 9451: # ------------------------------------------------------------Save Selected Files
                   9452: 
                   9453: sub save_selected_files {
                   9454:     my ($user, $path, @files) = @_;
                   9455:     my $filename = $user."savedfiles";
1.573     banghart 9456:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9457:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9458:     foreach my $file (@files) {
1.620     albertel 9459:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9460:     }
                   9461:     foreach my $file (@other_files) {
1.574     banghart 9462:         print (OUT $file."\n");
1.572     banghart 9463:     }
1.574     banghart 9464:     close (OUT);
1.572     banghart 9465:     return 'ok';
                   9466: }
                   9467: 
1.574     banghart 9468: sub clear_selected_files {
                   9469:     my ($user) = @_;
                   9470:     my $filename = $user."savedfiles";
1.1117    foxr     9471:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9472:     print (OUT undef);
                   9473:     close (OUT);
                   9474:     return ("ok");    
                   9475: }
                   9476: 
1.572     banghart 9477: sub files_in_path {
                   9478:     my ($user, $path) = @_;
                   9479:     my $filename = $user."savedfiles";
                   9480:     my %return_files;
1.1117    foxr     9481:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9482:     while (my $line_in = <IN>) {
1.574     banghart 9483:         chomp ($line_in);
                   9484:         my @paths_and_file = split (m!/!, $line_in);
                   9485:         my $file_part = pop (@paths_and_file);
                   9486:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9487:         $path_part.='/';
                   9488:         my $path_and_file = $path_part.$file_part;
                   9489:         if ($path_part eq $path) {
                   9490:             $return_files{$file_part}= 'selected';
                   9491:         }
                   9492:     }
1.574     banghart 9493:     close (IN);
                   9494:     return (\%return_files);
1.572     banghart 9495: }
                   9496: 
                   9497: # called in portfolio select mode, to show files selected NOT in current directory
                   9498: sub files_not_in_path {
                   9499:     my ($user, $path) = @_;
                   9500:     my $filename = $user."savedfiles";
                   9501:     my @return_files;
                   9502:     my $path_part;
1.1117    foxr     9503:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9504:     while (my $line = <IN>) {
1.572     banghart 9505:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9506:         my @paths_and_file = split(m|/|, $line);
                   9507:         my $file_part = pop(@paths_and_file);
                   9508:         chomp($file_part);
                   9509:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9510:         $path_part .= '/';
                   9511:         my $path_and_file = $path_part.$file_part;
                   9512:         if ($path_part ne $path) {
1.800     albertel 9513:             push(@return_files, ($path_and_file));
1.572     banghart 9514:         }
                   9515:     }
1.800     albertel 9516:     close(OUT);
1.574     banghart 9517:     return (@return_files);
1.572     banghart 9518: }
                   9519: 
1.1273    raeburn  9520: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9521:  
                   9522: sub portfiles_versioning {
                   9523:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9524:     my $portfolio_root = '/userfiles/portfolio';
                   9525:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9526:     foreach my $file (@{$portfiles}) {
                   9527:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9528:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9529:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9530:         my $getpropath = 1;
                   9531:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9532:                                              $stu_name,$getpropath);
                   9533:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9534:         my $new_answer = 
                   9535:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9536:         if ($new_answer ne 'problem getting file') {
                   9537:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9538:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9539:                               [$symb,$env{'request.course.id'},'graded']);
                   9540:         }
                   9541:     }
                   9542: }
                   9543: 
                   9544: sub get_next_version {
                   9545:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9546:     my $version;
                   9547:     if (ref($dir_list) eq 'ARRAY') {
                   9548:         foreach my $row (@{$dir_list}) {
                   9549:             my ($file) = split(/\&/,$row,2);
                   9550:             my ($file_name,$file_version,$file_ext) =
                   9551:                 &file_name_version_ext($file);
                   9552:             if (($file_name eq $answer_name) &&
                   9553:                 ($file_ext eq $answer_ext)) {
                   9554:                      # gets here if filename and extension match,
                   9555:                      # regardless of version
                   9556:                 if ($file_version ne '') {
                   9557:                     # a versioned file is found  so save it for later
                   9558:                     if ($file_version > $version) {
                   9559:                         $version = $file_version;
                   9560:                     }
                   9561:                 }
                   9562:             }
                   9563:         }
                   9564:     }
                   9565:     $version ++;
                   9566:     return($version);
                   9567: }
                   9568: 
                   9569: sub version_selected_portfile {
                   9570:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9571:     my ($answer_name,$answer_ver,$answer_ext) =
                   9572:         &file_name_version_ext($file_name);
                   9573:     my $new_answer;
                   9574:     $env{'form.copy'} =
                   9575:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9576:     if($env{'form.copy'} eq '-1') {
                   9577:         $new_answer = 'problem getting file';
                   9578:     } else {
                   9579:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9580:         my $copy_result = 
                   9581:             &finishuserfileupload($stu_name,$domain,'copy',
                   9582:                                   '/portfolio'.$directory.$new_answer);
                   9583:     }
                   9584:     undef($env{'form.copy'});
                   9585:     return ($new_answer);
                   9586: }
                   9587: 
                   9588: sub file_name_version_ext {
                   9589:     my ($file)=@_;
                   9590:     my @file_parts = split(/\./, $file);
                   9591:     my ($name,$version,$ext);
                   9592:     if (@file_parts > 1) {
                   9593:         $ext=pop(@file_parts);
                   9594:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9595:             $version=pop(@file_parts);
                   9596:         }
                   9597:         $name=join('.',@file_parts);
                   9598:     } else {
                   9599:         $name=join('.',@file_parts);
                   9600:     }
                   9601:     return($name,$version,$ext);
                   9602: }
                   9603: 
1.745     raeburn  9604: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9605: 
1.745     raeburn  9606: sub get_portfile_permissions {
                   9607:     my ($domain,$user) = @_;
1.613     albertel 9608:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9609:     my ($tmp)=keys(%current_permissions);
                   9610:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9611:     return \%current_permissions;
                   9612: }
                   9613: 
                   9614: #---------------------------------------------Get portfolio file access controls
                   9615: 
1.749     raeburn  9616: sub get_access_controls {
1.745     raeburn  9617:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9618:     my %access;
                   9619:     my $real_file = $file;
                   9620:     $file =~ s/\.meta$//;
1.745     raeburn  9621:     if (defined($file)) {
1.749     raeburn  9622:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9623:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9624:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9625:             }
                   9626:         }
1.745     raeburn  9627:     } else {
1.749     raeburn  9628:         foreach my $key (keys(%{$current_permissions})) {
                   9629:             if ($key =~ /\0accesscontrol$/) {
                   9630:                 if (defined($group)) {
                   9631:                     if ($key !~ m-^\Q$group\E/-) {
                   9632:                         next;
                   9633:                     }
                   9634:                 }
                   9635:                 my ($fullpath) = split(/\0/,$key);
                   9636:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9637:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9638:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9639:                     }
                   9640:                 }
                   9641:             }
                   9642:         }
                   9643:     }
                   9644:     return %access;
                   9645: }
                   9646: 
                   9647: sub modify_access_controls {
                   9648:     my ($file_name,$changes,$domain,$user)=@_;
                   9649:     my ($outcome,$deloutcome);
                   9650:     my %store_permissions;
                   9651:     my %new_values;
                   9652:     my %new_control;
                   9653:     my %translation;
                   9654:     my @deletions = ();
                   9655:     my $now = time;
                   9656:     if (exists($$changes{'activate'})) {
                   9657:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9658:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9659:             my $numnew = scalar(@newitems);
                   9660:             for (my $i=0; $i<$numnew; $i++) {
                   9661:                 my $newkey = $newitems[$i];
                   9662:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9663:                 if ($newkey =~ /^\d+:/) { 
                   9664:                     $newkey =~ s/^(\d+)/$newid/;
                   9665:                     $translation{$1} = $newid;
                   9666:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9667:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9668:                     $translation{$1} = $newid;
                   9669:                 }
1.749     raeburn  9670:                 $new_values{$file_name."\0".$newkey} = 
                   9671:                                           $$changes{'activate'}{$newitems[$i]};
                   9672:                 $new_control{$newkey} = $now;
                   9673:             }
                   9674:         }
                   9675:     }
                   9676:     my %todelete;
                   9677:     my %changed_items;
                   9678:     foreach my $action ('delete','update') {
                   9679:         if (exists($$changes{$action})) {
                   9680:             if (ref($$changes{$action}) eq 'HASH') {
                   9681:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9682:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9683:                     if ($action eq 'delete') { 
                   9684:                         $todelete{$itemnum} = 1;
                   9685:                     } else {
                   9686:                         $changed_items{$itemnum} = $key;
                   9687:                     }
                   9688:                 }
1.745     raeburn  9689:             }
                   9690:         }
1.749     raeburn  9691:     }
                   9692:     # get lock on access controls for file.
                   9693:     my $lockhash = {
                   9694:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9695:                                                        ':'.$env{'user.domain'},
                   9696:                    }; 
                   9697:     my $tries = 0;
                   9698:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9699:    
1.1288    damieng  9700:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9701:         $tries ++;
1.1289    damieng  9702:         sleep(0.1);
1.749     raeburn  9703:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9704:     }
                   9705:     if ($gotlock eq 'ok') {
                   9706:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9707:         my ($tmp)=keys(%curr_permissions);
                   9708:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9709:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9710:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9711:             if (ref($curr_controls) eq 'HASH') {
                   9712:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9713:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9714:                     if (defined($todelete{$itemnum})) {
                   9715:                         push(@deletions,$file_name."\0".$control_item);
                   9716:                     } else {
                   9717:                         if (defined($changed_items{$itemnum})) {
                   9718:                             $new_control{$changed_items{$itemnum}} = $now;
                   9719:                             push(@deletions,$file_name."\0".$control_item);
                   9720:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9721:                         } else {
                   9722:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9723:                         }
                   9724:                     }
1.745     raeburn  9725:                 }
                   9726:             }
                   9727:         }
1.970     raeburn  9728:         my ($group);
                   9729:         if (&is_course($domain,$user)) {
                   9730:             ($group,my $file) = split(/\//,$file_name,2);
                   9731:         }
1.749     raeburn  9732:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9733:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9734:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9735:         #  remove lock
                   9736:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9737:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9738:         my $sqlresult =
1.970     raeburn  9739:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9740:                                     $group);
1.749     raeburn  9741:     } else {
                   9742:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9743:     }
1.749     raeburn  9744:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9745: }
                   9746: 
1.827     raeburn  9747: sub make_public_indefinitely {
1.1271    raeburn  9748:     my (@requrl) = @_;
                   9749:     return &automated_portfile_access('public',\@requrl);
                   9750: }
                   9751: 
                   9752: sub automated_portfile_access {
                   9753:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9754:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9755:         return 'invalid';
                   9756:     }
1.1271    raeburn  9757:     my %urls;
                   9758:     if (ref($addsref) eq 'ARRAY') {
                   9759:         foreach my $requrl (@{$addsref}) {
                   9760:             if (&is_portfolio_url($requrl)) {
                   9761:                 unless (exists($urls{$requrl})) {
                   9762:                     $urls{$requrl} = 'add';
                   9763:                 }
                   9764:             }
                   9765:         }
                   9766:     }
                   9767:     if (ref($delsref) eq 'ARRAY') {
                   9768:         foreach my $requrl (@{$delsref}) { 
                   9769:             if (&is_portfolio_url($requrl)) {
                   9770:                 unless (exists($urls{$requrl})) {
                   9771:                     $urls{$requrl} = 'delete'; 
                   9772:                 }
                   9773:             }
                   9774:         }
                   9775:     }
                   9776:     unless (keys(%urls)) {
                   9777:         return 'invalid';
                   9778:     }
                   9779:     my $ip;
                   9780:     if ($accesstype eq 'ip') {
                   9781:         if (ref($info) eq 'HASH') {
                   9782:             if ($info->{'ip'} ne '') {
                   9783:                 $ip = $info->{'ip'};
                   9784:             }
                   9785:         }
                   9786:         if ($ip eq '') {
                   9787:             return 'invalid';
                   9788:         }
                   9789:     }
                   9790:     my $errors;
1.827     raeburn  9791:     my $now = time;
1.1271    raeburn  9792:     my %current_perms;
                   9793:     foreach my $requrl (sort(keys(%urls))) {
                   9794:         my $action;
                   9795:         if ($urls{$requrl} eq 'add') {
                   9796:             $action = 'activate';
                   9797:         } else {
                   9798:             $action = 'none';
                   9799:         }
                   9800:         my $aclnum = 0;
1.827     raeburn  9801:         my (undef,$udom,$unum,$file_name,$group) =
                   9802:             &parse_portfolio_url($requrl);
1.1271    raeburn  9803:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9804:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9805:         }
                   9806:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9807:                                                    $group,$file_name);
                   9808:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9809:             my ($num,$scope,$end,$start) = 
                   9810:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9811:             if ($scope eq $accesstype) {
                   9812:                 if (($start <= $now) && ($end == 0)) {
                   9813:                     if ($accesstype eq 'ip') {
                   9814:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9815:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9816:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9817:                                     if ($urls{$requrl} eq 'add') {
                   9818:                                         $action = 'none';
                   9819:                                         last;
                   9820:                                     } else {
                   9821:                                         $action = 'delete';
                   9822:                                         $aclnum = $num;
                   9823:                                         last;
                   9824:                                     }
                   9825:                                 }
                   9826:                             }
                   9827:                         }
                   9828:                     } elsif ($accesstype eq 'public') {
                   9829:                         if ($urls{$requrl} eq 'add') {
                   9830:                             $action = 'none';
                   9831:                             last;
                   9832:                         } else {
                   9833:                             $action = 'delete';
                   9834:                             $aclnum = $num;
                   9835:                             last;
                   9836:                         }
                   9837:                     }
                   9838:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9839:                     $action = 'update';
                   9840:                     $aclnum = $num;
1.1271    raeburn  9841:                     last;
1.827     raeburn  9842:                 }
                   9843:             }
                   9844:         }
                   9845:         if ($action eq 'none') {
1.1271    raeburn  9846:             next;
1.827     raeburn  9847:         } else {
                   9848:             my %changes;
                   9849:             my $newend = 0;
                   9850:             my $newstart = $now;
1.1271    raeburn  9851:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9852:             $changes{$action}{$newkey} = {
1.1271    raeburn  9853:                 type => $accesstype,
1.827     raeburn  9854:                 time => {
                   9855:                     start => $newstart,
                   9856:                     end   => $newend,
                   9857:                 },
                   9858:             };
1.1271    raeburn  9859:             if ($accesstype eq 'ip') {
                   9860:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9861:             }
1.827     raeburn  9862:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9863:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9864:             unless ($outcome eq 'ok') {
                   9865:                 $errors .= $outcome.' ';
                   9866:             }
1.827     raeburn  9867:         }
1.1271    raeburn  9868:     }
                   9869:     if ($errors) {
                   9870:         $errors =~ s/\s$//;
                   9871:         return $errors;
1.827     raeburn  9872:     } else {
1.1271    raeburn  9873:         return 'ok';
1.827     raeburn  9874:     }
                   9875: }
                   9876: 
1.745     raeburn  9877: #------------------------------------------------------Get Marked as Read Only
                   9878: 
                   9879: sub get_marked_as_readonly {
                   9880:     my ($domain,$user,$what,$group) = @_;
                   9881:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9882:     my @readonly_files;
1.629     banghart 9883:     my $cmp1=$what;
                   9884:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9885:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9886:         if (defined($group)) {
                   9887:             if ($file_name !~ m-^\Q$group\E/-) {
                   9888:                 next;
                   9889:             }
                   9890:         }
1.561     banghart 9891:         if (ref($value) eq "ARRAY"){
                   9892:             foreach my $stored_what (@{$value}) {
1.629     banghart 9893:                 my $cmp2=$stored_what;
1.759     albertel 9894:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9895:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9896:                 }
1.629     banghart 9897:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9898:                     push(@readonly_files, $file_name);
1.745     raeburn  9899:                     last;
1.563     banghart 9900:                 } elsif (!defined($what)) {
                   9901:                     push(@readonly_files, $file_name);
1.745     raeburn  9902:                     last;
1.561     banghart 9903:                 }
                   9904:             }
1.745     raeburn  9905:         }
1.561     banghart 9906:     }
                   9907:     return @readonly_files;
                   9908: }
1.577     banghart 9909: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9910: 
1.577     banghart 9911: sub get_marked_as_readonly_hash {
1.745     raeburn  9912:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9913:     my %readonly_files;
1.745     raeburn  9914:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9915:         if (defined($group)) {
                   9916:             if ($file_name !~ m-^\Q$group\E/-) {
                   9917:                 next;
                   9918:             }
                   9919:         }
1.577     banghart 9920:         if (ref($value) eq "ARRAY"){
                   9921:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9922:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9923:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9924:                         if ($lock_descriptor eq 'graded') {
                   9925:                             $readonly_files{$file_name} = 'graded';
                   9926:                         } elsif ($lock_descriptor eq 'handback') {
                   9927:                             $readonly_files{$file_name} = 'handback';
                   9928:                         } else {
                   9929:                             if (!exists($readonly_files{$file_name})) {
                   9930:                                 $readonly_files{$file_name} = 'locked';
                   9931:                             }
                   9932:                         }
1.745     raeburn  9933:                     }
1.750     banghart 9934:                 } 
1.577     banghart 9935:             }
                   9936:         } 
                   9937:     }
                   9938:     return %readonly_files;
                   9939: }
1.559     banghart 9940: # ------------------------------------------------------------ Unmark as Read Only
                   9941: 
                   9942: sub unmark_as_readonly {
1.629     banghart 9943:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9944:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9945:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9946:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9947:     my $symb_crs = $what;
                   9948:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9949:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9950:     my ($tmp)=keys(%current_permissions);
                   9951:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9952:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9953:     foreach my $file (@readonly_files) {
1.759     albertel 9954: 	my $clean_file = &declutter_portfile($file);
                   9955: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9956: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9957:         my @new_locks;
                   9958:         my @del_keys;
                   9959:         if (ref($current_locks) eq "ARRAY"){
                   9960:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9961:                 my $compare=$locker;
1.749     raeburn  9962:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9963:                     $compare=join('',@{$locker});
1.746     raeburn  9964:                     if ($compare ne $symb_crs) {
                   9965:                         push(@new_locks, $locker);
                   9966:                     }
1.563     banghart 9967:                 }
                   9968:             }
1.650     albertel 9969:             if (scalar(@new_locks) > 0) {
1.563     banghart 9970:                 $current_permissions{$file} = \@new_locks;
                   9971:             } else {
                   9972:                 push(@del_keys, $file);
1.613     albertel 9973:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9974:                 delete($current_permissions{$file});
1.563     banghart 9975:             }
                   9976:         }
1.561     banghart 9977:     }
1.613     albertel 9978:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9979:     return;
                   9980: }
1.512     banghart 9981: 
1.17      www      9982: # ------------------------------------------------------------ Directory lister
                   9983: 
                   9984: sub dirlist {
1.955     raeburn  9985:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9986:     $uri=~s/^\///;
                   9987:     $uri=~s/\/$//;
1.253     stredwic 9988:     my ($udom, $uname);
1.955     raeburn  9989:     if ($getuserdir) {
1.253     stredwic 9990:         $udom = $userdomain;
                   9991:         $uname = $username;
1.955     raeburn  9992:     } else {
                   9993:         (undef,$udom,$uname)=split(/\//,$uri);
                   9994:         if(defined($userdomain)) {
                   9995:             $udom = $userdomain;
                   9996:         }
                   9997:         if(defined($username)) {
                   9998:             $uname = $username;
                   9999:         }
1.253     stredwic 10000:     }
1.955     raeburn  10001:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10002: 
1.955     raeburn  10003:     $dirRoot = $perlvar{'lonDocRoot'};
                   10004:     if (defined($getpropath)) {
                   10005:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10006:         $dirRoot =~ s/\/$//;
1.955     raeburn  10007:     } elsif (defined($getuserdir)) {
                   10008:         my $subdir=$uname.'__';
                   10009:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10010:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10011:                    ."/$udom/$subdir/$uname";
                   10012:     } elsif (defined($alternateRoot)) {
                   10013:         $dirRoot = $alternateRoot;
1.751     banghart 10014:     }
1.253     stredwic 10015: 
                   10016:     if($udom) {
                   10017:         if($uname) {
1.1135    raeburn  10018:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10019:             if ($uhome eq 'no_host') {
                   10020:                 return ([],'no_host');
                   10021:             }
1.955     raeburn  10022:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10023:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10024:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10025:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10026:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10027:             } else {
                   10028:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10029:             }
1.605     matthew  10030:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10031:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10032:                 @listing_results = split(/:/,$listing);
                   10033:             } else {
                   10034:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10035:             }
1.1135    raeburn  10036:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10037:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10038:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10039:                 return ([],$listing);
                   10040:             } else {
                   10041:                 return (\@listing_results);
1.1135    raeburn  10042:             }
1.955     raeburn  10043:         } elsif(!$alternateRoot) {
1.1136    raeburn  10044:             my (%allusers,%listerror);
1.841     albertel 10045: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10046:  	    foreach my $tryserver (keys(%servers)) {
                   10047:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10048:                                   &escape($udom),$tryserver);
                   10049:                 if ($listing eq 'unknown_cmd') {
                   10050: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10051: 				      $udom, $tryserver);
                   10052:                 } else {
                   10053:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10054:                 }
1.841     albertel 10055: 		if ($listing eq 'unknown_cmd') {
                   10056: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10057: 				      $udom, $tryserver);
                   10058: 		    @listing_results = split(/:/,$listing);
                   10059: 		} else {
                   10060: 		    @listing_results =
                   10061: 			map { &unescape($_); } split(/:/,$listing);
                   10062: 		}
1.1136    raeburn  10063:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10064:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10065:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10066:                     $listerror{$tryserver} = $listing;
                   10067:                 } else {
1.841     albertel 10068: 		    foreach my $line (@listing_results) {
                   10069: 			my ($entry) = split(/&/,$line,2);
                   10070: 			$allusers{$entry} = 1;
                   10071: 		    }
                   10072: 		}
1.253     stredwic 10073:             }
1.1136    raeburn  10074:             my @alluserslist=();
1.800     albertel 10075:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10076:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10077:             }
1.1136    raeburn  10078:             return (\@alluserslist);
1.253     stredwic 10079:         } else {
1.1136    raeburn  10080:             return ([],'missing username');
1.253     stredwic 10081:         }
1.955     raeburn  10082:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10083:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10084:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10085:         return (\@all_domains);
1.955     raeburn  10086:     } else {
1.1136    raeburn  10087:         return ([],'missing domain');
1.275     stredwic 10088:     }
                   10089: }
                   10090: 
                   10091: # --------------------------------------------- GetFileTimestamp
                   10092: # This function utilizes dirlist and returns the date stamp for
                   10093: # when it was last modified.  It will also return an error of -1
                   10094: # if an error occurs
                   10095: 
                   10096: sub GetFileTimestamp {
1.955     raeburn  10097:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10098:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10099:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10100:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10101:                                     undef,$getuserdir);
                   10102:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10103:         return -1;
                   10104:     }
                   10105:     if (ref($fileref) eq 'ARRAY') {
                   10106:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10107:         # @stats contains first the filename, then the stat output
                   10108:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10109:     } else {
                   10110:         return -1;
1.253     stredwic 10111:     }
1.26      www      10112: }
                   10113: 
1.712     albertel 10114: sub stat_file {
                   10115:     my ($uri) = @_;
1.787     albertel 10116:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10117: 
1.955     raeburn  10118:     my ($udom,$uname,$file);
1.712     albertel 10119:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10120: 	($udom,$uname,$file) =
1.811     albertel 10121: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10122: 	$file = 'userfiles/'.$file;
                   10123:     }
                   10124:     if ($uri =~ m-^/res/-) {
                   10125: 	($udom,$uname) = 
1.807     albertel 10126: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10127: 	$file = $uri;
                   10128:     }
                   10129: 
                   10130:     if (!$udom || !$uname || !$file) {
                   10131: 	# unable to handle the uri
                   10132: 	return ();
                   10133:     }
1.956     raeburn  10134:     my $getpropath;
                   10135:     if ($file =~ /^userfiles\//) {
                   10136:         $getpropath = 1;
                   10137:     }
1.1136    raeburn  10138:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10139:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10140:         return ();
                   10141:     } else {
                   10142:         if (ref($listref) eq 'ARRAY') {
                   10143:             my @stats = split('&',$listref->[0]);
                   10144: 	    shift(@stats); #filename is first
                   10145: 	    return @stats;
                   10146:         }
1.712     albertel 10147:     }
                   10148:     return ();
                   10149: }
                   10150: 
1.26      www      10151: # -------------------------------------------------------- Value of a Condition
                   10152: 
1.713     albertel 10153: # gets the value of a specific preevaluated condition
                   10154: #    stored in the string  $env{user.state.<cid>}
                   10155: # or looks up a condition reference in the bighash and if if hasn't
                   10156: # already been evaluated recurses into docondval to get the value of
                   10157: # the condition, then memoizing it to 
                   10158: #   $env{user.state.<cid>.<condition>}
1.40      www      10159: sub directcondval {
                   10160:     my $number=shift;
1.620     albertel 10161:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10162: 	&Apache::lonuserstate::evalstate();
                   10163:     }
1.713     albertel 10164:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10165: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10166:     } elsif ($number =~ /^_/) {
                   10167: 	my $sub_condition;
                   10168: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10169: 		&GDBM_READER(),0640)) {
                   10170: 	    $sub_condition=$bighash{'conditions'.$number};
                   10171: 	    untie(%bighash);
                   10172: 	}
                   10173: 	my $value = &docondval($sub_condition);
1.949     raeburn  10174: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10175: 	return $value;
                   10176:     }
1.620     albertel 10177:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10178:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10179:     } else {
                   10180:        return 2;
                   10181:     }
                   10182: }
                   10183: 
1.713     albertel 10184: # get the collection of conditions for this resource
1.26      www      10185: sub condval {
                   10186:     my $condidx=shift;
1.54      www      10187:     my $allpathcond='';
1.713     albertel 10188:     foreach my $cond (split(/\|/,$condidx)) {
                   10189: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10190: 	    $allpathcond.=
                   10191: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10192: 	}
1.191     harris41 10193:     }
1.54      www      10194:     $allpathcond=~s/\|$//;
1.713     albertel 10195:     return &docondval($allpathcond);
                   10196: }
                   10197: 
                   10198: #evaluates an expression of conditions
                   10199: sub docondval {
                   10200:     my ($allpathcond) = @_;
                   10201:     my $result=0;
                   10202:     if ($env{'request.course.id'}
                   10203: 	&& defined($allpathcond)) {
                   10204: 	my $operand='|';
                   10205: 	my @stack;
                   10206: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10207: 	    if ($chunk eq '(') {
                   10208: 		push @stack,($operand,$result);
                   10209: 	    } elsif ($chunk eq ')') {
                   10210: 		my $before=pop @stack;
                   10211: 		if (pop @stack eq '&') {
                   10212: 		    $result=$result>$before?$before:$result;
                   10213: 		} else {
                   10214: 		    $result=$result>$before?$result:$before;
                   10215: 		}
                   10216: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10217: 		$operand=$chunk;
                   10218: 	    } else {
                   10219: 		my $new=directcondval($chunk);
                   10220: 		if ($operand eq '&') {
                   10221: 		    $result=$result>$new?$new:$result;
                   10222: 		} else {
                   10223: 		    $result=$result>$new?$result:$new;
                   10224: 		}
                   10225: 	    }
                   10226: 	}
1.26      www      10227:     }
                   10228:     return $result;
1.421     albertel 10229: }
                   10230: 
                   10231: # ---------------------------------------------------- Devalidate courseresdata
                   10232: 
                   10233: sub devalidatecourseresdata {
                   10234:     my ($coursenum,$coursedomain)=@_;
                   10235:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10236:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10237: }
                   10238: 
1.763     www      10239: 
1.200     www      10240: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10241: #
                   10242: #  Parameters:
                   10243: #      $coursenum    - Number of the course.
                   10244: #      $coursedomain - Domain at which the course was created.
                   10245: #  Returns:
                   10246: #     A hash of the course parameters along (I think) with timestamps
                   10247: #     and version info.
1.877     foxr     10248: 
1.624     albertel 10249: sub get_courseresdata {
                   10250:     my ($coursenum,$coursedomain)=@_;
1.200     www      10251:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10252:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10253:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10254:     my %dumpreply;
1.417     albertel 10255:     unless (defined($cached)) {
1.624     albertel 10256: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10257: 	$result=\%dumpreply;
1.251     albertel 10258: 	my ($tmp) = keys(%dumpreply);
                   10259: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10260: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10261: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10262: 	    return $tmp;
1.416     albertel 10263: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10264: 	    $result=undef;
1.599     albertel 10265: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10266: 	}
                   10267:     }
1.624     albertel 10268:     return $result;
                   10269: }
                   10270: 
1.633     albertel 10271: sub devalidateuserresdata {
                   10272:     my ($uname,$udom)=@_;
                   10273:     my $hashid="$udom:$uname";
                   10274:     &devalidate_cache_new('userres',$hashid);
                   10275: }
                   10276: 
1.624     albertel 10277: sub get_userresdata {
                   10278:     my ($uname,$udom)=@_;
                   10279:     #most student don\'t have any data set, check if there is some data
                   10280:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10281: 
                   10282:     my $hashid="$udom:$uname";
                   10283:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10284:     if (!defined($cached)) {
                   10285: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10286: 	$result=\%resourcedata;
                   10287: 	&do_cache_new('userres',$hashid,$result,600);
                   10288:     }
                   10289:     my ($tmp)=keys(%$result);
                   10290:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10291: 	return $result;
                   10292:     }
                   10293:     #error 2 occurs when the .db doesn't exist
                   10294:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10295:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10296: 	    &logthis("<font color=\"blue\">WARNING:".
                   10297: 		     " Trying to get resource data for ".
                   10298: 		     $uname." at ".$udom.": ".
                   10299: 		     $tmp."</font>");
                   10300:         }
1.624     albertel 10301:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10302: 	#&EXT_cache_set($udom,$uname);
                   10303: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10304: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10305:     }
                   10306:     return $tmp;
                   10307: }
1.879     foxr     10308: #----------------------------------------------- resdata - return resource data
                   10309: #  Purpose:
                   10310: #    Return resource data for either users or for a course.
                   10311: #  Parameters:
                   10312: #     $name      - Course/user name.
                   10313: #     $domain    - Name of the domain the user/course is registered on.
                   10314: #     $type      - Type of thing $name is (must be 'course' or 'user'
1.1301    raeburn  10315: #     $mapp      - decluttered URL of enclosing map  
                   10316: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10317: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10318: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10319: #     $courseid  - CourseID (first part of param identifier).
                   10320: #     $modifier  - Middle part of param identifier.
                   10321: #     $what      - Last part of param identifier.
1.879     foxr     10322: #     @which     - Array of names of resources desired.
                   10323: #  Returns:
                   10324: #     The value of the first reasource in @which that is found in the
                   10325: #     resource hash.
                   10326: #  Exceptional Conditions:
                   10327: #     If the $type passed in is not valid (not the string 'course' or 
                   10328: #     'user', an undefined  reference is returned.
                   10329: #     If none of the resources are found, an undef is returned
1.624     albertel 10330: sub resdata {
1.1301    raeburn  10331:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10332:         $modifier,$what,@which)=@_;
1.624     albertel 10333:     my $result;
                   10334:     if ($type eq 'course') {
                   10335: 	$result=&get_courseresdata($name,$domain);
                   10336:     } elsif ($type eq 'user') {
                   10337: 	$result=&get_userresdata($name,$domain);
                   10338:     }
                   10339:     if (!ref($result)) { return $result; }    
1.251     albertel 10340:     foreach my $item (@which) {
1.1301    raeburn  10341:         if ($item->[1] eq 'course') {
                   10342:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10343:                 unless ($$recursed) {
1.1302    raeburn  10344:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10345:                     $$recursed = 1;
                   10346:                 }
                   10347:                 foreach my $item (@${recurseup}) {
                   10348:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10349:                     last if (defined($result->{$norecursechk}));
                   10350:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10351:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10352:                 }
                   10353:             }
                   10354:         }
                   10355:         if (defined($result->{$item->[0]})) {
1.927     albertel 10356: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10357: 	}
1.250     albertel 10358:     }
1.291     albertel 10359:     return undef;
1.200     www      10360: }
                   10361: 
1.1298    raeburn  10362: sub get_domain_ltitools {
                   10363:     my ($cdom) = @_;
                   10364:     my %ltitools;
                   10365:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10366:     if (defined($cached)) {
                   10367:         if (ref($result) eq 'HASH') {
                   10368:             %ltitools = %{$result};
                   10369:         }
                   10370:     } else {
                   10371:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10372:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10373:             %ltitools = %{$domconfig{'ltitools'}};
                   10374:         }
                   10375:         my $cachetime = 24*60*60;
                   10376:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10377:     }
                   10378:     return %ltitools;
                   10379: }
                   10380: 
1.1236    raeburn  10381: sub get_numsuppfiles {
                   10382:     my ($cnum,$cdom,$ignorecache)=@_;
                   10383:     my $hashid=$cnum.':'.$cdom;
                   10384:     my ($suppcount,$cached);
                   10385:     unless ($ignorecache) {
                   10386:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10387:     }
                   10388:     unless (defined($cached)) {
                   10389:         my $chome=&homeserver($cnum,$cdom);
                   10390:         unless ($chome eq 'no_host') {
                   10391:             ($suppcount,my $errors) = (0,0);
                   10392:             my $suppmap = 'supplemental.sequence';
                   10393:             ($suppcount,$errors) = 
                   10394:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10395:         }
                   10396:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10397:     }
                   10398:     return $suppcount;
                   10399: }
                   10400: 
1.379     matthew  10401: #
                   10402: # EXT resource caching routines
                   10403: #
                   10404: 
1.1302    raeburn  10405: {
                   10406: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10407: #
                   10408: # The course for which we cache
                   10409: my $cachedmapkey='';
                   10410: # The cached recursive maps for this course
                   10411: my %cachedmaps=();
                   10412: # When this was last done
                   10413: my $cachedmaptime='';
                   10414: 
1.379     matthew  10415: sub clear_EXT_cache_status {
1.383     albertel 10416:     &delenv('cache.EXT.');
1.379     matthew  10417: }
                   10418: 
                   10419: sub EXT_cache_status {
                   10420:     my ($target_domain,$target_user) = @_;
1.383     albertel 10421:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10422:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10423:         # We know already the user has no data
                   10424:         return 1;
                   10425:     } else {
                   10426:         return 0;
                   10427:     }
                   10428: }
                   10429: 
                   10430: sub EXT_cache_set {
                   10431:     my ($target_domain,$target_user) = @_;
1.383     albertel 10432:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10433:     #&appenv({$cachename => time});
1.379     matthew  10434: }
                   10435: 
1.28      www      10436: # --------------------------------------------------------- Value of a Variable
1.58      www      10437: sub EXT {
1.715     albertel 10438: 
1.1228    raeburn  10439:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10440:     unless ($varname) { return ''; }
1.218     albertel 10441:     #get real user name/domain, courseid and symb
                   10442:     my $courseid;
1.359     albertel 10443:     my $publicuser;
1.427     www      10444:     if ($symbparm) {
                   10445: 	$symbparm=&get_symb_from_alias($symbparm);
                   10446:     }
1.218     albertel 10447:     if (!($uname && $udom)) {
1.790     albertel 10448:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10449:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10450:     } else {
1.620     albertel 10451: 	$courseid=$env{'request.course.id'};
1.218     albertel 10452:     }
1.48      www      10453:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10454:     my $rest;
1.320     albertel 10455:     if (defined($therest[0])) {
1.48      www      10456:        $rest=join('.',@therest);
                   10457:     } else {
                   10458:        $rest='';
                   10459:     }
1.320     albertel 10460: 
1.57      www      10461:     my $qualifierrest=$qualifier;
                   10462:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10463:     my $spacequalifierrest=$space;
                   10464:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10465:     if ($realm eq 'user') {
1.48      www      10466: # --------------------------------------------------------------- user.resource
                   10467: 	if ($space eq 'resource') {
1.651     albertel 10468: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10469: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10470: 		 &&
1.744     albertel 10471: 		 ($symbparm eq &symbread()) ) {	
                   10472: 		# if we are in the middle of processing the resource the
                   10473: 		# get the value we are planning on committing
                   10474:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10475:                     return $Apache::lonhomework::results{$qualifierrest};
                   10476:                 } else {
                   10477:                     return $Apache::lonhomework::history{$qualifierrest};
                   10478:                 }
1.335     albertel 10479: 	    } else {
1.359     albertel 10480: 		my %restored;
1.620     albertel 10481: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10482: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10483: 		} else {
                   10484: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10485: 		}
1.335     albertel 10486: 		return $restored{$qualifierrest};
                   10487: 	    }
1.48      www      10488: # ----------------------------------------------------------------- user.access
                   10489:         } elsif ($space eq 'access') {
1.218     albertel 10490: 	    # FIXME - not supporting calls for a specific user
1.48      www      10491:             return &allowed($qualifier,$rest);
                   10492: # ------------------------------------------ user.preferences, user.environment
                   10493:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10494: 	    if (($uname eq $env{'user.name'}) &&
                   10495: 		($udom eq $env{'user.domain'})) {
                   10496: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10497: 	    } else {
1.359     albertel 10498: 		my %returnhash;
                   10499: 		if (!$publicuser) {
                   10500: 		    %returnhash=&userenvironment($udom,$uname,
                   10501: 						 $qualifierrest);
                   10502: 		}
1.218     albertel 10503: 		return $returnhash{$qualifierrest};
                   10504: 	    }
1.48      www      10505: # ----------------------------------------------------------------- user.course
                   10506:         } elsif ($space eq 'course') {
1.218     albertel 10507: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10508:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10509: # ------------------------------------------------------------------- user.role
                   10510:         } elsif ($space eq 'role') {
1.218     albertel 10511: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10512:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10513:             if ($qualifier eq 'value') {
                   10514: 		return $role;
                   10515:             } elsif ($qualifier eq 'extent') {
                   10516:                 return $where;
                   10517:             }
                   10518: # ----------------------------------------------------------------- user.domain
                   10519:         } elsif ($space eq 'domain') {
1.218     albertel 10520:             return $udom;
1.48      www      10521: # ------------------------------------------------------------------- user.name
                   10522:         } elsif ($space eq 'name') {
1.218     albertel 10523:             return $uname;
1.48      www      10524: # ---------------------------------------------------- Any other user namespace
1.29      www      10525:         } else {
1.359     albertel 10526: 	    my %reply;
                   10527: 	    if (!$publicuser) {
                   10528: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10529: 	    }
                   10530: 	    return $reply{$qualifierrest};
1.48      www      10531:         }
1.236     www      10532:     } elsif ($realm eq 'query') {
                   10533: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10534:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10535: 						[$spacequalifierrest]);
1.620     albertel 10536: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10537:    } elsif ($realm eq 'request') {
1.48      www      10538: # ------------------------------------------------------------- request.browser
                   10539:         if ($space eq 'browser') {
1.1145    bisitz   10540:             return $env{'browser.'.$qualifier};
1.57      www      10541: # ------------------------------------------------------------ request.filename
                   10542:         } else {
1.620     albertel 10543:             return $env{'request.'.$spacequalifierrest};
1.29      www      10544:         }
1.28      www      10545:     } elsif ($realm eq 'course') {
1.48      www      10546: # ---------------------------------------------------------- course.description
1.620     albertel 10547:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10548:     } elsif ($realm eq 'resource') {
1.165     www      10549: 
1.620     albertel 10550: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10551: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10552: 	}
1.693     albertel 10553: 
1.1232    raeburn  10554:         if ($qualifier eq '') {
                   10555: 	    if ($space eq 'title') {
                   10556: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10557: 	        return &gettitle($symbparm);
                   10558: 	    }
1.693     albertel 10559: 	
1.1232    raeburn  10560: 	    if ($space eq 'map') {
                   10561: 	        my ($map) = &decode_symb($symbparm);
                   10562: 	        return &symbread($map);
                   10563: 	    }
                   10564:             if ($space eq 'maptitle') {
                   10565:                 my ($map) = &decode_symb($symbparm);
                   10566:                 return &gettitle($map);
                   10567:             }
                   10568: 	    if ($space eq 'filename') {
                   10569: 	        if ($symbparm) {
                   10570: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10571: 	        }
                   10572: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10573: 	    }
1.1232    raeburn  10574: 
1.1233    raeburn  10575:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10576:                 if ($space eq 'visibleparts') {
                   10577:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10578:                     my $item;
                   10579:                     if (ref($navmap)) {
                   10580:                         my $res = $navmap->getBySymb($symbparm);
                   10581:                         my $parts = $res->parts();
                   10582:                         if (ref($parts) eq 'ARRAY') {
                   10583:                             $item = join(',',@{$parts});
                   10584:                         }
                   10585:                         undef($navmap);
1.1232    raeburn  10586:                     }
1.1233    raeburn  10587:                     return $item;
1.1232    raeburn  10588:                 }
                   10589:             }
                   10590:         }
1.693     albertel 10591: 
1.1301    raeburn  10592: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10593: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10594:         if (($courseid eq '') && ($cid)) {
                   10595:             $courseid = $cid;
                   10596:         }
                   10597: 	if (($symbparm && $courseid) && 
                   10598: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10599: 
1.218     albertel 10600: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10601: 
1.60      www      10602: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10603: 	    my $symbp=$symbparm;
1.1301    raeburn  10604: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10605: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10606:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10607: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10608: 	    if (($env{'user.name'} eq $uname) &&
                   10609: 		($env{'user.domain'} eq $udom)) {
                   10610: 		$section=$env{'request.course.sec'};
1.733     raeburn  10611:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10612:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10613: 	    } else {
1.539     albertel 10614: 		if (! defined($usection)) {
1.551     albertel 10615: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10616: 		} else {
                   10617: 		    $section = $usection;
                   10618: 		}
1.733     raeburn  10619:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10620: 	    }
                   10621: 
                   10622: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10623: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10624:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10625: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10626: 
1.593     albertel 10627: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10628: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10629:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10630: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10631: 
1.60      www      10632: # ----------------------------------------------------------- first, check user
1.624     albertel 10633: 
1.1301    raeburn  10634: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10635:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10636: 				       ([$courselevelr,'resource'],
                   10637: 					[$courselevelm,'map'     ],
1.1301    raeburn  10638:                                         [$courseleveli,'map'     ],
1.927     albertel 10639: 					[$courselevel, 'course'  ]));
1.931     albertel 10640: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10641: 
1.594     albertel 10642: # ------------------------------------------------ second, check some of course
1.684     raeburn  10643:             my $coursereply;
1.691     raeburn  10644:             if (@groups > 0) {
                   10645:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10646:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10647:                                        $mapp,\$recursed,\@recurseup);
                   10648:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10649:             }
1.96      www      10650: 
1.684     raeburn  10651: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10652: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10653: 				  'course',$mapp,\$recursed,\@recurseup,
                   10654:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10655: 				  ([$seclevelr,   'resource'],
                   10656: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10657:                                    [$secleveli,   'map'     ],
1.927     albertel 10658: 				   [$seclevel,    'course'  ],
                   10659: 				   [$courselevelr,'resource']));
                   10660: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10661: 
1.60      www      10662: # ------------------------------------------------------ third, check map parms
1.218     albertel 10663: 	    my %parmhash=();
                   10664: 	    my $thisparm='';
                   10665: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10666: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10667: 		    &GDBM_READER(),0640)) {
1.218     albertel 10668: 		$thisparm=$parmhash{$symbparm};
                   10669: 		untie(%parmhash);
                   10670: 	    }
1.927     albertel 10671: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10672: 	}
1.594     albertel 10673: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10674:  
                   10675:         my $what = $spacequalifierrest;
                   10676: 	$what=~s/\./\_/;
1.282     albertel 10677: 	my $filename;
                   10678: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10679: 	if ($symbparm) {
1.409     www      10680: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10681: 	} else {
1.620     albertel 10682: 	    $filename=$env{'request.filename'};
1.282     albertel 10683: 	}
1.1301    raeburn  10684: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10685: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10686: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10687: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10688: 
1.1301    raeburn  10689: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10690: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10691: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10692: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10693: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10694: 				     'course',$mapp,\$recursed,\@recurseup,
                   10695:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10696: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10697:                                       [$courseleveli,'map'   ],
1.927     albertel 10698: 				      [$courselevel, 'course']));
                   10699: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10700: 	}
1.145     www      10701: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10702: 	unless ($space eq '0') {
1.336     albertel 10703: 	    my @parts=split(/_/,$space);
                   10704: 	    my $id=pop(@parts);
                   10705: 	    my $part=join('_',@parts);
                   10706: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10707: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10708: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10709: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10710: 	}
1.395     albertel 10711: 	if ($recurse) { return undef; }
                   10712: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10713: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10714: # ---------------------------------------------------- Any other user namespace
                   10715:     } elsif ($realm eq 'environment') {
                   10716: # ----------------------------------------------------------------- environment
1.620     albertel 10717: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10718: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10719: 	} else {
1.770     albertel 10720: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10721: 		return '';
                   10722: 	    }
1.219     albertel 10723: 	    my %returnhash=&userenvironment($udom,$uname,
                   10724: 					    $spacequalifierrest);
                   10725: 	    return $returnhash{$spacequalifierrest};
                   10726: 	}
1.28      www      10727:     } elsif ($realm eq 'system') {
1.48      www      10728: # ----------------------------------------------------------------- system.time
                   10729: 	if ($space eq 'time') {
                   10730: 	    return time;
                   10731:         }
1.696     albertel 10732:     } elsif ($realm eq 'server') {
                   10733: # ----------------------------------------------------------------- system.time
                   10734: 	if ($space eq 'name') {
                   10735: 	    return $ENV{'SERVER_NAME'};
                   10736:         }
1.28      www      10737:     }
1.48      www      10738:     return '';
1.61      www      10739: }
                   10740: 
1.927     albertel 10741: sub get_reply {
                   10742:     my ($reply_value) = @_;
1.940     raeburn  10743:     if (ref($reply_value) eq 'ARRAY') {
                   10744:         if (wantarray) {
                   10745: 	    return @$reply_value;
                   10746:         }
                   10747:         return $reply_value->[0];
                   10748:     } else {
                   10749:         return $reply_value;
1.927     albertel 10750:     }
                   10751: }
                   10752: 
1.691     raeburn  10753: sub check_group_parms {
1.1301    raeburn  10754:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   10755:         $recursed,$recurseupref) = @_;
                   10756:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   10757:                   [$what,'course']);
                   10758:     my $coursereply;
1.691     raeburn  10759:     foreach my $group (@{$groups}) {
1.1301    raeburn  10760:         my @groupitems = ();
1.691     raeburn  10761:         foreach my $level (@levels) {
1.927     albertel 10762:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10763:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10764:         }
1.1301    raeburn  10765:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10766:                                    $env{'course.'.$courseid.'.domain'},
                   10767:                                    'course',$mapp,$recursed,$recurseupref,
                   10768:                                    $courseid,'.['.$group.'].',$what,
                   10769:                                    @groupitems);
                   10770:         last if (defined($coursereply));
1.691     raeburn  10771:     }
                   10772:     return $coursereply;
                   10773: }
                   10774: 
1.1301    raeburn  10775: sub get_map_hierarchy {
1.1302    raeburn  10776:     my ($mapname,$courseid) = @_;
                   10777:     my @recurseup = ();
1.1301    raeburn  10778:     if ($mapname) {
1.1302    raeburn  10779:         if (($cachedmapkey eq $courseid) &&
                   10780:             (abs($cachedmaptime-time)<5)) {
                   10781:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   10782:                 return @{$cachedmaps{$mapname}};
                   10783:             }
                   10784:         }
1.1301    raeburn  10785:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10786:         if (ref($navmap)) {
                   10787:             @recurseup = $navmap->recurseup_maps($mapname);
                   10788:             undef($navmap);
1.1302    raeburn  10789:             $cachedmaps{$mapname} = \@recurseup;
                   10790:             $cachedmaptime=time;
                   10791:             $cachedmapkey=$courseid;
1.1301    raeburn  10792:         }
                   10793:     }
                   10794:     return @recurseup;
                   10795: }
                   10796: 
1.1302    raeburn  10797: }
                   10798: 
1.691     raeburn  10799: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10800:     my ($courseid,@groups) = @_;
                   10801:     @groups = sort(@groups);
1.691     raeburn  10802:     return @groups;
                   10803: }
                   10804: 
1.395     albertel 10805: sub packages_tab_default {
                   10806:     my ($uri,$varname)=@_;
                   10807:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10808: 
                   10809:     my (@extension,@specifics,$do_default);
                   10810:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10811: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10812: 	if ($pack_type eq 'default') {
                   10813: 	    $do_default=1;
                   10814: 	} elsif ($pack_type eq 'extension') {
                   10815: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10816: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10817: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10818: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10819: 	}
                   10820:     }
                   10821:     # first look for a package that matches the requested part id
                   10822:     foreach my $package (@specifics) {
                   10823: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10824: 	next if ($pack_part ne $part);
                   10825: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10826: 	    return $packagetab{"$pack_type&$name&default"};
                   10827: 	}
                   10828:     }
                   10829:     # look for any possible matching non extension_ package
                   10830:     foreach my $package (@specifics) {
                   10831: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10832: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10833: 	    return $packagetab{"$pack_type&$name&default"};
                   10834: 	}
1.585     albertel 10835: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10836: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10837: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10838: 	}
                   10839:     }
1.738     albertel 10840:     # look for any posible extension_ match
                   10841:     foreach my $package (@extension) {
                   10842: 	my ($package,$pack_type)=@{$package};
                   10843: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10844: 	    return $packagetab{"$pack_type&$name&default"};
                   10845: 	}
                   10846: 	if (defined($packagetab{$package."&$name&default"})) {
                   10847: 	    return $packagetab{$package."&$name&default"};
                   10848: 	}
                   10849:     }
                   10850:     # look for a global default setting
                   10851:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10852: 	return $packagetab{"default&$name&default"};
                   10853:     }
1.395     albertel 10854:     return undef;
                   10855: }
                   10856: 
1.334     albertel 10857: sub add_prefix_and_part {
                   10858:     my ($prefix,$part)=@_;
                   10859:     my $keyroot;
                   10860:     if (defined($prefix) && $prefix !~ /^__/) {
                   10861: 	# prefix that has a part already
                   10862: 	$keyroot=$prefix;
                   10863:     } elsif (defined($prefix)) {
                   10864: 	# prefix that is missing a part
                   10865: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10866:     } else {
                   10867: 	# no prefix at all
                   10868: 	if (defined($part)) { $keyroot='_'.$part; }
                   10869:     }
                   10870:     return $keyroot;
                   10871: }
                   10872: 
1.71      www      10873: # ---------------------------------------------------------------- Get metadata
                   10874: 
1.599     albertel 10875: my %metaentry;
1.1070    www      10876: my %importedpartids;
1.71      www      10877: sub metadata {
1.176     www      10878:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10879:     $uri=&declutter($uri);
1.288     albertel 10880:     # if it is a non metadata possible uri return quickly
1.529     albertel 10881:     if (($uri eq '') || 
                   10882: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  10883: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  10884:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10885: 	return undef;
                   10886:     }
1.1261    raeburn  10887:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10888: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10889: 	return undef;
1.288     albertel 10890:     }
1.73      www      10891:     my $filename=$uri;
                   10892:     $uri=~s/\.meta$//;
1.172     www      10893: #
                   10894: # Is the metadata already cached?
1.177     www      10895: # Look at timestamp of caching
1.172     www      10896: # Everything is cached by the main uri, libraries are never directly cached
                   10897: #
1.428     albertel 10898:     if (!defined($liburi)) {
1.599     albertel 10899: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10900: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10901:     }
                   10902:     {
1.1069    www      10903: # Imported parts would go here
1.1070    www      10904:         my %importedids=();
                   10905:         my @origfileimportpartids=();
1.1069    www      10906:         my $importedparts=0;
1.172     www      10907: #
                   10908: # Is this a recursive call for a library?
                   10909: #
1.599     albertel 10910: #	if (! exists($metacache{$uri})) {
                   10911: #	    $metacache{$uri}={};
                   10912: #	}
1.924     albertel 10913: 	my $cachetime = 60*60;
1.171     www      10914:         if ($liburi) {
                   10915: 	    $liburi=&declutter($liburi);
                   10916:             $filename=$liburi;
1.401     bowersj2 10917:         } else {
1.599     albertel 10918: 	    &devalidate_cache_new('meta',$uri);
                   10919: 	    undef(%metaentry);
1.401     bowersj2 10920: 	}
1.140     www      10921:         my %metathesekeys=();
1.73      www      10922:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10923: 	my $metastring;
1.1140    www      10924: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10925: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10926: 	    $metastring = 
1.929     albertel 10927: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10928: 					  ('grade_target' => 'meta'));
                   10929: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10930: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10931:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10932: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10933: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10934: 	    $metastring=&getfile($file);
1.489     albertel 10935: 	}
1.208     albertel 10936:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10937:         my $token;
1.140     www      10938:         undef %metathesekeys;
1.71      www      10939:         while ($token=$parser->get_token) {
1.339     albertel 10940: 	    if ($token->[0] eq 'S') {
                   10941: 		if (defined($token->[2]->{'package'})) {
1.172     www      10942: #
                   10943: # This is a package - get package info
                   10944: #
1.339     albertel 10945: 		    my $package=$token->[2]->{'package'};
                   10946: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10947: 		    if (defined($token->[2]->{'id'})) { 
                   10948: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10949: 		    }
1.599     albertel 10950: 		    if ($metaentry{':packages'}) {
                   10951: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10952: 		    } else {
1.599     albertel 10953: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10954: 		    }
1.736     albertel 10955: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10956: 			my $part=$keyroot;
                   10957: 			$part=~s/^\_//;
1.736     albertel 10958: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10959: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10960: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10961: 			    # ignore package.tab specified default values
                   10962:                             # here &package_tab_default() will fetch those
                   10963: 			    if ($subp eq 'default') { next; }
1.736     albertel 10964: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10965: 			    my $unikey;
                   10966: 			    if ($pack =~ /_0$/) {
                   10967: 				$unikey='parameter_0_'.$name;
                   10968: 				$part=0;
                   10969: 			    } else {
                   10970: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10971: 			    }
1.339     albertel 10972: 			    if ($subp eq 'display') {
                   10973: 				$value.=' [Part: '.$part.']';
                   10974: 			    }
1.599     albertel 10975: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10976: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10977: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10978: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10979: 			    }
1.599     albertel 10980: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10981: 				$metaentry{':'.$unikey}=
                   10982: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10983: 			    }
1.339     albertel 10984: 			}
                   10985: 		    }
                   10986: 		} else {
1.172     www      10987: #
                   10988: # This is not a package - some other kind of start tag
1.339     albertel 10989: #
                   10990: 		    my $entry=$token->[1];
1.1068    www      10991: 		    my $unikey='';
1.175     www      10992: 
1.339     albertel 10993: 		    if ($entry eq 'import') {
1.175     www      10994: #
                   10995: # Importing a library here
1.339     albertel 10996: #
1.1067    www      10997:                         my $location=$parser->get_text('/import');
                   10998:                         my $dir=$filename;
                   10999:                         $dir=~s|[^/]*$||;
                   11000:                         $location=&filelocation($dir,$location);
1.1069    www      11001:                        
1.1068    www      11002:                         my $importmode=$token->[2]->{'importmode'};
                   11003:                         if ($importmode eq 'problem') {
1.1069    www      11004: # Import as problem/response
1.1068    www      11005:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11006:                         } elsif ($importmode eq 'part') {
                   11007: # Import as part(s)
1.1069    www      11008:                            $importedparts=1;
                   11009: # We need to get the original file and the imported file to get the part order correct
                   11010: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11011: # Load and inspect original file
1.1070    www      11012:                            if ($#origfileimportpartids<0) {
                   11013:                               undef(%importedpartids);
                   11014:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11015:                               my $origfile=&getfile($origfilelocation);
                   11016:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11017:                            }
                   11018: 
1.1069    www      11019: # Load and inspect imported file
                   11020:                            my $impfile=&getfile($location);
                   11021:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11022:                            if ($#impfilepartids>=0) {
                   11023: # This problem had parts
1.1070    www      11024:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11025:                            } else {
                   11026: # Importing by turning a single problem into a problem part
                   11027: # It gets the import-tags ID as part-ID
                   11028:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11029:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11030:                            }
1.1068    www      11031:                         } else {
                   11032: # Normal import
                   11033:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11034:                            if (defined($token->[2]->{'id'})) {
                   11035:                               $unikey.='_'.$token->[2]->{'id'};
                   11036:                            }
1.1067    www      11037:                         }
                   11038: 
1.339     albertel 11039: 			if ($depthcount<20) {
1.736     albertel 11040: 			    my $metadata = 
                   11041: 				&metadata($uri,'keys', $location,$unikey,
                   11042: 					  $depthcount+1);
                   11043: 			    foreach my $meta (split(',',$metadata)) {
                   11044: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11045: 				$metathesekeys{$meta}=1;
1.339     albertel 11046: 			    }
1.1068    www      11047: 			
                   11048:                         }
1.1067    www      11049: 		    } else {
                   11050: #
                   11051: # Not importing, some other kind of non-package, non-library start tag
                   11052: # 
                   11053:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11054:                         if (defined($token->[2]->{'id'})) {
                   11055:                             $unikey.='_'.$token->[2]->{'id'};
                   11056:                         }
1.339     albertel 11057: 			if (defined($token->[2]->{'name'})) { 
                   11058: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11059: 			}
                   11060: 			$metathesekeys{$unikey}=1;
1.736     albertel 11061: 			foreach my $param (@{$token->[3]}) {
                   11062: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11063: 				$token->[2]->{$param};
1.339     albertel 11064: 			}
                   11065: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11066: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11067: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11068: 		 # only ws inside the tag, and not in default, so use default
                   11069: 		 # as value
1.599     albertel 11070: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11071: 			} elsif ( $internaltext =~ /\S/ ) {
                   11072: 		  # something interesting inside the tag
                   11073: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11074: 			} else {
1.908     albertel 11075: 		  # no interesting values, don't set a default
1.339     albertel 11076: 			}
1.172     www      11077: # end of not-a-package not-a-library import
1.339     albertel 11078: 		    }
1.172     www      11079: # end of not-a-package start tag
1.339     albertel 11080: 		}
1.172     www      11081: # the next is the end of "start tag"
1.339     albertel 11082: 	    }
                   11083: 	}
1.483     albertel 11084: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11085: 	$extension = lc($extension);
                   11086: 	if ($extension eq 'htm') { $extension='html'; }
                   11087: 
1.737     albertel 11088: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11089: 	    #no specific packages #how's our extension
                   11090: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11091: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11092: 					 \%metathesekeys);
                   11093: 	}
1.883     albertel 11094: 
                   11095: 	if (!exists($metaentry{':packages'})
                   11096: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11097: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11098: 		#no specific packages well let's get default then
                   11099: 		if ($key!~/^default&/) { next; }
1.488     albertel 11100: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11101: 					     \%metathesekeys);
                   11102: 	    }
                   11103: 	}
1.338     www      11104: # are there custom rights to evaluate
1.599     albertel 11105: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11106: 
1.338     www      11107:     #
                   11108:     # Importing a rights file here
1.339     albertel 11109:     #
                   11110: 	    unless ($depthcount) {
1.599     albertel 11111: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11112: 		my $dir=$filename;
                   11113: 		$dir=~s|[^/]*$||;
                   11114: 		$location=&filelocation($dir,$location);
1.736     albertel 11115: 		my $rights_metadata =
                   11116: 		    &metadata($uri,'keys',$location,'_rights',
                   11117: 			      $depthcount+1);
                   11118: 		foreach my $rights (split(',',$rights_metadata)) {
                   11119: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11120: 		    $metathesekeys{$rights}=1;
1.339     albertel 11121: 		}
                   11122: 	    }
                   11123: 	}
1.737     albertel 11124: 	# uniqifiy package listing
                   11125: 	my %seen;
                   11126: 	my @uniq_packages =
                   11127: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11128: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11129: 
1.1070    www      11130:         if ($importedparts) {
                   11131: # We had imported parts and need to rebuild partorder
                   11132:            $metaentry{':partorder'}='';
                   11133:            $metathesekeys{'partorder'}=1;
                   11134:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11135:                if ($origfileimportpartids[$index] eq 'part') {
                   11136: # original part, part of the problem
                   11137:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11138:                } else {
                   11139: # we have imported parts at this position
                   11140:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11141:                }
                   11142:            }
                   11143:            $metaentry{':partorder'}=~s/^\,//;
                   11144:         }
                   11145: 
1.737     albertel 11146: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11147: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11148: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11149: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11150: # this is the end of "was not already recently cached
1.71      www      11151:     }
1.599     albertel 11152:     return $metaentry{':'.$what};
1.261     albertel 11153: }
                   11154: 
1.488     albertel 11155: sub metadata_create_package_def {
1.483     albertel 11156:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11157:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11158:     if ($subp eq 'default') { next; }
                   11159:     
1.599     albertel 11160:     if (defined($metaentry{':packages'})) {
                   11161: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11162:     } else {
1.599     albertel 11163: 	$metaentry{':packages'}=$package;
1.483     albertel 11164:     }
                   11165:     my $value=$packagetab{$key};
                   11166:     my $unikey;
                   11167:     $unikey='parameter_0_'.$name;
1.599     albertel 11168:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11169:     $$metathesekeys{$unikey}=1;
1.599     albertel 11170:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11171: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11172:     }
1.599     albertel 11173:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11174: 	$metaentry{':'.$unikey}=
                   11175: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11176:     }
                   11177: }
                   11178: 
1.261     albertel 11179: sub metadata_generate_part0 {
                   11180:     my ($metadata,$metacache,$uri) = @_;
                   11181:     my %allnames;
1.737     albertel 11182:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11183: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11184: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11185: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11186: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11187: 	    $allnames{$name}=$part;
                   11188: 	  }
                   11189: 	}
                   11190:     }
                   11191:     foreach my $name (keys(%allnames)) {
                   11192:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11193:       my $key=":parameter_0_$name";
1.261     albertel 11194:       $$metacache{"$key.part"}='0';
                   11195:       $$metacache{"$key.name"}=$name;
1.428     albertel 11196:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11197: 					   $allnames{$name}.'_'.$name.
                   11198: 					   '.type'};
1.428     albertel 11199:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11200: 			     '.display'};
1.644     www      11201:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11202:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11203:       $$metacache{"$key.display"}=$olddis;
                   11204:     }
1.71      www      11205: }
                   11206: 
1.764     albertel 11207: # ------------------------------------------------------ Devalidate title cache
                   11208: 
                   11209: sub devalidate_title_cache {
                   11210:     my ($url)=@_;
                   11211:     if (!$env{'request.course.id'}) { return; }
                   11212:     my $symb=&symbread($url);
                   11213:     if (!$symb) { return; }
                   11214:     my $key=$env{'request.course.id'}."\0".$symb;
                   11215:     &devalidate_cache_new('title',$key);
                   11216: }
                   11217: 
1.1014    droeschl 11218: # ------------------------------------------------- Get the title of a course
                   11219: 
                   11220: sub current_course_title {
                   11221:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11222: }
1.301     www      11223: # ------------------------------------------------- Get the title of a resource
                   11224: 
                   11225: sub gettitle {
                   11226:     my $urlsymb=shift;
                   11227:     my $symb=&symbread($urlsymb);
1.534     albertel 11228:     if ($symb) {
1.620     albertel 11229: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11230: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11231: 	if (defined($cached)) { 
                   11232: 	    return $result;
                   11233: 	}
1.534     albertel 11234: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11235: 	my $title='';
1.907     albertel 11236: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11237: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11238: 	} else {
                   11239: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11240: 		    &GDBM_READER(),0640)) {
                   11241: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11242: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11243: 		untie(%bighash);
                   11244: 	    }
1.534     albertel 11245: 	}
                   11246: 	$title=~s/\&colon\;/\:/gs;
                   11247: 	if ($title) {
1.1159    www      11248: # Remember both $symb and $title for dynamic metadata
                   11249:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11250:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11251: # Cache this title and then return it
1.599     albertel 11252: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11253: 	}
                   11254: 	$urlsymb=$url;
                   11255:     }
                   11256:     my $title=&metadata($urlsymb,'title');
                   11257:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11258:     return $title;
1.301     www      11259: }
1.613     albertel 11260: 
1.614     albertel 11261: sub get_slot {
                   11262:     my ($which,$cnum,$cdom)=@_;
                   11263:     if (!$cnum || !$cdom) {
1.790     albertel 11264: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11265: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11266: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11267:     }
1.703     albertel 11268:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11269:     my %slotinfo;
                   11270:     if (exists($remembered{$key})) {
                   11271: 	$slotinfo{$which} = $remembered{$key};
                   11272:     } else {
                   11273: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11274: 	&Apache::lonhomework::showhash(%slotinfo);
                   11275: 	my ($tmp)=keys(%slotinfo);
                   11276: 	if ($tmp=~/^error:/) { return (); }
                   11277: 	$remembered{$key} = $slotinfo{$which};
                   11278:     }
1.616     albertel 11279:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11280: 	return %{$slotinfo{$which}};
                   11281:     }
                   11282:     return $slotinfo{$which};
1.614     albertel 11283: }
1.1150    raeburn  11284: 
                   11285: sub get_reservable_slots {
                   11286:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11287:     my $now = time;
                   11288:     my $reservable_info;
                   11289:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11290:     if (exists($remembered{$key})) {
                   11291:         $reservable_info = $remembered{$key};
                   11292:     } else {
                   11293:         my %resv;
                   11294:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11295:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11296:         $reservable_info = \%resv;
                   11297:         $remembered{$key} = $reservable_info;
                   11298:     }
                   11299:     return $reservable_info;
                   11300: }
                   11301: 
                   11302: sub get_course_slots {
                   11303:     my ($cnum,$cdom) = @_;
                   11304:     my $hashid=$cnum.':'.$cdom;
                   11305:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11306:     if (defined($cached)) {
                   11307:         if (ref($result) eq 'HASH') {
                   11308:             return %{$result};
                   11309:         }
                   11310:     } else {
                   11311:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11312:         my ($tmp) = keys(%slots);
                   11313:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11314:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11315:             return %slots;
                   11316:         }
                   11317:     }
                   11318:     return;
                   11319: }
                   11320: 
                   11321: sub devalidate_slots_cache {
                   11322:     my ($cnum,$cdom)=@_;
                   11323:     my $hashid=$cnum.':'.$cdom;
                   11324:     &devalidate_cache_new('allslots',$hashid);
                   11325: }
                   11326: 
1.1181    raeburn  11327: sub get_coursechange {
                   11328:     my ($cdom,$cnum) = @_;
                   11329:     if ($cdom eq '' || $cnum eq '') {
                   11330:         return unless ($env{'request.course.id'});
                   11331:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11332:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11333:     }
                   11334:     my $hashid=$cdom.'_'.$cnum;
                   11335:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11336:     if ((defined($cached)) && ($change ne '')) {
                   11337:         return $change;
                   11338:     } else {
                   11339:         my %crshash;
                   11340:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11341:         if ($crshash{'internal.contentchange'} eq '') {
                   11342:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11343:             if ($change eq '') {
                   11344:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11345:                 $change = $crshash{'internal.created'};
                   11346:             }
                   11347:         } else {
                   11348:             $change = $crshash{'internal.contentchange'};
                   11349:         }
                   11350:         my $cachetime = 600;
                   11351:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11352:     }
                   11353:     return $change;
                   11354: }
                   11355: 
                   11356: sub devalidate_coursechange_cache {
                   11357:     my ($cnum,$cdom)=@_;
                   11358:     my $hashid=$cnum.':'.$cdom;
                   11359:     &devalidate_cache_new('crschange',$hashid);
                   11360: }
                   11361: 
1.31      www      11362: # ------------------------------------------------- Update symbolic store links
                   11363: 
                   11364: sub symblist {
                   11365:     my ($mapname,%newhash)=@_;
1.438     www      11366:     $mapname=&deversion(&declutter($mapname));
1.31      www      11367:     my %hash;
1.620     albertel 11368:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11369:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11370:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11371: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11372: 		next if ($url eq 'last_known'
                   11373: 			 && $env{'form.no_update_last_known'});
                   11374: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11375: 						    $newhash{$url}->[1],
                   11376: 						    $newhash{$url}->[0]);
1.191     harris41 11377:             }
1.31      www      11378:             if (untie(%hash)) {
                   11379: 		return 'ok';
                   11380:             }
                   11381:         }
                   11382:     }
                   11383:     return 'error';
1.212     www      11384: }
                   11385: 
                   11386: # --------------------------------------------------------------- Verify a symb
                   11387: 
                   11388: sub symbverify {
1.1190    raeburn  11389:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11390:     my $thisfn=$thisurl;
1.439     www      11391:     $thisfn=&declutter($thisfn);
1.215     www      11392: # direct jump to resource in page or to a sequence - will construct own symbs
                   11393:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11394: # check URL part
1.409     www      11395:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11396: 
1.431     www      11397:     unless ($url eq $thisfn) { return 0; }
1.213     www      11398: 
1.216     www      11399:     $symb=&symbclean($symb);
1.510     www      11400:     $thisurl=&deversion($thisurl);
1.439     www      11401:     $thisfn=&deversion($thisfn);
1.213     www      11402: 
                   11403:     my %bighash;
                   11404:     my $okay=0;
1.431     www      11405: 
1.620     albertel 11406:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11407:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11408:         my $noclutter;
1.1032    raeburn  11409:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11410:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11411:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11412:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11413:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11414:                 $noclutter = 1;
                   11415:             }
                   11416:         }
                   11417:         my $ids;
                   11418:         if ($noclutter) {
                   11419:             $ids=$bighash{'ids_'.$thisurl};
                   11420:         } else {
                   11421:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11422:         }
1.1102    raeburn  11423:         unless ($ids) {
                   11424:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11425:             $ids=$bighash{$idkey};
1.216     www      11426:         }
                   11427:         if ($ids) {
                   11428: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11429:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11430:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11431:             }
1.800     albertel 11432: 	    foreach my $id (split(/\,/,$ids)) {
                   11433: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11434:                if (
                   11435:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11436:    eq $symb) {
                   11437:                    if (ref($encstate)) {
                   11438:                        $$encstate = $bighash{'encrypted_'.$id};
                   11439:                    }
1.620     albertel 11440: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11441: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11442:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11443: 		       $okay=1;
1.1202    raeburn  11444:                        last;
1.582     albertel 11445: 		   }
                   11446: 	       }
1.216     www      11447: 	   }
                   11448:         }
1.213     www      11449: 	untie(%bighash);
                   11450:     }
                   11451:     return $okay;
1.31      www      11452: }
                   11453: 
1.210     www      11454: # --------------------------------------------------------------- Clean-up symb
                   11455: 
                   11456: sub symbclean {
                   11457:     my $symb=shift;
1.568     albertel 11458:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11459: # remove version from map
                   11460:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11461: 
1.210     www      11462: # remove version from URL
                   11463:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11464: 
1.507     www      11465: # remove wrapper
                   11466: 
1.510     www      11467:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11468:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11469:     return $symb;
1.409     www      11470: }
                   11471: 
                   11472: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11473: 
                   11474: sub encode_symb {
                   11475:     my ($map,$resid,$url)=@_;
                   11476:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11477: }
1.409     www      11478: 
                   11479: sub decode_symb {
1.568     albertel 11480:     my $symb=shift;
                   11481:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11482:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11483:     return (&fixversion($map),$resid,&fixversion($url));
                   11484: }
                   11485: 
                   11486: sub fixversion {
                   11487:     my $fn=shift;
1.609     banghart 11488:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11489:     my %bighash;
                   11490:     my $uri=&clutter($fn);
1.620     albertel 11491:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11492: # is this cached?
1.599     albertel 11493:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11494:     if (defined($cached)) { return $result; }
                   11495: # unfortunately not cached, or expired
1.620     albertel 11496:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11497: 	    &GDBM_READER(),0640)) {
                   11498:  	if ($bighash{'version_'.$uri}) {
                   11499:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11500:  	    unless (($version eq 'mostrecent') || 
                   11501: 		    ($version==&getversion($uri))) {
1.440     www      11502:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11503:  	    }
                   11504:  	}
                   11505:  	untie %bighash;
1.413     www      11506:     }
1.599     albertel 11507:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11508: }
                   11509: 
                   11510: sub deversion {
                   11511:     my $url=shift;
                   11512:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11513:     return $url;
1.210     www      11514: }
                   11515: 
1.31      www      11516: # ------------------------------------------------------ Return symb list entry
                   11517: 
                   11518: sub symbread {
1.1282    raeburn  11519:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11520:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11521:     if (defined($env{$cache_str})) {
                   11522:         if ($ignorecachednull) {
                   11523:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11524:         } else {
                   11525:             return $env{$cache_str};
                   11526:         }
                   11527:     }
1.242     www      11528: # no filename provided? try from environment
1.1265    raeburn  11529:     unless ($thisfn) {
1.620     albertel 11530:         if ($env{'request.symb'}) {
                   11531: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11532: 	}
1.620     albertel 11533: 	$thisfn=$env{'request.filename'};
1.44      www      11534:     }
1.569     albertel 11535:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11536: # is that filename actually a symb? Verify, clean, and return
                   11537:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11538: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11539: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11540: 	}
1.242     www      11541:     }
1.44      www      11542:     $thisfn=declutter($thisfn);
1.31      www      11543:     my %hash;
1.37      www      11544:     my %bighash;
                   11545:     my $syval='';
1.620     albertel 11546:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11547:         my $targetfn = $thisfn;
1.609     banghart 11548:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11549:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11550:         }
1.687     albertel 11551: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11552: 	    $targetfn=$1;
                   11553: 	}
1.620     albertel 11554:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11555:                       &GDBM_READER(),0640)) {
1.481     raeburn  11556: 	    $syval=$hash{$targetfn};
1.37      www      11557:             untie(%hash);
                   11558:         }
                   11559: # ---------------------------------------------------------- There was an entry
                   11560:         if ($syval) {
1.601     albertel 11561: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11562: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11563: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11564: 		    #return $env{$cache_str}='';
1.601     albertel 11565: 		#}    
                   11566: 		#$syval.=$1;
                   11567: 	    #}
1.37      www      11568:         } else {
                   11569: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11570:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11571:                             &GDBM_READER(),0640)) {
1.37      www      11572: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11573:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11574:               unless ($ids) { 
                   11575:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11576:               }
                   11577:               unless ($ids) {
                   11578: # alias?
                   11579: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11580:               }
1.37      www      11581:               if ($ids) {
                   11582: # ------------------------------------------------------------------- Has ID(s)
                   11583:                  my @possibilities=split(/\,/,$ids);
1.39      www      11584:                  if ($#possibilities==0) {
                   11585: # ----------------------------------------------- There is only one possibility
1.37      www      11586: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11587: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11588: 						    $resid,$thisfn);
1.1282    raeburn  11589:                      if (ref($possibles) eq 'HASH') {
                   11590:                          $possibles->{$syval} = 1;    
                   11591:                      }
                   11592:                      if ($checkforblock) {
                   11593:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11594:                          if (@blockers) {
                   11595:                              $syval = '';
                   11596:                              return;
                   11597:                          }
                   11598:                      }
                   11599:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11600: # ------------------------------------------ There is more than one possibility
                   11601:                      my $realpossible=0;
1.800     albertel 11602:                      foreach my $id (@possibilities) {
                   11603: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11604:                          my $canaccess;
                   11605:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11606:                              $canaccess = 1;
                   11607:                          } else { 
                   11608:                              $canaccess = &allowed('bre',$file);
                   11609:                          }
                   11610:                          if ($canaccess) {
                   11611:          		     my ($mapid,$resid)=split(/\./,$id);
                   11612:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11613:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11614: 						             $resid,$thisfn);
                   11615:                                  if (ref($possibles) eq 'HASH') {
                   11616:                                      $possibles->{$syval} = 1;
                   11617:                                  }
                   11618:                                  if ($checkforblock) {
                   11619:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11620:                                      unless (@blockers > 0) {
                   11621:                                          $syval = $poss_syval;
                   11622:                                          $realpossible++;
                   11623:                                      }
                   11624:                                  } else {
                   11625:                                      $syval = $poss_syval;
                   11626:                                      $realpossible++;
                   11627:                                  }
                   11628:                              }
1.39      www      11629: 			 }
1.191     harris41 11630:                      }
1.39      www      11631: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11632:                  } else {
                   11633:                      $syval='';
1.37      www      11634:                  }
                   11635: 	      }
1.1282    raeburn  11636:               untie(%bighash);
1.481     raeburn  11637:            }
1.31      www      11638:         }
1.62      www      11639:         if ($syval) {
1.620     albertel 11640: 	    return $env{$cache_str}=$syval;
1.62      www      11641:         }
1.31      www      11642:     }
1.949     raeburn  11643:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11644:     return $env{$cache_str}='';
1.31      www      11645: }
                   11646: 
                   11647: # ---------------------------------------------------------- Return random seed
                   11648: 
1.32      www      11649: sub numval {
                   11650:     my $txt=shift;
                   11651:     $txt=~tr/A-J/0-9/;
                   11652:     $txt=~tr/a-j/0-9/;
                   11653:     $txt=~tr/K-T/0-9/;
                   11654:     $txt=~tr/k-t/0-9/;
                   11655:     $txt=~tr/U-Z/0-5/;
                   11656:     $txt=~tr/u-z/0-5/;
                   11657:     $txt=~s/\D//g;
1.564     albertel 11658:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11659:     return int($txt);
1.368     albertel 11660: }
                   11661: 
1.484     albertel 11662: sub numval2 {
                   11663:     my $txt=shift;
                   11664:     $txt=~tr/A-J/0-9/;
                   11665:     $txt=~tr/a-j/0-9/;
                   11666:     $txt=~tr/K-T/0-9/;
                   11667:     $txt=~tr/k-t/0-9/;
                   11668:     $txt=~tr/U-Z/0-5/;
                   11669:     $txt=~tr/u-z/0-5/;
                   11670:     $txt=~s/\D//g;
                   11671:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11672:     my $total;
                   11673:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11674:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11675:     return int($total);
                   11676: }
                   11677: 
1.575     albertel 11678: sub numval3 {
                   11679:     use integer;
                   11680:     my $txt=shift;
                   11681:     $txt=~tr/A-J/0-9/;
                   11682:     $txt=~tr/a-j/0-9/;
                   11683:     $txt=~tr/K-T/0-9/;
                   11684:     $txt=~tr/k-t/0-9/;
                   11685:     $txt=~tr/U-Z/0-5/;
                   11686:     $txt=~tr/u-z/0-5/;
                   11687:     $txt=~s/\D//g;
                   11688:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11689:     my $total;
                   11690:     foreach my $val (@txts) { $total+=$val; }
                   11691:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11692:     return $total;
                   11693: }
                   11694: 
1.675     albertel 11695: sub digest {
                   11696:     my ($data)=@_;
                   11697:     my $digest=&Digest::MD5::md5($data);
                   11698:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11699:     my ($e,$f);
                   11700:     {
                   11701:         use integer;
                   11702:         $e=($a+$b);
                   11703:         $f=($c+$d);
                   11704:         if ($_64bit) {
                   11705:             $e=(($e<<32)>>32);
                   11706:             $f=(($f<<32)>>32);
                   11707:         }
                   11708:     }
                   11709:     if (wantarray) {
                   11710: 	return ($e,$f);
                   11711:     } else {
                   11712: 	my $g;
                   11713: 	{
                   11714: 	    use integer;
                   11715: 	    $g=($e+$f);
                   11716: 	    if ($_64bit) {
                   11717: 		$g=(($g<<32)>>32);
                   11718: 	    }
                   11719: 	}
                   11720: 	return $g;
                   11721:     }
                   11722: }
                   11723: 
1.368     albertel 11724: sub latest_rnd_algorithm_id {
1.675     albertel 11725:     return '64bit5';
1.366     albertel 11726: }
1.32      www      11727: 
1.503     albertel 11728: sub get_rand_alg {
                   11729:     my ($courseid)=@_;
1.790     albertel 11730:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11731:     if ($courseid) {
1.620     albertel 11732: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11733:     }
                   11734:     return &latest_rnd_algorithm_id();
                   11735: }
                   11736: 
1.562     albertel 11737: sub validCODE {
                   11738:     my ($CODE)=@_;
                   11739:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11740:     return 0;
                   11741: }
                   11742: 
1.491     albertel 11743: sub getCODE {
1.620     albertel 11744:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11745:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11746: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11747: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11748: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11749:     }
                   11750:     return undef;
                   11751: }
1.1133    foxr     11752: #
                   11753: #  Determines the random seed for a specific context:
                   11754: #
                   11755: # parameters:
                   11756: #   symb      - in course context the symb for the seed.
                   11757: #   course_id - The course id of the form domain_coursenum.
                   11758: #   domain    - Domain for the user.
                   11759: #   course    - Course for the user.
                   11760: #   cenv      - environment of the course.
                   11761: #
                   11762: # NOTE:
                   11763: #   All parameters are picked out of the environment if missing
                   11764: #   or not defined.
                   11765: #   If a symb cannot be determined the current time is used instead.
                   11766: #
                   11767: #  For a given well defined symb, courside, domain, username,
                   11768: #  and course environment, the seed is reproducible.
                   11769: #
1.31      www      11770: sub rndseed {
1.1133    foxr     11771:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11772:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11773:     if (!defined($symb)) {
1.366     albertel 11774: 	unless ($symb=$wsymb) { return time; }
                   11775:     }
1.1146    foxr     11776:     if (!defined $courseid) { 
                   11777: 	$courseid=$wcourseid; 
                   11778:     }
                   11779:     if (!defined $domain) { $domain=$wdomain; }
                   11780:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11781: 
                   11782:     my $which;
                   11783:     if (defined($cenv->{'rndseed'})) {
                   11784: 	$which = $cenv->{'rndseed'};
                   11785:     } else {
                   11786: 	$which =&get_rand_alg($courseid);
                   11787:     }
1.491     albertel 11788:     if (defined(&getCODE())) {
1.1133    foxr     11789: 
1.675     albertel 11790: 	if ($which eq '64bit5') {
                   11791: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11792: 	} elsif ($which eq '64bit4') {
1.575     albertel 11793: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11794: 	} else {
                   11795: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11796: 	}
1.675     albertel 11797:     } elsif ($which eq '64bit5') {
                   11798: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11799:     } elsif ($which eq '64bit4') {
                   11800: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11801:     } elsif ($which eq '64bit3') {
                   11802: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11803:     } elsif ($which eq '64bit2') {
                   11804: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11805:     } elsif ($which eq '64bit') {
                   11806: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11807:     }
                   11808:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11809: }
                   11810: 
                   11811: sub rndseed_32bit {
                   11812:     my ($symb,$courseid,$domain,$username)=@_;
                   11813:     {
                   11814: 	use integer;
                   11815: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11816: 	my $symbseed=numval($symb) << 22;
                   11817: 	my $namechck=unpack("%32C*",$username) << 17;
                   11818: 	my $nameseed=numval($username) << 12;
                   11819: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11820: 	my $courseseed=unpack("%32C*",$courseid);
                   11821: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11822: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11823: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11824: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11825: 	return $num;
                   11826:     }
                   11827: }
                   11828: 
                   11829: sub rndseed_64bit {
                   11830:     my ($symb,$courseid,$domain,$username)=@_;
                   11831:     {
                   11832: 	use integer;
                   11833: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11834: 	my $symbseed=numval($symb) << 10;
                   11835: 	my $namechck=unpack("%32S*",$username);
                   11836: 	
                   11837: 	my $nameseed=numval($username) << 21;
                   11838: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11839: 	my $courseseed=unpack("%32S*",$courseid);
                   11840: 	
                   11841: 	my $num1=$symbchck+$symbseed+$namechck;
                   11842: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11843: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11844: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11845: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11846: 	return "$num1,$num2";
1.155     albertel 11847:     }
1.366     albertel 11848: }
                   11849: 
1.443     albertel 11850: sub rndseed_64bit2 {
                   11851:     my ($symb,$courseid,$domain,$username)=@_;
                   11852:     {
                   11853: 	use integer;
                   11854: 	# strings need to be an even # of cahracters long, it it is odd the
                   11855:         # last characters gets thrown away
                   11856: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11857: 	my $symbseed=numval($symb) << 10;
                   11858: 	my $namechck=unpack("%32S*",$username.' ');
                   11859: 	
                   11860: 	my $nameseed=numval($username) << 21;
1.501     albertel 11861: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11862: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11863: 	
                   11864: 	my $num1=$symbchck+$symbseed+$namechck;
                   11865: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11866: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11867: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11868: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11869: 	return "$num1,$num2";
                   11870:     }
                   11871: }
                   11872: 
                   11873: sub rndseed_64bit3 {
                   11874:     my ($symb,$courseid,$domain,$username)=@_;
                   11875:     {
                   11876: 	use integer;
                   11877: 	# strings need to be an even # of cahracters long, it it is odd the
                   11878:         # last characters gets thrown away
                   11879: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11880: 	my $symbseed=numval2($symb) << 10;
                   11881: 	my $namechck=unpack("%32S*",$username.' ');
                   11882: 	
                   11883: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11884: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11885: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11886: 	
                   11887: 	my $num1=$symbchck+$symbseed+$namechck;
                   11888: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11889: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11890: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11891: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11892: 	
1.503     albertel 11893: 	return "$num1:$num2";
1.443     albertel 11894:     }
                   11895: }
                   11896: 
1.575     albertel 11897: sub rndseed_64bit4 {
                   11898:     my ($symb,$courseid,$domain,$username)=@_;
                   11899:     {
                   11900: 	use integer;
                   11901: 	# strings need to be an even # of cahracters long, it it is odd the
                   11902:         # last characters gets thrown away
                   11903: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11904: 	my $symbseed=numval3($symb) << 10;
                   11905: 	my $namechck=unpack("%32S*",$username.' ');
                   11906: 	
                   11907: 	my $nameseed=numval3($username) << 21;
                   11908: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11909: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11910: 	
                   11911: 	my $num1=$symbchck+$symbseed+$namechck;
                   11912: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11913: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11914: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11915: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11916: 	
1.575     albertel 11917: 	return "$num1:$num2";
                   11918:     }
                   11919: }
                   11920: 
1.675     albertel 11921: sub rndseed_64bit5 {
                   11922:     my ($symb,$courseid,$domain,$username)=@_;
                   11923:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11924:     return "$num1:$num2";
                   11925: }
                   11926: 
1.366     albertel 11927: sub rndseed_CODE_64bit {
                   11928:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11929:     {
1.366     albertel 11930: 	use integer;
1.443     albertel 11931: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11932: 	my $symbseed=numval2($symb);
1.491     albertel 11933: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11934: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11935: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11936: 	my $num1=$symbseed+$CODEchck;
                   11937: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11938: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11939: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11940: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11941: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11942: 	return "$num1:$num2";
1.366     albertel 11943:     }
                   11944: }
                   11945: 
1.575     albertel 11946: sub rndseed_CODE_64bit4 {
                   11947:     my ($symb,$courseid,$domain,$username)=@_;
                   11948:     {
                   11949: 	use integer;
                   11950: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11951: 	my $symbseed=numval3($symb);
                   11952: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11953: 	my $CODEseed=numval3(&getCODE());
                   11954: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11955: 	my $num1=$symbseed+$CODEchck;
                   11956: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11957: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11958: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11959: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11960: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11961: 	return "$num1:$num2";
                   11962:     }
                   11963: }
                   11964: 
1.675     albertel 11965: sub rndseed_CODE_64bit5 {
                   11966:     my ($symb,$courseid,$domain,$username)=@_;
                   11967:     my $code = &getCODE();
                   11968:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11969:     return "$num1:$num2";
                   11970: }
                   11971: 
1.366     albertel 11972: sub setup_random_from_rndseed {
                   11973:     my ($rndseed)=@_;
1.503     albertel 11974:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11975:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11976:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11977:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11978:         } else {
                   11979:             &Math::Random::random_set_seed($num1,$num2);
                   11980:         }
1.366     albertel 11981:     } else {
                   11982: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11983:     }
1.36      albertel 11984: }
                   11985: 
1.474     albertel 11986: sub latest_receipt_algorithm_id {
1.835     albertel 11987:     return 'receipt3';
1.474     albertel 11988: }
                   11989: 
1.480     www      11990: sub recunique {
                   11991:     my $fucourseid=shift;
                   11992:     my $unique;
1.835     albertel 11993:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11994: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11995: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11996:     } else {
                   11997: 	$unique=$perlvar{'lonReceipt'};
                   11998:     }
                   11999:     return unpack("%32C*",$unique);
                   12000: }
                   12001: 
                   12002: sub recprefix {
                   12003:     my $fucourseid=shift;
                   12004:     my $prefix;
1.835     albertel 12005:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12006: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12007: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12008:     } else {
                   12009: 	$prefix=$perlvar{'lonHostID'};
                   12010:     }
                   12011:     return unpack("%32C*",$prefix);
                   12012: }
                   12013: 
1.76      www      12014: sub ireceipt {
1.474     albertel 12015:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12016: 
                   12017:     my $return =&recprefix($fucourseid).'-';
                   12018: 
                   12019:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12020: 	$env{'request.state'} eq 'construct') {
                   12021: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12022: 	return $return;
                   12023:     }
                   12024: 
1.76      www      12025:     my $cuname=unpack("%32C*",$funame);
                   12026:     my $cudom=unpack("%32C*",$fudom);
                   12027:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12028:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12029:     my $cunique=&recunique($fucourseid);
1.474     albertel 12030:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12031:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12032: 
1.790     albertel 12033: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12034: 			       
                   12035: 	$return.= ($cunique%$cuname+
                   12036: 		   $cunique%$cudom+
                   12037: 		   $cusymb%$cuname+
                   12038: 		   $cusymb%$cudom+
                   12039: 		   $cucourseid%$cuname+
                   12040: 		   $cucourseid%$cudom+
                   12041: 		   $cpart%$cuname+
                   12042: 		   $cpart%$cudom);
                   12043:     } else {
                   12044: 	$return.= ($cunique%$cuname+
                   12045: 		   $cunique%$cudom+
                   12046: 		   $cusymb%$cuname+
                   12047: 		   $cusymb%$cudom+
                   12048: 		   $cucourseid%$cuname+
                   12049: 		   $cucourseid%$cudom);
                   12050:     }
                   12051:     return $return;
1.76      www      12052: }
                   12053: 
                   12054: sub receipt {
1.474     albertel 12055:     my ($part)=@_;
1.790     albertel 12056:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12057:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12058: }
1.260     ng       12059: 
1.790     albertel 12060: sub whichuser {
                   12061:     my ($passedsymb)=@_;
                   12062:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12063:     if (defined($env{'form.grade_symb'})) {
                   12064: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12065: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12066: 	if (!$allowed &&
                   12067: 	    exists($env{'request.course.sec'}) &&
                   12068: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12069: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12070: 			      '/'.$env{'request.course.sec'});
                   12071: 	}
                   12072: 	if ($allowed) {
                   12073: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12074: 	    $courseid=$tmp_courseid;
                   12075: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12076: 	    ($name)=&get_env_multiple('form.grade_username');
                   12077: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12078: 	}
                   12079:     }
                   12080:     if (!$passedsymb) {
                   12081: 	$symb=&symbread();
                   12082:     } else {
                   12083: 	$symb=$passedsymb;
                   12084:     }
                   12085:     $courseid=$env{'request.course.id'};
                   12086:     $domain=$env{'user.domain'};
                   12087:     $name=$env{'user.name'};
                   12088:     if ($name eq 'public' && $domain eq 'public') {
                   12089: 	if (!defined($env{'form.username'})) {
                   12090: 	    $env{'form.username'}.=time.rand(10000000);
                   12091: 	}
                   12092: 	$name.=$env{'form.username'};
                   12093:     }
                   12094:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12095: 
                   12096: }
                   12097: 
1.36      albertel 12098: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12099: # returns either the contents of the file or 
                   12100: # -1 if the file doesn't exist
1.481     raeburn  12101: #
                   12102: # if the target is a file that was uploaded via DOCS, 
                   12103: # a check will be made to see if a current copy exists on the local server,
                   12104: # if it does this will be served, otherwise a copy will be retrieved from
                   12105: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12106: # the local server.   
1.472     albertel 12107: 
1.36      albertel 12108: sub getfile {
1.538     albertel 12109:     my ($file) = @_;
1.609     banghart 12110:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12111:     &repcopy($file);
                   12112:     return &readfile($file);
                   12113: }
                   12114: 
                   12115: sub repcopy_userfile {
                   12116:     my ($file)=@_;
1.1142    raeburn  12117:     my $londocroot = $perlvar{'lonDocRoot'};
                   12118:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12119:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12120:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12121: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12122:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12123:     if (-e "$file") {
1.828     www      12124: # we already have a local copy, check it out
1.538     albertel 12125: 	my @fileinfo = stat($file);
1.828     www      12126: 	my $rtncode;
                   12127: 	my $info;
1.538     albertel 12128: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12129: 	if ($lwpresp ne 'ok') {
1.828     www      12130: # there is no such file anymore, even though we had a local copy
1.482     albertel 12131: 	    if ($rtncode eq '404') {
1.538     albertel 12132: 		unlink($file);
1.482     albertel 12133: 	    }
                   12134: 	    return -1;
                   12135: 	}
                   12136: 	if ($info < $fileinfo[9]) {
1.828     www      12137: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12138: 	    return 'ok';
1.828     www      12139: 	} else {
                   12140: # the file is outdated, get rid of it
                   12141: 	    unlink($file);
1.482     albertel 12142: 	}
1.828     www      12143:     }
                   12144: # one way or the other, at this point, we don't have the file
                   12145: # construct the correct path for the file
                   12146:     my @parts = ($cdom,$cnum); 
                   12147:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12148: 	push @parts, split(/\//,$1);
                   12149:     }
                   12150:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12151:     foreach my $part (@parts) {
                   12152: 	$path .= '/'.$part;
                   12153: 	if (!-e $path) {
                   12154: 	    mkdir($path,0770);
1.482     albertel 12155: 	}
                   12156:     }
1.828     www      12157: # now the path exists for sure
                   12158: # get a user agent
                   12159:     my $ua=new LWP::UserAgent;
                   12160:     my $transferfile=$file.'.in.transfer';
                   12161: # FIXME: this should flock
                   12162:     if (-e $transferfile) { return 'ok'; }
                   12163:     my $request;
                   12164:     $uri=~s/^\///;
1.980     raeburn  12165:     my $homeserver = &homeserver($cnum,$cdom);
                   12166:     my $protocol = $protocol{$homeserver};
                   12167:     $protocol = 'http' if ($protocol ne 'https');
                   12168:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12169:     my $response=$ua->request($request,$transferfile);
                   12170: # did it work?
                   12171:     if ($response->is_error()) {
                   12172: 	unlink($transferfile);
                   12173: 	&logthis("Userfile repcopy failed for $uri");
                   12174: 	return -1;
                   12175:     }
                   12176: # worked, rename the transfer file
                   12177:     rename($transferfile,$file);
1.607     raeburn  12178:     return 'ok';
1.481     raeburn  12179: }
                   12180: 
1.517     albertel 12181: sub tokenwrapper {
                   12182:     my $uri=shift;
1.980     raeburn  12183:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12184:     $uri=~s|^/||;
1.620     albertel 12185:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12186:     my $token=$1;
1.552     albertel 12187:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12188:     if ($udom && $uname && $file) {
                   12189: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12190:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12191:         my $homeserver = &homeserver($uname,$udom);
                   12192:         my $protocol = $protocol{$homeserver};
                   12193:         $protocol = 'http' if ($protocol ne 'https');
                   12194:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12195:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12196:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12197:     } else {
                   12198:         return '/adm/notfound.html';
                   12199:     }
                   12200: }
                   12201: 
1.828     www      12202: # call with reqtype HEAD: get last modification time
                   12203: # call with reqtype GET: get the file contents
                   12204: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12205: #
1.481     raeburn  12206: sub getuploaded {
                   12207:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12208:     $uri=~s/^\///;
1.980     raeburn  12209:     my $homeserver = &homeserver($cnum,$cdom);
                   12210:     my $protocol = $protocol{$homeserver};
                   12211:     $protocol = 'http' if ($protocol ne 'https');
                   12212:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12213:     my $ua=new LWP::UserAgent;
                   12214:     my $request=new HTTP::Request($reqtype,$uri);
                   12215:     my $response=$ua->request($request);
                   12216:     $$rtncode = $response->code;
1.482     albertel 12217:     if (! $response->is_success()) {
                   12218: 	return 'failed';
                   12219:     }      
                   12220:     if ($reqtype eq 'HEAD') {
1.486     www      12221: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12222:     } elsif ($reqtype eq 'GET') {
                   12223: 	$$info = $response->content;
1.472     albertel 12224:     }
1.482     albertel 12225:     return 'ok';
1.36      albertel 12226: }
                   12227: 
1.481     raeburn  12228: sub readfile {
                   12229:     my $file = shift;
                   12230:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12231:     my $fh;
                   12232:     open($fh,"<$file");
                   12233:     my $a='';
1.800     albertel 12234:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12235:     return $a;
                   12236: }
                   12237: 
1.36      albertel 12238: sub filelocation {
1.590     banghart 12239:     my ($dir,$file) = @_;
                   12240:     my $location;
                   12241:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12242: 
                   12243:     if ($file =~ m-^/adm/-) {
                   12244: 	$file=~s-^/adm/wrapper/-/-;
                   12245: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12246:     }
1.882     albertel 12247: 
1.1139    www      12248:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12249:         $location = $file;
1.609     banghart 12250:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12251:         my ($udom,$uname,$filename)=
1.811     albertel 12252:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12253:         my $home=&homeserver($uname,$udom);
                   12254:         my $is_me=0;
                   12255:         my @ids=&current_machine_ids();
                   12256:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12257:         if ($is_me) {
1.1117    foxr     12258:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12259:         } else {
                   12260:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12261:   	      $udom.'/'.$uname.'/'.$filename;
                   12262:         }
1.882     albertel 12263:     } elsif ($file =~ m-^/adm/-) {
                   12264: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12265:     } else {
                   12266:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12267:         $file=~s:^/(res|priv)/:/:;
                   12268:         my $space=$1;
1.590     banghart 12269:         if ( !( $file =~ m:^/:) ) {
                   12270:             $location = $dir. '/'.$file;
                   12271:         } else {
1.1142    raeburn  12272:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12273:         }
1.59      albertel 12274:     }
1.590     banghart 12275:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12276:     while ($location=~m{/\.\./}) {
                   12277: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12278: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12279: 	} else {
                   12280: 	    $location=~ s{/\.\./}{/}g;
                   12281: 	}
                   12282:     } #remove dir/..
1.590     banghart 12283:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12284:     return $location;
1.46      www      12285: }
1.36      albertel 12286: 
1.46      www      12287: sub hreflocation {
                   12288:     my ($dir,$file)=@_;
1.980     raeburn  12289:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12290: 	$file=filelocation($dir,$file);
1.700     albertel 12291:     } elsif ($file=~m-^/adm/-) {
                   12292: 	$file=~s-^/adm/wrapper/-/-;
                   12293: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12294:     }
                   12295:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12296: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12297:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12298: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12299: 	        {/uploaded/$1/$2/}x;
1.46      www      12300:     }
1.913     albertel 12301:     if ($file=~ m{^/userfiles/}) {
                   12302: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12303:     }
1.462     albertel 12304:     return $file;
1.465     albertel 12305: }
                   12306: 
1.1139    www      12307: 
                   12308: 
                   12309: 
                   12310: 
1.465     albertel 12311: sub current_machine_domains {
1.853     albertel 12312:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12313: }
                   12314: 
                   12315: sub machine_domains {
                   12316:     my ($hostname) = @_;
1.465     albertel 12317:     my @domains;
1.838     albertel 12318:     my %hostname = &all_hostnames();
1.465     albertel 12319:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12320: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12321: 	if ($hostname eq $name) {
1.844     albertel 12322: 	    push(@domains,&host_domain($id));
1.465     albertel 12323: 	}
                   12324:     }
                   12325:     return @domains;
                   12326: }
                   12327: 
                   12328: sub current_machine_ids {
1.853     albertel 12329:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12330: }
                   12331: 
                   12332: sub machine_ids {
                   12333:     my ($hostname) = @_;
                   12334:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12335:     my @ids;
1.888     albertel 12336:     my %name_to_host = &all_names();
1.889     albertel 12337:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12338: 	return @{ $name_to_host{$hostname} };
                   12339:     }
                   12340:     return;
1.31      www      12341: }
                   12342: 
1.824     raeburn  12343: sub additional_machine_domains {
                   12344:     my @domains;
                   12345:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12346:     while( my $line = <$fh>) {
                   12347:         $line =~ s/\s//g;
                   12348:         push(@domains,$line);
                   12349:     }
                   12350:     return @domains;
                   12351: }
                   12352: 
                   12353: sub default_login_domain {
                   12354:     my $domain = $perlvar{'lonDefDomain'};
                   12355:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12356:     foreach my $posdom (&current_machine_domains(),
                   12357:                         &additional_machine_domains()) {
                   12358:         if (lc($posdom) eq lc($testdomain)) {
                   12359:             $domain=$posdom;
                   12360:             last;
                   12361:         }
                   12362:     }
                   12363:     return $domain;
                   12364: }
                   12365: 
1.31      www      12366: # ------------------------------------------------------------- Declutters URLs
                   12367: 
                   12368: sub declutter {
                   12369:     my $thisfn=shift;
1.569     albertel 12370:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12371:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12372:         $thisfn=~s{^/home/httpd/html}{};
                   12373:     }
1.31      www      12374:     $thisfn=~s/^\///;
1.697     albertel 12375:     $thisfn=~s|^adm/wrapper/||;
                   12376:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12377:     $thisfn=~s/^res\///;
1.1172    bisitz   12378:     $thisfn=~s/^priv\///;
1.1032    raeburn  12379:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12380:         $thisfn=~s/\?.+$//;
                   12381:     }
1.268     www      12382:     return $thisfn;
                   12383: }
                   12384: 
                   12385: # ------------------------------------------------------------- Clutter up URLs
                   12386: 
                   12387: sub clutter {
                   12388:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12389:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12390: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12391:        $thisfn='/res'.$thisfn; 
                   12392:     }
1.1031    raeburn  12393:     if ($thisfn !~m|^/adm|) {
                   12394: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12395: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12396: 	} else {
                   12397: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12398: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12399: 	    if ($embstyle eq 'ssi'
                   12400: 		|| ($embstyle eq 'hdn')
                   12401: 		|| ($embstyle eq 'rat')
                   12402: 		|| ($embstyle eq 'prv')
                   12403: 		|| ($embstyle eq 'ign')) {
                   12404: 		#do nothing with these
                   12405: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12406: 		|| ($embstyle eq 'emb')
                   12407: 		|| ($embstyle eq 'wrp')) {
                   12408: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12409: 	    } elsif ($embstyle eq 'unk'
                   12410: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12411: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12412: 	    } else {
1.718     www      12413: #		&logthis("Got a blank emb style");
1.695     albertel 12414: 	    }
1.694     albertel 12415: 	}
1.1298    raeburn  12416:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12417:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12418:     }
1.31      www      12419:     return $thisfn;
1.12      www      12420: }
                   12421: 
1.787     albertel 12422: sub clutter_with_no_wrapper {
                   12423:     my $uri = &clutter(shift);
                   12424:     if ($uri =~ m-^/adm/-) {
                   12425: 	$uri =~ s-^/adm/wrapper/-/-;
                   12426: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12427:     }
                   12428:     return $uri;
                   12429: }
                   12430: 
1.557     albertel 12431: sub freeze_escape {
                   12432:     my ($value)=@_;
                   12433:     if (ref($value)) {
                   12434: 	$value=&nfreeze($value);
                   12435: 	return '__FROZEN__'.&escape($value);
                   12436:     }
                   12437:     return &escape($value);
                   12438: }
                   12439: 
1.11      www      12440: 
1.557     albertel 12441: sub thaw_unescape {
                   12442:     my ($value)=@_;
                   12443:     if ($value =~ /^__FROZEN__/) {
                   12444: 	substr($value,0,10,undef);
                   12445: 	$value=&unescape($value);
                   12446: 	return &thaw($value);
                   12447:     }
                   12448:     return &unescape($value);
                   12449: }
                   12450: 
1.436     albertel 12451: sub correct_line_ends {
                   12452:     my ($result)=@_;
                   12453:     $$result =~s/\r\n/\n/mg;
                   12454:     $$result =~s/\r/\n/mg;
1.415     albertel 12455: }
1.1       albertel 12456: # ================================================================ Main Program
                   12457: 
1.184     www      12458: sub goodbye {
1.204     albertel 12459:    &logthis("Starting Shut down");
1.443     albertel 12460: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12461:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12462: #converted
1.599     albertel 12463: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12464:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12465: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12466: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12467: #1.1 only
1.870     albertel 12468: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12469: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12470: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12471: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12472:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12473:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12474:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12475:    &flushcourselogs();
                   12476:    &logthis("Shutting down");
                   12477: }
                   12478: 
1.852     albertel 12479: sub get_dns {
1.1210    raeburn  12480:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12481:     if (!$ignore_cache) {
                   12482: 	my ($content,$cached)=
                   12483: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12484: 	if ($cached) {
1.1210    raeburn  12485: 	    &$func($content,$hashref);
1.869     albertel 12486: 	    return;
                   12487: 	}
                   12488:     }
                   12489: 
                   12490:     my %alldns;
1.852     albertel 12491:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12492:     foreach my $dns (<$config>) {
                   12493: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12494:         my $line = $1;
                   12495:         my ($host,$protocol) = split(/:/,$line);
                   12496:         if ($protocol ne 'https') {
                   12497:             $protocol = 'http';
                   12498:         }
                   12499: 	$alldns{$host} = $protocol;
1.869     albertel 12500:     }
                   12501:     while (%alldns) {
1.1263    raeburn  12502: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12503: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12504:         $ua->timeout(30);
1.979     raeburn  12505: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12506: 	my $response=$ua->request($request);
1.979     raeburn  12507:         delete($alldns{$dns});
1.852     albertel 12508: 	next if ($response->is_error());
                   12509: 	my @content = split("\n",$response->content);
1.1210    raeburn  12510: 	unless ($nocache) {
1.1219    raeburn  12511: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12512: 	}
                   12513: 	&$func(\@content,$hashref);
1.869     albertel 12514: 	return;
1.852     albertel 12515:     }
                   12516:     close($config);
1.871     albertel 12517:     my $which = (split('/',$url))[3];
                   12518:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12519:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12520:     my @content = <$config>;
1.1210    raeburn  12521:     &$func(\@content,$hashref);
                   12522:     return;
                   12523: }
                   12524: 
                   12525: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12526: sub parse_dns_checksums_tab {
1.1210    raeburn  12527:     my ($lines,$hashref) = @_;
1.1264    raeburn  12528:     my $lonhost = $perlvar{'lonHostID'};
                   12529:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12530:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12531:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12532:     my $webconfdir = '/etc/httpd/conf';
                   12533:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12534:         $webconfdir = '/etc/apache2';
                   12535:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12536:         if ($1 >= 10) {
                   12537:             $webconfdir = '/etc/apache2';
                   12538:         }
                   12539:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12540:         if ($1 >= 10.0) {
                   12541:             $webconfdir = '/etc/apache2';
                   12542:         }
                   12543:     }
1.1210    raeburn  12544:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12545:     my (%chksum,%revnum);
                   12546:     if (ref($lines) eq 'ARRAY') {
                   12547:         chomp(@{$lines});
1.1238    raeburn  12548:         my $version = shift(@{$lines});
                   12549:         if ($version eq $release) {  
1.1210    raeburn  12550:             foreach my $line (@{$lines}) {
1.1238    raeburn  12551:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12552:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12553:                     if ($webconfdir eq '/etc/apache2') {
                   12554:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12555:                     }
                   12556:                 }
1.1238    raeburn  12557:                 $chksum{$file} = $shasum;
                   12558:                 $revnum{$file} = $version;
1.1210    raeburn  12559:             }
                   12560:             if (ref($hashref) eq 'HASH') {
                   12561:                 %{$hashref} = (
                   12562:                                 sums     => \%chksum,
                   12563:                                 versions => \%revnum,
                   12564:                               );
                   12565:             }
                   12566:         }
                   12567:     }
1.869     albertel 12568:     return;
1.852     albertel 12569: }
1.1210    raeburn  12570: 
                   12571: sub fetch_dns_checksums {
1.1238    raeburn  12572:     my %checksums;
                   12573:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12574:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12575:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12576:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12577:              \%checksums);
1.1210    raeburn  12578:     return \%checksums;
                   12579: }
                   12580: 
1.327     albertel 12581: # ------------------------------------------------------------ Read domain file
                   12582: {
1.852     albertel 12583:     my $loaded;
1.846     albertel 12584:     my %domain;
                   12585: 
1.852     albertel 12586:     sub parse_domain_tab {
                   12587: 	my ($lines) = @_;
                   12588: 	foreach my $line (@$lines) {
                   12589: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12590: 
1.846     albertel 12591: 	    chomp($line);
1.852     albertel 12592: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12593: 	    my %this_domain;
                   12594: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12595: 			       'lang_def', 'city', 'longi', 'lati',
                   12596: 			       'primary') {
                   12597: 		$this_domain{$field} = shift(@elements);
                   12598: 	    }
                   12599: 	    $domain{$name} = \%this_domain;
1.852     albertel 12600: 	}
                   12601:     }
1.864     albertel 12602: 
                   12603:     sub reset_domain_info {
                   12604: 	undef($loaded);
                   12605: 	undef(%domain);
                   12606:     }
                   12607: 
1.852     albertel 12608:     sub load_domain_tab {
1.1293    raeburn  12609: 	my ($ignore_cache,$nocache) = @_;
                   12610: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12611: 	my $fh;
                   12612: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12613: 	    my @lines = <$fh>;
                   12614: 	    &parse_domain_tab(\@lines);
1.448     albertel 12615: 	}
1.852     albertel 12616: 	close($fh);
                   12617: 	$loaded = 1;
1.327     albertel 12618:     }
1.846     albertel 12619: 
                   12620:     sub domain {
1.852     albertel 12621: 	&load_domain_tab() if (!$loaded);
                   12622: 
1.846     albertel 12623: 	my ($name,$what) = @_;
                   12624: 	return if ( !exists($domain{$name}) );
                   12625: 
                   12626: 	if (!$what) {
                   12627: 	    return $domain{$name}{'description'};
                   12628: 	}
                   12629: 	return $domain{$name}{$what};
                   12630:     }
1.974     raeburn  12631: 
                   12632:     sub domain_info {
                   12633:         &load_domain_tab() if (!$loaded);
                   12634:         return %domain;
                   12635:     }
                   12636: 
1.327     albertel 12637: }
                   12638: 
                   12639: 
1.1       albertel 12640: # ------------------------------------------------------------- Read hosts file
                   12641: {
1.838     albertel 12642:     my %hostname;
1.844     albertel 12643:     my %hostdom;
1.845     albertel 12644:     my %libserv;
1.852     albertel 12645:     my $loaded;
1.888     albertel 12646:     my %name_to_host;
1.1074    raeburn  12647:     my %internetdom;
1.1107    raeburn  12648:     my %LC_dns_serv;
1.852     albertel 12649: 
                   12650:     sub parse_hosts_tab {
                   12651: 	my ($file) = @_;
                   12652: 	foreach my $configline (@$file) {
                   12653: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12654:             chomp($configline);
                   12655: 	    if ($configline =~ /^\^/) {
                   12656:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12657:                     $LC_dns_serv{$1} = 1;
                   12658:                 }
                   12659:                 next;
                   12660:             }
1.1074    raeburn  12661: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12662: 	    $name=~s/\s//g;
                   12663: 	    if ($id && $domain && $role && $name) {
                   12664: 		$hostname{$id}=$name;
1.888     albertel 12665: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12666: 		$hostdom{$id}=$domain;
                   12667: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12668:                 if (defined($protocol)) {
                   12669:                     if ($protocol eq 'https') {
                   12670:                         $protocol{$id} = $protocol;
                   12671:                     } else {
                   12672:                         $protocol{$id} = 'http'; 
                   12673:                     }
1.968     raeburn  12674:                 } else {
1.969     raeburn  12675:                     $protocol{$id} = 'http';
1.968     raeburn  12676:                 }
1.1074    raeburn  12677:                 if (defined($intdom)) {
                   12678:                     $internetdom{$id} = $intdom;
                   12679:                 }
1.852     albertel 12680: 	    }
                   12681: 	}
                   12682:     }
1.864     albertel 12683:     
                   12684:     sub reset_hosts_info {
1.897     albertel 12685: 	&purge_remembered();
1.864     albertel 12686: 	&reset_domain_info();
                   12687: 	&reset_hosts_ip_info();
1.892     albertel 12688: 	undef(%name_to_host);
1.864     albertel 12689: 	undef(%hostname);
                   12690: 	undef(%hostdom);
                   12691: 	undef(%libserv);
                   12692: 	undef($loaded);
                   12693:     }
1.1       albertel 12694: 
1.852     albertel 12695:     sub load_hosts_tab {
1.1293    raeburn  12696: 	my ($ignore_cache,$nocache) = @_;
                   12697: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12698: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12699: 	my @config = <$config>;
                   12700: 	&parse_hosts_tab(\@config);
                   12701: 	close($config);
                   12702: 	$loaded=1;
1.1       albertel 12703:     }
1.852     albertel 12704: 
1.838     albertel 12705:     sub hostname {
1.852     albertel 12706: 	&load_hosts_tab() if (!$loaded);
                   12707: 
1.838     albertel 12708: 	my ($lonid) = @_;
                   12709: 	return $hostname{$lonid};
                   12710:     }
1.845     albertel 12711: 
1.838     albertel 12712:     sub all_hostnames {
1.852     albertel 12713: 	&load_hosts_tab() if (!$loaded);
                   12714: 
1.838     albertel 12715: 	return %hostname;
                   12716:     }
1.845     albertel 12717: 
1.888     albertel 12718:     sub all_names {
1.1293    raeburn  12719:         my ($ignore_cache,$nocache) = @_;
                   12720: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12721: 
                   12722: 	return %name_to_host;
                   12723:     }
                   12724: 
1.974     raeburn  12725:     sub all_host_domain {
                   12726:         &load_hosts_tab() if (!$loaded);
                   12727:         return %hostdom;
                   12728:     }
                   12729: 
1.845     albertel 12730:     sub is_library {
1.852     albertel 12731: 	&load_hosts_tab() if (!$loaded);
                   12732: 
1.845     albertel 12733: 	return exists($libserv{$_[0]});
                   12734:     }
                   12735: 
                   12736:     sub all_library {
1.852     albertel 12737: 	&load_hosts_tab() if (!$loaded);
                   12738: 
1.845     albertel 12739: 	return %libserv;
                   12740:     }
                   12741: 
1.1062    droeschl 12742:     sub unique_library {
                   12743: 	#2x reverse removes all hostnames that appear more than once
                   12744:         my %unique = reverse &all_library();
                   12745:         return reverse %unique;
                   12746:     }
                   12747: 
1.841     albertel 12748:     sub get_servers {
1.852     albertel 12749: 	&load_hosts_tab() if (!$loaded);
                   12750: 
1.841     albertel 12751: 	my ($domain,$type) = @_;
                   12752: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12753: 	                                          : %hostname;
                   12754: 	my %result;
1.842     albertel 12755: 	if (ref($domain) eq 'ARRAY') {
                   12756: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12757: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12758: 		    $result{$host} = $hostname;
                   12759: 		}
                   12760: 	    }
                   12761: 	} else {
                   12762: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12763: 		if ($hostdom{$host} eq $domain) {
                   12764: 		    $result{$host} = $hostname;
                   12765: 		}
1.841     albertel 12766: 	    }
                   12767: 	}
                   12768: 	return %result;
                   12769:     }
1.845     albertel 12770: 
1.1062    droeschl 12771:     sub get_unique_servers {
                   12772:         my %unique = reverse &get_servers(@_);
                   12773: 	return reverse %unique;
                   12774:     }
                   12775: 
1.844     albertel 12776:     sub host_domain {
1.852     albertel 12777: 	&load_hosts_tab() if (!$loaded);
                   12778: 
1.844     albertel 12779: 	my ($lonid) = @_;
                   12780: 	return $hostdom{$lonid};
                   12781:     }
                   12782: 
1.841     albertel 12783:     sub all_domains {
1.852     albertel 12784: 	&load_hosts_tab() if (!$loaded);
                   12785: 
1.841     albertel 12786: 	my %seen;
                   12787: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12788: 	return @uniq;
                   12789:     }
1.1074    raeburn  12790: 
                   12791:     sub internet_dom {
                   12792:         &load_hosts_tab() if (!$loaded);
                   12793: 
                   12794:         my ($lonid) = @_;
                   12795:         return $internetdom{$lonid};
                   12796:     }
1.1107    raeburn  12797: 
                   12798:     sub is_LC_dns {
                   12799:         &load_hosts_tab() if (!$loaded);
                   12800: 
                   12801:         my ($hostname) = @_;
                   12802:         return exists($LC_dns_serv{$hostname});
                   12803:     }
                   12804: 
1.1       albertel 12805: }
                   12806: 
1.847     albertel 12807: { 
                   12808:     my %iphost;
1.856     albertel 12809:     my %name_to_ip;
                   12810:     my %lonid_to_ip;
1.869     albertel 12811: 
1.847     albertel 12812:     sub get_hosts_from_ip {
                   12813: 	my ($ip) = @_;
                   12814: 	my %iphosts = &get_iphost();
                   12815: 	if (ref($iphosts{$ip})) {
                   12816: 	    return @{$iphosts{$ip}};
                   12817: 	}
                   12818: 	return;
1.839     albertel 12819:     }
1.864     albertel 12820:     
                   12821:     sub reset_hosts_ip_info {
                   12822: 	undef(%iphost);
                   12823: 	undef(%name_to_ip);
                   12824: 	undef(%lonid_to_ip);
                   12825:     }
1.856     albertel 12826: 
                   12827:     sub get_host_ip {
                   12828: 	my ($lonid) = @_;
                   12829: 	if (exists($lonid_to_ip{$lonid})) {
                   12830: 	    return $lonid_to_ip{$lonid};
                   12831: 	}
                   12832: 	my $name=&hostname($lonid);
                   12833:    	my $ip = gethostbyname($name);
                   12834: 	return if (!$ip || length($ip) ne 4);
                   12835: 	$ip=inet_ntoa($ip);
                   12836: 	$name_to_ip{$name}   = $ip;
                   12837: 	$lonid_to_ip{$lonid} = $ip;
                   12838: 	return $ip;
                   12839:     }
1.847     albertel 12840:     
                   12841:     sub get_iphost {
1.1293    raeburn  12842: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12843: 
1.869     albertel 12844: 	if (!$ignore_cache) {
                   12845: 	    if (%iphost) {
                   12846: 		return %iphost;
                   12847: 	    }
                   12848: 	    my ($ip_info,$cached)=
                   12849: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12850: 	    if ($cached) {
                   12851: 		%iphost      = %{$ip_info->[0]};
                   12852: 		%name_to_ip  = %{$ip_info->[1]};
                   12853: 		%lonid_to_ip = %{$ip_info->[2]};
                   12854: 		return %iphost;
                   12855: 	    }
                   12856: 	}
1.894     albertel 12857: 
                   12858: 	# get yesterday's info for fallback
                   12859: 	my %old_name_to_ip;
                   12860: 	my ($ip_info,$cached)=
                   12861: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12862: 	if ($cached) {
                   12863: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12864: 	}
                   12865: 
1.1293    raeburn  12866: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 12867: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12868: 	    my $ip;
                   12869: 	    if (!exists($name_to_ip{$name})) {
                   12870: 		$ip = gethostbyname($name);
                   12871: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12872: 		    if (defined($old_name_to_ip{$name})) {
                   12873: 			$ip = $old_name_to_ip{$name};
                   12874: 			&logthis("Can't find $name defaulting to old $ip");
                   12875: 		    } else {
                   12876: 			&logthis("Name $name no IP found");
                   12877: 			next;
                   12878: 		    }
                   12879: 		} else {
                   12880: 		    $ip=inet_ntoa($ip);
1.847     albertel 12881: 		}
                   12882: 		$name_to_ip{$name} = $ip;
                   12883: 	    } else {
                   12884: 		$ip = $name_to_ip{$name};
1.653     albertel 12885: 	    }
1.888     albertel 12886: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12887: 		$lonid_to_ip{$id} = $ip;
                   12888: 	    }
                   12889: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12890: 	}
1.1293    raeburn  12891:         unless ($nocache) {
                   12892: 	    &do_cache_new('iphost','iphost',
                   12893: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12894: 		          48*60*60);
                   12895:         }
1.869     albertel 12896: 
1.847     albertel 12897: 	return %iphost;
1.598     albertel 12898:     }
                   12899: 
1.992     raeburn  12900:     #
                   12901:     #  Given a DNS returns the loncapa host name for that DNS 
                   12902:     # 
                   12903:     sub host_from_dns {
                   12904:         my ($dns) = @_;
                   12905:         my @hosts;
                   12906:         my $ip;
                   12907: 
1.993     raeburn  12908:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12909:             $ip = $name_to_ip{$dns};
                   12910:         }
                   12911:         if (!$ip) {
                   12912:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12913:             if (length($ip) == 4) { 
                   12914: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12915:             }
                   12916:         }
                   12917:         if ($ip) {
                   12918: 	    @hosts = get_hosts_from_ip($ip);
                   12919: 	    return $hosts[0];
                   12920:         }
                   12921:         return undef;
1.986     foxr     12922:     }
1.992     raeburn  12923: 
1.1074    raeburn  12924:     sub get_internet_names {
                   12925:         my ($lonid) = @_;
                   12926:         return if ($lonid eq '');
                   12927:         my ($idnref,$cached)=
                   12928:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12929:         if ($cached) {
                   12930:             return $idnref;
                   12931:         }
                   12932:         my $ip = &get_host_ip($lonid);
                   12933:         my @hosts = &get_hosts_from_ip($ip);
                   12934:         my %iphost = &get_iphost();
                   12935:         my (@idns,%seen);
                   12936:         foreach my $id (@hosts) {
                   12937:             my $dom = &host_domain($id);
                   12938:             my $prim_id = &domain($dom,'primary');
                   12939:             my $prim_ip = &get_host_ip($prim_id);
                   12940:             next if ($seen{$prim_ip});
                   12941:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12942:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12943:                     my $intdom = &internet_dom($id);
                   12944:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12945:                         push(@idns,$intdom);
                   12946:                     }
                   12947:                 }
                   12948:             }
                   12949:             $seen{$prim_ip} = 1;
                   12950:         }
1.1219    raeburn  12951:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12952:     }
                   12953: 
1.986     foxr     12954: }
                   12955: 
1.1079    raeburn  12956: sub all_loncaparevs {
1.1249    raeburn  12957:     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 2.11);
1.1079    raeburn  12958: }
                   12959: 
1.1227    raeburn  12960: # ---------------------------------------------------------- Read loncaparev table
                   12961: {
                   12962:     sub load_loncaparevs { 
                   12963:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12964:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12965:                 while (my $configline=<$config>) {
                   12966:                     chomp($configline);
                   12967:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12968:                     $loncaparevs{$hostid}=$loncaparev;
                   12969:                 }
                   12970:                 close($config);
                   12971:             }
                   12972:         }
                   12973:     }
                   12974: }
                   12975: 
                   12976: # ---------------------------------------------------------- Read serverhostID table
                   12977: {
                   12978:     sub load_serverhomeIDs {
                   12979:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12980:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12981:                 while (my $configline=<$config>) {
                   12982:                     chomp($configline);
                   12983:                     my ($name,$id)=split(/:/,$configline);
                   12984:                     $serverhomeIDs{$name}=$id;
                   12985:                 }
                   12986:                 close($config);
                   12987:             }
                   12988:         }
                   12989:     }
                   12990: }
                   12991: 
                   12992: 
1.862     albertel 12993: BEGIN {
                   12994: 
                   12995: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12996:     unless ($readit) {
                   12997: {
                   12998:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12999:     %perlvar = (%perlvar,%{$configvars});
                   13000: }
                   13001: 
                   13002: 
1.1       albertel 13003: # ------------------------------------------------------ Read spare server file
                   13004: {
1.448     albertel 13005:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13006: 
                   13007:     while (my $configline=<$config>) {
                   13008:        chomp($configline);
1.284     matthew  13009:        if ($configline) {
1.784     albertel 13010: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13011: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13012: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13013:        }
                   13014:     }
1.448     albertel 13015:     close($config);
1.1       albertel 13016: }
1.11      www      13017: # ------------------------------------------------------------ Read permissions
                   13018: {
1.448     albertel 13019:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13020: 
                   13021:     while (my $configline=<$config>) {
1.448     albertel 13022: 	chomp($configline);
                   13023: 	if ($configline) {
                   13024: 	    my ($role,$perm)=split(/ /,$configline);
                   13025: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13026: 	}
1.11      www      13027:     }
1.448     albertel 13028:     close($config);
1.11      www      13029: }
                   13030: 
                   13031: # -------------------------------------------- Read plain texts for permissions
                   13032: {
1.448     albertel 13033:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13034: 
                   13035:     while (my $configline=<$config>) {
1.448     albertel 13036: 	chomp($configline);
                   13037: 	if ($configline) {
1.742     raeburn  13038: 	    my ($short,@plain)=split(/:/,$configline);
                   13039:             %{$prp{$short}} = ();
                   13040: 	    if (@plain > 0) {
                   13041:                 $prp{$short}{'std'} = $plain[0];
                   13042:                 for (my $i=1; $i<@plain; $i++) {
                   13043:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13044:                 }
                   13045:             }
1.448     albertel 13046: 	}
1.135     www      13047:     }
1.448     albertel 13048:     close($config);
1.135     www      13049: }
                   13050: 
                   13051: # ---------------------------------------------------------- Read package table
                   13052: {
1.448     albertel 13053:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13054: 
                   13055:     while (my $configline=<$config>) {
1.483     albertel 13056: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13057: 	chomp($configline);
                   13058: 	my ($short,$plain)=split(/:/,$configline);
                   13059: 	my ($pack,$name)=split(/\&/,$short);
                   13060: 	if ($plain ne '') {
                   13061: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13062: 	    $packagetab{$short}=$plain; 
                   13063: 	}
1.11      www      13064:     }
1.448     albertel 13065:     close($config);
1.329     matthew  13066: }
                   13067: 
1.1073    raeburn  13068: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13069: 
                   13070: &load_loncaparevs();
1.1073    raeburn  13071: 
1.1074    raeburn  13072: # ---------------------------------------------------------- Read serverhostID table
                   13073: 
1.1227    raeburn  13074: &load_serverhomeIDs();
                   13075: 
                   13076: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13077: {
                   13078:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13079:     if (-e $file) {
                   13080:         my $parser = HTML::LCParser->new($file);
                   13081:         while (my $token = $parser->get_token()) {
                   13082:             if ($token->[0] eq 'S') {
                   13083:                 my $item = $token->[1];
                   13084:                 my $name = $token->[2]{'name'};
                   13085:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13086:                 my $valuematch = $token->[2]{'valuematch'};
1.1303  ! raeburn  13087:                 my $namematch = $token->[2]{'namematch'};
        !          13088:                 if ($item eq 'parameter') {
        !          13089:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
        !          13090:                         my $release = $parser->get_text();
        !          13091:                         $release =~ s/(^\s*|\s*$ )//gx;
        !          13092:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
        !          13093:                     }
        !          13094:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13095:                     my $release = $parser->get_text();
                   13096:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303  ! raeburn  13097:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13098:                 }
                   13099:             }
                   13100:         }
                   13101:     }
1.1073    raeburn  13102: }
                   13103: 
1.1138    raeburn  13104: # ---------------------------------------------------------- Read managers table
                   13105: {
                   13106:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13107:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13108:             while (my $configline=<$config>) {
                   13109:                 chomp($configline);
                   13110:                 next if ($configline =~ /^\#/);
                   13111:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13112:                     $managerstab{$configline} = 1;
                   13113:                 }
                   13114:             }
                   13115:             close($config);
                   13116:         }
                   13117:     }
                   13118: }
                   13119: 
1.329     matthew  13120: # ------------- set up temporary directory
                   13121: {
1.1117    foxr     13122:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13123: 
1.11      www      13124: }
                   13125: 
1.794     albertel 13126: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13127: 				'compress_threshold'=> 20_000,
                   13128:  			        });
1.185     www      13129: 
1.281     www      13130: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13131: $dumpcount=0;
1.958     www      13132: $locknum=0;
1.22      www      13133: 
1.163     harris41 13134: &logtouch();
1.672     albertel 13135: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13136: $readit=1;
1.564     albertel 13137:     {
                   13138: 	use integer;
                   13139: 	my $test=(2**32)+1;
1.568     albertel 13140: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13141: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13142:     }
1.195     www      13143: }
1.1       albertel 13144: }
1.179     www      13145: 
1.1       albertel 13146: 1;
1.191     harris41 13147: __END__
                   13148: 
1.243     albertel 13149: =pod
                   13150: 
1.191     harris41 13151: =head1 NAME
                   13152: 
1.243     albertel 13153: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13154: 
                   13155: =head1 SYNOPSIS
                   13156: 
1.243     albertel 13157: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13158: 
                   13159:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13160: 
1.243     albertel 13161: Common parameters:
                   13162: 
                   13163: =over 4
                   13164: 
                   13165: =item *
                   13166: 
                   13167: $uname : an internal username (if $cname expecting a course Id specifically)
                   13168: 
                   13169: =item *
                   13170: 
                   13171: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13172: 
                   13173: =item *
                   13174: 
                   13175: $symb : a resource instance identifier
                   13176: 
                   13177: =item *
                   13178: 
                   13179: $namespace : the name of a .db file that contains the data needed or
                   13180: being set.
                   13181: 
                   13182: =back
                   13183: 
1.394     bowersj2 13184: =head1 OVERVIEW
1.191     harris41 13185: 
1.394     bowersj2 13186: lonnet provides subroutines which interact with the
                   13187: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13188: about classes, users, and resources.
1.243     albertel 13189: 
                   13190: For many of these objects you can also use this to store data about
                   13191: them or modify them in various ways.
1.191     harris41 13192: 
1.394     bowersj2 13193: =head2 Symbs
1.191     harris41 13194: 
1.394     bowersj2 13195: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13196: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13197: map, the resource number of the resource in the map, and the URL of
                   13198: the resource itself. The latter is somewhat redundant, but might help
                   13199: if maps change.
                   13200: 
                   13201: An example is
                   13202: 
                   13203:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13204: 
                   13205: The respective map entry is
                   13206: 
                   13207:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13208:   title="Problem 2">
                   13209:  </resource>
                   13210: 
                   13211: Symbs are used by the random number generator, as well as to store and
                   13212: restore data specific to a certain instance of for example a problem.
                   13213: 
                   13214: =head2 Storing And Retrieving Data
                   13215: 
                   13216: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13217: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13218: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13219: is is the non-critical message twin of cstore. These functions are for
                   13220: handlers to store a perl hash to a user's permanent data space in an
                   13221: easy manner, and to retrieve it again on another call. It is expected
                   13222: that a handler would use this once at the beginning to retrieve data,
                   13223: and then again once at the end to send only the new data back.
                   13224: 
                   13225: The data is stored in the user's data directory on the user's
                   13226: homeserver under the ID of the course.
                   13227: 
                   13228: The hash that is returned by restore will have all of the previous
                   13229: value for all of the elements of the hash.
                   13230: 
                   13231: Example:
                   13232: 
                   13233:  #creating a hash
                   13234:  my %hash;
                   13235:  $hash{'foo'}='bar';
                   13236: 
                   13237:  #storing it
                   13238:  &Apache::lonnet::cstore(\%hash);
                   13239: 
                   13240:  #changing a value
                   13241:  $hash{'foo'}='notbar';
                   13242: 
                   13243:  #adding a new value
                   13244:  $hash{'bar'}='foo';
                   13245:  &Apache::lonnet::cstore(\%hash);
                   13246: 
                   13247:  #retrieving the hash
                   13248:  my %history=&Apache::lonnet::restore();
                   13249: 
                   13250:  #print the hash
                   13251:  foreach my $key (sort(keys(%history))) {
                   13252:    print("\%history{$key} = $history{$key}");
                   13253:  }
                   13254: 
                   13255: Will print out:
1.191     harris41 13256: 
1.394     bowersj2 13257:  %history{1:foo} = bar
                   13258:  %history{1:keys} = foo:timestamp
                   13259:  %history{1:timestamp} = 990455579
                   13260:  %history{2:bar} = foo
                   13261:  %history{2:foo} = notbar
                   13262:  %history{2:keys} = foo:bar:timestamp
                   13263:  %history{2:timestamp} = 990455580
                   13264:  %history{bar} = foo
                   13265:  %history{foo} = notbar
                   13266:  %history{timestamp} = 990455580
                   13267:  %history{version} = 2
                   13268: 
                   13269: Note that the special hash entries C<keys>, C<version> and
                   13270: C<timestamp> were added to the hash. C<version> will be equal to the
                   13271: total number of versions of the data that have been stored. The
                   13272: C<timestamp> attribute will be the UNIX time the hash was
                   13273: stored. C<keys> is available in every historical section to list which
                   13274: keys were added or changed at a specific historical revision of a
                   13275: hash.
                   13276: 
                   13277: B<Warning>: do not store the hash that restore returns directly. This
                   13278: will cause a mess since it will restore the historical keys as if the
                   13279: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13280: 
1.394     bowersj2 13281: Calling convention:
1.191     harris41 13282: 
1.1225    raeburn  13283:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13284:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13285: 
1.394     bowersj2 13286: For more detailed information, see lonnet specific documentation.
1.191     harris41 13287: 
1.394     bowersj2 13288: =head1 RETURN MESSAGES
1.191     harris41 13289: 
1.394     bowersj2 13290: =over 4
1.191     harris41 13291: 
1.394     bowersj2 13292: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13293: 
1.394     bowersj2 13294: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13295: when the connection is brought back up
1.191     harris41 13296: 
1.394     bowersj2 13297: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13298: for later delivery
1.191     harris41 13299: 
1.967     bisitz   13300: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13301: 
1.394     bowersj2 13302: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13303: that was requested
1.191     harris41 13304: 
1.243     albertel 13305: =back
1.191     harris41 13306: 
1.243     albertel 13307: =head1 PUBLIC SUBROUTINES
1.191     harris41 13308: 
1.243     albertel 13309: =head2 Session Environment Functions
1.191     harris41 13310: 
1.243     albertel 13311: =over 4
1.191     harris41 13312: 
1.394     bowersj2 13313: =item * 
                   13314: X<appenv()>
1.949     raeburn  13315: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13316: the user envirnoment file, and will be restored for each access this
1.620     albertel 13317: user makes during this session, also modifies the %env for the current
1.949     raeburn  13318: process. Optional rolesarrayref - if defined contains a reference to an array
                   13319: of roles which are exempt from the restriction on modifying user.role entries 
                   13320: in the user's environment.db and in %env.    
1.191     harris41 13321: 
                   13322: =item *
1.394     bowersj2 13323: X<delenv()>
1.987     raeburn  13324: B<delenv($delthis,$regexp)>: removes all items from the session
                   13325: environment file that begin with $delthis. If the 
                   13326: optional second arg - $regexp - is true, $delthis is treated as a 
                   13327: regular expression, otherwise \Q$delthis\E is used. 
                   13328: The values are also deleted from the current processes %env.
1.191     harris41 13329: 
1.795     albertel 13330: =item * get_env_multiple($name) 
                   13331: 
                   13332: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13333: values may be defined and end up as an array ref.
                   13334: 
                   13335: returns an array of values
                   13336: 
1.243     albertel 13337: =back
                   13338: 
                   13339: =head2 User Information
1.191     harris41 13340: 
1.243     albertel 13341: =over 4
1.191     harris41 13342: 
                   13343: =item *
1.394     bowersj2 13344: X<queryauthenticate()>
                   13345: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13346: authentication scheme
                   13347: 
                   13348: =item *
1.394     bowersj2 13349: X<authenticate()>
1.1073    raeburn  13350: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13351: authenticate user from domain's lib servers (first use the current
                   13352: one). C<$upass> should be the users password.
1.1073    raeburn  13353: $checkdefauth is optional (value is 1 if a check should be made to
                   13354:    authenticate user using default authentication method, and allow
                   13355:    account creation if username does not have account in the domain).
                   13356: $clientcancheckhost is optional (value is 1 if checking whether the
                   13357:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13358: 
                   13359: =item *
1.394     bowersj2 13360: X<homeserver()>
                   13361: B<homeserver($uname,$udom)>: find the server which has
                   13362: the user's directory and files (there must be only one), this caches
                   13363: the answer, and also caches if there is a borken connection.
1.191     harris41 13364: 
                   13365: =item *
1.394     bowersj2 13366: X<idget()>
1.1300    raeburn  13367: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13368: a list of student/employee IDs or clicker IDs
                   13369: (student/employee IDs are a unique resource in a domain, there must be 
                   13370: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13371: clickerIDs are not necessarily unique, as students might share clickers.
                   13372: (returns hash: id=>name,id=>name)
1.191     harris41 13373: 
                   13374: =item *
1.394     bowersj2 13375: X<idrget()>
                   13376: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13377: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13378: 
                   13379: =item *
1.394     bowersj2 13380: X<idput()>
1.1300    raeburn  13381: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13382: names and associated student/employee IDs or clicker IDs.
                   13383: 
                   13384: =item *
                   13385: X<iddel()>
                   13386: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13387: student/employee ID or clicker ID username look-ups from domain.
                   13388: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13389: If no $uhome is provided, it will be determined usig &homeserver()
                   13390: for each user.  If no $namespace is provided, the default is ids.
                   13391: 
                   13392: =item *
                   13393: X<updateclickers()>
                   13394: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13395: clicker ID-to-username look-ups in clickers.db on library server.
                   13396: Permitted actions are add or del (i.e., add or delete). The 
                   13397: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13398: value is an escaped comma-separated list of usernames (for whom the
                   13399: library server is the homeserver), who registered that particular ID.
                   13400: If $critical is true, the update will be sent via &critical, otherwise
                   13401: &reply() will be used.
1.191     harris41 13402: 
                   13403: =item *
1.394     bowersj2 13404: X<rolesinit()>
1.1169    droeschl 13405: B<rolesinit($udom,$username)>: get user privileges.
                   13406: returns user role, first access and timer interval hashes
1.243     albertel 13407: 
                   13408: =item *
1.1171    droeschl 13409: X<privileged()>
                   13410: B<privileged($username,$domain)>: returns a true if user has a
                   13411: privileged and active role (i.e. su or dc), false otherwise.
                   13412: 
                   13413: =item *
1.551     albertel 13414: X<getsection()>
                   13415: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13416: course $cname, return section name/number or '' for "not in course"
                   13417: and '-1' for "no section"
                   13418: 
                   13419: =item *
1.394     bowersj2 13420: X<userenvironment()>
                   13421: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13422: passed in @what from the requested user's environment, returns a hash
                   13423: 
1.858     raeburn  13424: =item * 
                   13425: X<userlog_query()>
1.859     albertel 13426: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13427: activity.log file. %filters defines filters applied when parsing the
                   13428: log file. These can be start or end timestamps, or the type of action
                   13429: - log to look for Login or Logout events, check for Checkin or
                   13430: Checkout, role for role selection. The response is in the form
                   13431: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13432: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13433: 
1.243     albertel 13434: =back
                   13435: 
                   13436: =head2 User Roles
                   13437: 
                   13438: =over 4
                   13439: 
                   13440: =item *
                   13441: 
1.1284    raeburn  13442: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13443: returns codes for allowed actions.
                   13444: 
                   13445: The first argument is required, all others are optional.
                   13446: 
                   13447: $priv is the privilege being checked.
                   13448: $uri contains additional information about what is being checked for access (e.g.,
                   13449: URL, course ID etc.). 
                   13450: $symb is the unique resource instance identifier in a course; if needed,
                   13451: but not provided, it will be retrieved via a call to &symbread(). 
                   13452: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13453: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13454: files).
                   13455: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13456: prevents recursive calls to &allowed.
                   13457: 
1.243     albertel 13458:  F: full access
                   13459:  U,I,K: authentication modes (cxx only)
                   13460:  '': forbidden
                   13461:  1: user needs to choose course
                   13462:  2: browse allowed
1.766     albertel 13463:  A: passphrase authentication needed
1.1284    raeburn  13464:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13465: 
                   13466: =item *
                   13467: 
1.1192    raeburn  13468: constructaccess($url,$setpriv) : check for access to construction space URL
                   13469: 
                   13470: See if the owner domain and name in the URL match those in the
                   13471: expected environment.  If so, return three element list
                   13472: ($ownername,$ownerdomain,$ownerhome).
                   13473: 
                   13474: Otherwise return the null string.
                   13475: 
                   13476: If second argument 'setpriv' is true, it assigns the privileges,
                   13477: and returns the same three element list, unless the owner has
                   13478: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13479: in which case the null string is returned.
                   13480: 
                   13481: =item *
                   13482: 
1.243     albertel 13483: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13484: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13485: and course level
                   13486: 
                   13487: =item *
                   13488: 
1.988     raeburn  13489: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13490: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13491: $type is Course (default) or Community.
1.988     raeburn  13492: If $forcedefault evaluates to true, text returned will be default 
                   13493: text for $type. Otherwise, if this is a course, the text returned 
                   13494: will be a custom name for the role (if defined in the course's 
                   13495: environment).  If no custom name is defined the default is returned.
                   13496:    
1.832     raeburn  13497: =item *
                   13498: 
1.1219    raeburn  13499: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13500: All arguments are optional. Returns a hash of a roles, either for
                   13501: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13502: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13503: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13504: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13505: For each key, value is set to colon-separated start and end times for
                   13506: the role.  If no username and domain are specified, will default to
1.934     raeburn  13507: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13508: of role statuses (active, future or previous), roles 
                   13509: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13510: to restrict the list of roles reported. If no array ref is 
                   13511: provided for types, will default to return only active roles.
1.834     albertel 13512: 
1.1195    raeburn  13513: =item *
                   13514: 
                   13515: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13516: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13517: 
                   13518: Additional optional arguments are: $type (if role checking is to be restricted 
                   13519: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13520: available roles) or future (roles available in the future), and
                   13521: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13522: have active Domain Coordinator role in course's domain or in additional
                   13523: domains (specified in 'Domains to check for privileged users' in course
                   13524: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13525: 
                   13526: =item *
                   13527: 
                   13528: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13529: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13530: $possdomains and $possroles are optional array refs -- to domains to check and
                   13531: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13532: users' roles.db to check for a dc or su role in any domain. This can be
                   13533: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13534: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13535: this then allows &privileged_by_domain() to be used, which caches the identity
                   13536: of privileged users, eliminating the need for repeated calls to &dump().
                   13537: 
                   13538: =item *
                   13539: 
                   13540: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13541: where the outer hash keys are domains specified in the $possdomains array ref,
                   13542: next inner hash keys are privileged roles specified in the $roles array ref,
                   13543: and the innermost hash contains key = value pairs for username:domain = end:start
                   13544: for active or future "privileged" users with that role in that domain. To avoid
                   13545: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13546: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13547: 
1.243     albertel 13548: =back
                   13549: 
                   13550: =head2 User Modification
                   13551: 
                   13552: =over 4
                   13553: 
                   13554: =item *
                   13555: 
1.957     raeburn  13556: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13557: user for the level given by URL.  Optional start and end dates (leave empty
                   13558: string or zero for "no date")
1.191     harris41 13559: 
                   13560: =item *
                   13561: 
1.243     albertel 13562: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13563: change a users, password, possible return values are: ok,
                   13564: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13565: refused
1.191     harris41 13566: 
                   13567: =item *
                   13568: 
1.243     albertel 13569: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13570: 
                   13571: =item *
                   13572: 
1.1058    raeburn  13573: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13574:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13575: 
                   13576: will update user information (firstname,middlename,lastname,generation,
                   13577: permanentemail), and if forceid is true, student/employee ID also.
                   13578: A user's institutional affiliation(s) can also be updated.
                   13579: User information fields will not be overwritten with empty entries 
                   13580: unless the field is included in the $candelete array reference.
                   13581: This array is included when a single user is modified via "Manage Users",
                   13582: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13583: 
                   13584: =item *
                   13585: 
1.286     matthew  13586: modifystudent
                   13587: 
1.957     raeburn  13588: modify a student's enrollment and identification information.
1.1235    raeburn  13589: The course id is resolved based on the current user's environment.  
                   13590: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13591: associated with a course.
                   13592: 
1.297     matthew  13593: This call is essentially a wrapper for lonnet::modifyuser and
                   13594: lonnet::modify_student_enrollment
1.286     matthew  13595: 
                   13596: Inputs: 
                   13597: 
                   13598: =over 4
                   13599: 
1.957     raeburn  13600: =item B<$udom> Student's loncapa domain
1.286     matthew  13601: 
1.957     raeburn  13602: =item B<$uname> Student's loncapa login name
1.286     matthew  13603: 
1.964     bisitz   13604: =item B<$uid> Student/Employee ID
1.286     matthew  13605: 
1.957     raeburn  13606: =item B<$umode> Student's authentication mode
1.286     matthew  13607: 
1.957     raeburn  13608: =item B<$upass> Student's password
1.286     matthew  13609: 
1.957     raeburn  13610: =item B<$first> Student's first name
1.286     matthew  13611: 
1.957     raeburn  13612: =item B<$middle> Student's middle name
1.286     matthew  13613: 
1.957     raeburn  13614: =item B<$last> Student's last name
1.286     matthew  13615: 
1.957     raeburn  13616: =item B<$gene> Student's generation
1.286     matthew  13617: 
1.957     raeburn  13618: =item B<$usec> Student's section in course
1.286     matthew  13619: 
                   13620: =item B<$end> Unix time of the roles expiration
                   13621: 
                   13622: =item B<$start> Unix time of the roles start date
                   13623: 
                   13624: =item B<$forceid> If defined, allow $uid to be changed
                   13625: 
                   13626: =item B<$desiredhome> server to use as home server for student
                   13627: 
1.957     raeburn  13628: =item B<$email> Student's permanent e-mail address
                   13629: 
                   13630: =item B<$type> Type of enrollment (auto or manual)
                   13631: 
1.963     raeburn  13632: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13633: 
                   13634: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13635: 
1.963     raeburn  13636: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13637: 
1.963     raeburn  13638: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13639: 
1.1216    raeburn  13640: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13641: 
                   13642: =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  13643: 
1.286     matthew  13644: =back
1.297     matthew  13645: 
                   13646: =item *
                   13647: 
                   13648: modify_student_enrollment
                   13649: 
1.1235    raeburn  13650: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13651: 'role.request.course' must be defined for this function to proceed.
                   13652: 
                   13653: Inputs:
                   13654: 
                   13655: =over 4
                   13656: 
1.1235    raeburn  13657: =item $udom, student's domain
1.297     matthew  13658: 
1.1235    raeburn  13659: =item $uname, student's name
1.297     matthew  13660: 
1.1235    raeburn  13661: =item $uid, student's user id
1.297     matthew  13662: 
1.1235    raeburn  13663: =item $first, student's first name
1.297     matthew  13664: 
                   13665: =item $middle
                   13666: 
                   13667: =item $last
                   13668: 
                   13669: =item $gene
                   13670: 
                   13671: =item $usec
                   13672: 
                   13673: =item $end
                   13674: 
                   13675: =item $start
                   13676: 
1.957     raeburn  13677: =item $type
                   13678: 
                   13679: =item $locktype
                   13680: 
                   13681: =item $cid
                   13682: 
                   13683: =item $selfenroll
                   13684: 
                   13685: =item $context
                   13686: 
1.1216    raeburn  13687: =item $credits, number of credits student will earn from this class
                   13688: 
1.297     matthew  13689: =back
                   13690: 
1.191     harris41 13691: 
                   13692: =item *
                   13693: 
1.243     albertel 13694: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13695: custom role; give a custom role to a user for the level given by URL.  Specify
                   13696: name and domain of role author, and role name
1.191     harris41 13697: 
                   13698: =item *
                   13699: 
1.243     albertel 13700: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13701: 
                   13702: =item *
                   13703: 
1.243     albertel 13704: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13705: 
                   13706: =back
                   13707: 
                   13708: =head2 Course Infomation
                   13709: 
                   13710: =over 4
1.191     harris41 13711: 
                   13712: =item *
                   13713: 
1.1118    foxr     13714: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13715: specified course id, including all environment settings for the
                   13716: course, the description of the course will be in the hash under the
                   13717: key 'description'
1.191     harris41 13718: 
1.1118    foxr     13719: $options is an optional parameter that if supplied is a hash reference that controls
                   13720: what how this function works.  It has the following key/values:
                   13721: 
                   13722: =over 4
                   13723: 
                   13724: =item freshen_cache
                   13725: 
                   13726: If defined, and the environment cache for the course is valid, it is 
                   13727: returned in the returned hash.
                   13728: 
                   13729: =item one_time
                   13730: 
                   13731: If defined, the last cache time is set to _now_
                   13732: 
                   13733: =item user
                   13734: 
                   13735: If defined, the supplied username is used instead of the current user.
                   13736: 
                   13737: 
                   13738: =back
                   13739: 
1.191     harris41 13740: =item *
                   13741: 
1.624     albertel 13742: resdata($name,$domain,$type,@which) : request for current parameter
                   13743: setting for a specific $type, where $type is either 'course' or 'user',
                   13744: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13745: answers for 10 minutes.
1.243     albertel 13746: 
1.877     foxr     13747: =item *
                   13748: 
                   13749: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13750: data base, returning a hash that is keyed by the resource name and has
                   13751: values that are the resource value.  I believe that the timestamps and
                   13752: versions are also returned.
                   13753: 
1.1236    raeburn  13754: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13755: supplemental content area. This routine caches the number of files for 
                   13756: 10 minutes.
                   13757: 
1.243     albertel 13758: =back
                   13759: 
                   13760: =head2 Course Modification
                   13761: 
                   13762: =over 4
1.191     harris41 13763: 
                   13764: =item *
                   13765: 
1.243     albertel 13766: writecoursepref($courseid,%prefs) : write preferences (environment
                   13767: database) for a course
1.191     harris41 13768: 
                   13769: =item *
                   13770: 
1.1011    raeburn  13771: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13772: 
                   13773: =item *
                   13774: 
1.1038    raeburn  13775: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13776: 
1.1167    droeschl 13777: =item *
                   13778: 
                   13779: is_course($courseid), is_course($cdom, $cnum)
                   13780: 
                   13781: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13782: two component version $cdom, $cnum. It checks if the specified course exists.
                   13783: 
                   13784: Returns:
                   13785:     undef if the course doesn't exist, otherwise
                   13786:     in scalar context the combined courseid.
                   13787:     in list context the two components of the course identifier, domain and 
                   13788:     courseid.    
                   13789: 
1.243     albertel 13790: =back
                   13791: 
                   13792: =head2 Resource Subroutines
                   13793: 
                   13794: =over 4
1.191     harris41 13795: 
                   13796: =item *
                   13797: 
1.243     albertel 13798: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13799: 
                   13800: =item *
                   13801: 
1.243     albertel 13802: repcopy($filename) : subscribes to the requested file, and attempts to
                   13803: replicate from the owning library server, Might return
1.607     raeburn  13804: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13805: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13806: resource. Expects the local filesystem pathname
                   13807: (/home/httpd/html/res/....)
                   13808: 
                   13809: =back
                   13810: 
                   13811: =head2 Resource Information
                   13812: 
                   13813: =over 4
1.191     harris41 13814: 
                   13815: =item *
                   13816: 
1.1228    raeburn  13817: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13818: and returns the value of a variety of different possible values,
                   13819: $varname should be a request string, and the other parameters can be
                   13820: used to specify who and what one is asking about. Ordinarily, $cid 
                   13821: does not need to be specified, as it is retrived from 
                   13822: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13823: within lonuserstate::loadmap() when initializing a course, before
                   13824: $env{'request.course.id'} has been set, so it needs to be provided
                   13825: in that one case.
1.243     albertel 13826: 
                   13827: Possible values for $varname are environment.lastname (or other item
                   13828: from the envirnment hash), user.name (or someother aspect about the
                   13829: user), resource.0.maxtries (or some other part and parameter of a
                   13830: resource)
1.204     albertel 13831: 
                   13832: =item *
                   13833: 
1.243     albertel 13834: directcondval($number) : get current value of a condition; reads from a state
                   13835: string
1.204     albertel 13836: 
                   13837: =item *
                   13838: 
1.243     albertel 13839: condval($condidx) : value of condition index based on state
1.204     albertel 13840: 
                   13841: =item *
                   13842: 
1.243     albertel 13843: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13844: resource's metadata, $what should be either a specific key, or either
                   13845: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13846: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13847: 
                   13848: this function automatically caches all requests
1.191     harris41 13849: 
                   13850: =item *
                   13851: 
1.243     albertel 13852: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13853: network of library servers; returns file handle of where SQL and regex results
                   13854: will be stored for query
1.191     harris41 13855: 
                   13856: =item *
                   13857: 
1.1282    raeburn  13858: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   13859: return symbolic list entry (all arguments optional). 
                   13860: 
                   13861: Args: filename is the filename (including path) for the file for which a symb 
                   13862: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   13863: to check access status if more than one resource was found in the bighash 
                   13864: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   13865: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   13866: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13867: cause possible symbs to be checked to determine if they are subject to content
                   13868: blocking, if so they will not be included as possible symbs; possibles is a
                   13869: ref to a hash, which, as a side effect, will be populated with all possible 
                   13870: symbs (content blocking not tested).
                   13871:  
1.243     albertel 13872: returns the data handle
1.191     harris41 13873: 
                   13874: =item *
                   13875: 
1.1190    raeburn  13876: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13877: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13878: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13879: on failure, user must be in a course, as it assumes the existence of
                   13880: the course initial hash, and uses $env('request.course.id'}.  The third
                   13881: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13882: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13883: encrypted; otherwise it will be null.  
1.191     harris41 13884: 
                   13885: =item *
                   13886: 
1.243     albertel 13887: symbclean($symb) : removes versions numbers from a symb, returns the
                   13888: cleaned symb
1.191     harris41 13889: 
                   13890: =item *
                   13891: 
1.243     albertel 13892: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13893: course map, user must be in a course for it to work.
1.191     harris41 13894: 
                   13895: =item *
                   13896: 
1.243     albertel 13897: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13898: 
                   13899: =item *
                   13900: 
1.243     albertel 13901: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13902: a random seed, all arguments are optional, if they aren't sent it uses the
                   13903: environment to derive them. Note: if symb isn't sent and it can't get one
                   13904: from &symbread it will use the current time as its return value
1.191     harris41 13905: 
                   13906: =item *
                   13907: 
1.243     albertel 13908: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13909: unfakeable, receipt
1.191     harris41 13910: 
                   13911: =item *
                   13912: 
1.620     albertel 13913: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13914: 
                   13915: =item *
                   13916: 
1.243     albertel 13917: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13918: 
                   13919: =item *
                   13920: 
1.243     albertel 13921: 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 13922: 
                   13923: =item *
                   13924: 
1.243     albertel 13925: 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 13926: 
                   13927: =item *
                   13928: 
1.243     albertel 13929: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13930: 
                   13931: =item *
                   13932: 
1.243     albertel 13933: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13934: forcing spreadsheet to reevaluate the resource scores next time.
                   13935: 
1.1195    raeburn  13936: =item * 
                   13937: 
1.1196    raeburn  13938: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13939: when viewing in course context.
1.1195    raeburn  13940: 
1.1196    raeburn  13941:  input: six args -- filename (decluttered), course number, course domain,
                   13942:                     url, symb (if registered) and group (if this is a 
                   13943:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13944: 
1.1196    raeburn  13945:  output: array of five scalars --
1.1195    raeburn  13946:          $cfile -- url for file editing if editable on current server
                   13947:          $home -- homeserver of resource (i.e., for author if published,
                   13948:                                           or course if uploaded.).
                   13949:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13950:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13951:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13952: 
                   13953: =item *
                   13954: 
                   13955: is_course_upload($file,$cnum,$cdom)
                   13956: 
                   13957: Used in course context to determine if current file was uploaded to 
                   13958: the course (i.e., would be found in /userfiles/docs on the course's 
                   13959: homeserver.
                   13960: 
                   13961:   input: 3 args -- filename (decluttered), course number and course domain.
                   13962:   output: boolean -- 1 if file was uploaded.
                   13963: 
1.243     albertel 13964: =back
                   13965: 
                   13966: =head2 Storing/Retreiving Data
                   13967: 
                   13968: =over 4
1.191     harris41 13969: 
                   13970: =item *
                   13971: 
1.1269    raeburn  13972: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   13973: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13974: the remaining args aren't required and if they aren't passed or are '' they will
                   13975: be derived from the env (with the exception of $laststore, which is an 
                   13976: optional arg used when a user's submission is stored in grading).
                   13977: $laststore is $version=$timestamp, where $version is the most recent version
                   13978: number retrieved for the corresponding $symb in the $namespace db file, and
                   13979: $timestamp is the timestamp for that transaction (UNIX time).
                   13980: $laststore is currently only passed when cstore() is called by 
                   13981: structuretags::finalize_storage().
1.191     harris41 13982: 
                   13983: =item *
                   13984: 
1.1269    raeburn  13985: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   13986: but uses critical subroutine
1.191     harris41 13987: 
                   13988: =item *
                   13989: 
1.243     albertel 13990: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13991: all args are optional
1.191     harris41 13992: 
                   13993: =item *
                   13994: 
1.717     albertel 13995: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13996: dumps the complete (or key matching regexp) namespace into a hash
                   13997: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13998: normally &store()ed into
                   13999: 
                   14000: $range should be either an integer '100' (give me the first 100
                   14001:                                            matching records)
                   14002:               or be  two integers sperated by a - with no spaces
                   14003:                  '30-50' (give me the 30th through the 50th matching
                   14004:                           records)
                   14005: 
                   14006: 
                   14007: =item *
                   14008: 
1.1269    raeburn  14009: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14010: replaces a &store() version of data with a replacement set of data
                   14011: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14012: reference. If $tolog is true, the transaction is logged in the courselog
                   14013: with an action=PUTSTORE.
1.717     albertel 14014: 
                   14015: =item *
                   14016: 
1.243     albertel 14017: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14018: works very similar to store/cstore, but all data is stored in a
                   14019: temporary location and can be reset using tmpreset, $storehash should
                   14020: be a hash reference, returns nothing on success
1.191     harris41 14021: 
                   14022: =item *
                   14023: 
1.243     albertel 14024: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14025: similar to restore, but all data is stored in a temporary location and
                   14026: can be reset using tmpreset. Returns a hash of values on success,
                   14027: error string otherwise.
1.191     harris41 14028: 
                   14029: =item *
                   14030: 
1.243     albertel 14031: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14032: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14033: 
                   14034: =item *
                   14035: 
1.243     albertel 14036: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14037: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14038: 
                   14039: =item *
                   14040: 
1.243     albertel 14041: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14042: namesp ($udom and $uname are optional)
1.191     harris41 14043: 
                   14044: =item *
                   14045: 
1.702     albertel 14046: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14047: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14048: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14049: 
1.702     albertel 14050: $range should be either an integer '100' (give me the first 100
                   14051:                                            matching records)
                   14052:               or be  two integers sperated by a - with no spaces
                   14053:                  '30-50' (give me the 30th through the 50th matching
                   14054:                           records)
1.449     matthew  14055: =item *
                   14056: 
                   14057: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14058: $store can be a scalar, an array reference, or if the amount to be 
                   14059: incremented is > 1, a hash reference.
                   14060: 
                   14061: ($udom and $uname are optional)
1.191     harris41 14062: 
                   14063: =item *
                   14064: 
1.243     albertel 14065: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14066: ($udom and $uname are optional)
1.191     harris41 14067: 
                   14068: =item *
                   14069: 
1.243     albertel 14070: cput($namespace,$storehash,$udom,$uname) : critical put
                   14071: ($udom and $uname are optional)
1.191     harris41 14072: 
                   14073: =item *
                   14074: 
1.748     albertel 14075: newput($namespace,$storehash,$udom,$uname) :
                   14076: 
                   14077: Attempts to store the items in the $storehash, but only if they don't
                   14078: currently exist, if this succeeds you can be certain that you have 
                   14079: successfully created a new key value pair in the $namespace db.
                   14080: 
                   14081: 
                   14082: Args:
                   14083:  $namespace: name of database to store values to
                   14084:  $storehash: hashref to store to the db
                   14085:  $udom: (optional) domain of user containing the db
                   14086:  $uname: (optional) name of user caontaining the db
                   14087: 
                   14088: Returns:
                   14089:  'ok' -> succeeded in storing all keys of $storehash
                   14090:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14091:                         least <key> already existed in the db (other
                   14092:                         requested keys may also already exist)
1.967     bisitz   14093:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14094:  'con_lost' -> unable to contact request server
                   14095:  'refused' -> action was not allowed by remote machine
                   14096: 
                   14097: 
                   14098: =item *
                   14099: 
1.243     albertel 14100: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14101: reference filled in from namesp (encrypts the return communication)
                   14102: ($udom and $uname are optional)
1.191     harris41 14103: 
                   14104: =item *
                   14105: 
1.243     albertel 14106: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14107: critical subroutine
                   14108: 
1.806     raeburn  14109: =item *
                   14110: 
1.860     raeburn  14111: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14112: array reference filled in from namespace found in domain level on either
                   14113: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14114: 
                   14115: =item *
                   14116: 
1.860     raeburn  14117: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14118: domain level either on specified domain server ($uhome) or primary domain 
                   14119: server ($udom and $uhome are optional)
1.806     raeburn  14120: 
1.943     raeburn  14121: =item * 
                   14122: 
1.1240    raeburn  14123: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14124: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14125: the target domain.
                   14126: 
                   14127: May also include additional key => value pairs for the following groups:
                   14128: 
                   14129: =over
                   14130: 
                   14131: =item
                   14132: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14133: 
                   14134: =over
                   14135: 
                   14136: =item defaultquota, authorquota
                   14137: 
                   14138: =back
                   14139: 
                   14140: =item
                   14141: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14142: portfolio for users).
                   14143: 
                   14144: =over
                   14145: 
                   14146: =item
                   14147: aboutme, blog, webdav, portfolio
                   14148: 
                   14149: =back
                   14150: 
                   14151: =item
                   14152: requestcourses: ability to request courses, and how requests are processed.
                   14153: 
                   14154: =over
                   14155: 
                   14156: =item
1.1246    raeburn  14157: official, unofficial, community, textbook
1.1240    raeburn  14158: 
                   14159: =back
                   14160: 
                   14161: =item
                   14162: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14163: 
                   14164: =over
                   14165: 
                   14166: =item
1.1256    raeburn  14167: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14168: 
                   14169: =back
                   14170: 
                   14171: =item
                   14172: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14173: for course's uploaded content.
                   14174: 
                   14175: =over
                   14176: 
                   14177: =item
1.1246    raeburn  14178: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   14179: communityquota, textbookquota
1.1240    raeburn  14180: 
                   14181: =back
                   14182: 
                   14183: =item
                   14184: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14185: on your servers.
                   14186: 
                   14187: =over
                   14188: 
                   14189: =item 
                   14190: remotesessions, hostedsessions
                   14191: 
                   14192: =back
                   14193: 
                   14194: =back
                   14195: 
                   14196: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14197: utility to create a configuration.db file on a domain's primary library server 
                   14198: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14199: -- corresponding values are authentication type (internal, krb4, krb5,
                   14200: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14201: will be available. Values are retrieved from cache (if current), unless the
                   14202: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14203: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14204: 
                   14205: Typical usage:
1.943     raeburn  14206: 
1.1240    raeburn  14207: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14208: 
1.243     albertel 14209: =back
                   14210: 
                   14211: =head2 Network Status Functions
                   14212: 
                   14213: =over 4
1.191     harris41 14214: 
                   14215: =item *
                   14216: 
1.1137    raeburn  14217: dirlist() : return directory list based on URI (first arg).
                   14218: 
                   14219: Inputs: 1 required, 5 optional.
                   14220: 
                   14221: =over
                   14222: 
                   14223: =item 
                   14224: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14225: 
                   14226: =item
                   14227: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14228: 
                   14229: =item
                   14230: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14231: 
                   14232: =item
                   14233: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14234: 
                   14235: =item
                   14236: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14237: 
                   14238: =item 
                   14239: $alternateRoot - path to prepend in place of path from $uri.
                   14240: 
                   14241: =back
                   14242: 
                   14243: Returns: Array of up to two items.
                   14244: 
                   14245: =over
                   14246: 
                   14247: a reference to an array of files/subdirectories
                   14248: 
                   14249: =over
                   14250: 
                   14251: Each element in the array of files/subdirectories is a & separated list of
                   14252: item name and the result of running stat on the item.  If dirlist was requested
                   14253: for a file instead of a directory, the item name will be ''. For a directory 
                   14254: listing, if the item is a metadata file, the element will end &N&M 
                   14255: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14256: default copyright set (1).  
                   14257: 
                   14258: =back
                   14259: 
                   14260: a scalar containing error condition (if encountered).
                   14261: 
                   14262: =over
                   14263: 
                   14264: =item 
                   14265: no_host (no homeserver identified for $username:$domain).
                   14266: 
                   14267: =item 
                   14268: no_such_host (server contacted for listing not identified as valid host).
                   14269: 
                   14270: =item 
                   14271: con_lost (connection to remote server failed).
                   14272: 
                   14273: =item 
                   14274: refused (invalid $username:$domain received on lond side).
                   14275: 
                   14276: =item 
                   14277: no_such_dir (directory at specified path on lond side does not exist). 
                   14278: 
                   14279: =item 
                   14280: empty (directory at specified path on lond side is empty).
                   14281: 
                   14282: =over
                   14283: 
                   14284: This is currently not encountered because the &ls3, &ls2, 
                   14285: &ls (_handler) routines on the lond side do not filter out
                   14286: . and .. from a directory listing. 
                   14287: 
                   14288: =back
                   14289: 
                   14290: =back
                   14291: 
                   14292: =back
1.191     harris41 14293: 
                   14294: =item *
                   14295: 
1.243     albertel 14296: spareserver() : find server with least workload from spare.tab
                   14297: 
1.986     foxr     14298: 
                   14299: =item *
                   14300: 
                   14301: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14302: if there is no corresponding loncapa host.
                   14303: 
1.243     albertel 14304: =back
                   14305: 
1.986     foxr     14306: 
1.243     albertel 14307: =head2 Apache Request
                   14308: 
                   14309: =over 4
1.191     harris41 14310: 
                   14311: =item *
                   14312: 
1.243     albertel 14313: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14314: localhost, posts hash
                   14315: 
                   14316: =back
                   14317: 
                   14318: =head2 Data to String to Data
                   14319: 
                   14320: =over 4
1.191     harris41 14321: 
                   14322: =item *
                   14323: 
1.243     albertel 14324: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14325: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14326: 
                   14327: =item *
                   14328: 
1.243     albertel 14329: hashref2str($hashref) : convert a hashref into a string complete with
                   14330: escaping and '=' and '&' separators, supports elements that are
                   14331: arrayrefs and hashrefs
1.191     harris41 14332: 
                   14333: =item *
                   14334: 
1.243     albertel 14335: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14336: with escaping and '&' separators, supports elements that are arrayrefs
                   14337: and hashrefs
1.191     harris41 14338: 
                   14339: =item *
                   14340: 
1.243     albertel 14341: str2hash($string) : convert string to hash using unescaping and
                   14342: splitting on '=' and '&', supports elements that are arrayrefs and
                   14343: hashrefs
1.191     harris41 14344: 
                   14345: =item *
                   14346: 
1.243     albertel 14347: str2array($string) : convert string to hash using unescaping and
                   14348: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14349: 
                   14350: =back
                   14351: 
                   14352: =head2 Logging Routines
                   14353: 
                   14354: 
                   14355: These routines allow one to make log messages in the lonnet.log and
                   14356: lonnet.perm logfiles.
1.191     harris41 14357: 
1.1119    foxr     14358: =over 4
                   14359: 
1.191     harris41 14360: =item *
                   14361: 
1.243     albertel 14362: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14363: 
                   14364: =item *
                   14365: 
1.243     albertel 14366: logthis() : append message to the normal lonnet.log file, it gets
                   14367: preiodically rolled over and deleted.
1.191     harris41 14368: 
                   14369: =item *
                   14370: 
1.243     albertel 14371: logperm() : append a permanent message to lonnet.perm.log, this log
                   14372: file never gets deleted by any automated portion of the system, only
                   14373: messages of critical importance should go in here.
                   14374: 
1.1119    foxr     14375: 
1.243     albertel 14376: =back
                   14377: 
                   14378: =head2 General File Helper Routines
                   14379: 
                   14380: =over 4
1.191     harris41 14381: 
                   14382: =item *
                   14383: 
1.481     raeburn  14384: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14385: (a) files in /uploaded
                   14386:   (i) If a local copy of the file exists - 
                   14387:       compares modification date of local copy with last-modified date for 
                   14388:       definitive version stored on home server for course. If local copy is 
                   14389:       stale, requests a new version from the home server and stores it. 
                   14390:       If the original has been removed from the home server, then local copy 
                   14391:       is unlinked.
                   14392:   (ii) If local copy does not exist -
                   14393:       requests the file from the home server and stores it. 
                   14394:   
                   14395:   If $caller is 'uploadrep':  
                   14396:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14397:     for request for files originally uploaded via DOCS. 
                   14398:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14399:   
                   14400:   Otherwise:
                   14401:      This indicates a call from the content generation phase of the request.
                   14402:      -  returns the entire contents of the file or -1.
                   14403:      
                   14404: (b) files in /res
                   14405:    - returns the entire contents of a file or -1; 
                   14406:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14407: 
1.712     albertel 14408: 
                   14409: =item *
                   14410: 
                   14411: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14412:                   reference
                   14413: 
                   14414: returns either a stat() list of data about the file or an empty list
                   14415: if the file doesn't exist or couldn't find out about it (connection
                   14416: problems or user unknown)
                   14417: 
1.191     harris41 14418: =item *
                   14419: 
1.243     albertel 14420: filelocation($dir,$file) : returns file system location of a file
                   14421: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14422: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14423: and a file of ../bob will become /a/bob)
1.191     harris41 14424: 
                   14425: =item *
                   14426: 
                   14427: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14428: filelocation except for hrefs
                   14429: 
                   14430: =item *
                   14431: 
1.1261    raeburn  14432: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14433: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14434: 
1.243     albertel 14435: =back
                   14436: 
1.608     albertel 14437: =head2 Usererfile file routines (/uploaded*)
                   14438: 
                   14439: =over 4
                   14440: 
                   14441: =item *
                   14442: 
                   14443: userfileupload(): main rotine for putting a file in a user or course's
                   14444:                   filespace, arguments are,
                   14445: 
1.620     albertel 14446:  formname - required - this is the name of the element in $env where the
1.608     albertel 14447:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14448:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14449:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14450:  context - if coursedoc, store the file in the course of the active role
                   14451:              of the current user; 
                   14452:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14453:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14454:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14455:          if undefined, it will be placed in "unknown"
                   14456: 
                   14457:  (This routine calls clean_filename() to remove any dangerous
                   14458:  characters from the filename, and then calls finuserfileupload() to
                   14459:  complete the transaction)
                   14460: 
                   14461:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14462:  and /adm/notfound.html if unsuccessful
                   14463: 
                   14464: =item *
                   14465: 
                   14466: clean_filename(): routine for cleaing a filename up for storage in
                   14467:                  userfile space, argument is:
                   14468: 
                   14469:  filename - proposed filename
                   14470: 
                   14471: returns: the new clean filename
                   14472: 
                   14473: =item *
                   14474: 
1.1090    raeburn  14475: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14476: userspace, probably shouldn't be called directly
                   14477: 
                   14478:   docuname: username or courseid of destination for the file
                   14479:   docudom: domain of user/course of destination for the file
                   14480:   formname: same as for userfileupload()
1.1090    raeburn  14481:   fname: filename (including subdirectories) for the file
                   14482:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14483:   allfiles: reference to hash used to store objects found by parser
                   14484:   codebase: reference to hash used for codebases of java objects found by parser
                   14485:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14486:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14487:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14488:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14489:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14490:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14491:   mimetype: reference to scalar to accommodate mime type determined
                   14492:             from File::MMagic if $parser = parse.
1.608     albertel 14493: 
                   14494:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14495:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14496:  was 'overwrite').
                   14497:  
1.608     albertel 14498: 
                   14499: =item *
                   14500: 
                   14501: renameuserfile(): renames an existing userfile to a new name
                   14502: 
                   14503:   Args:
                   14504:    docuname: username or courseid of destination for the file
                   14505:    docudom: domain of user/course of destination for the file
                   14506:    old: current file name (including any subdirs under userfiles)
                   14507:    new: desired file name (including any subdirs under userfiles)
                   14508: 
                   14509: =item *
                   14510: 
                   14511: mkdiruserfile(): creates a directory is a userfiles dir
                   14512: 
                   14513:   Args:
                   14514:    docuname: username or courseid of destination for the file
                   14515:    docudom: domain of user/course of destination for the file
                   14516:    dir: dir to create (including any subdirs under userfiles)
                   14517: 
                   14518: =item *
                   14519: 
                   14520: removeuserfile(): removes a file that exists in userfiles
                   14521: 
                   14522:   Args:
                   14523:    docuname: username or courseid of destination for the file
                   14524:    docudom: domain of user/course of destination for the file
                   14525:    fname: filname to delete (including any subdirs under userfiles)
                   14526: 
                   14527: =item *
                   14528: 
                   14529: removeuploadedurl(): convience function for removeuserfile()
                   14530: 
                   14531:   Args:
                   14532:    url:  a full /uploaded/... url to delete
                   14533: 
1.747     albertel 14534: =item * 
                   14535: 
                   14536: get_portfile_permissions():
                   14537:   Args:
                   14538:     domain: domain of user or course contain the portfolio files
                   14539:     user: name of user or num of course contain the portfolio files
                   14540:   Returns:
                   14541:     hashref of a dump of the proper file_permissions.db
                   14542:    
                   14543: 
                   14544: =item * 
                   14545: 
                   14546: get_access_controls():
                   14547: 
                   14548: Args:
                   14549:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14550:   group: (optional) the group you want the files associated with
                   14551:   file: (optional) the file you want access info on
                   14552: 
                   14553: Returns:
1.749     raeburn  14554:     a hash (keys are file names) of hashes containing
                   14555:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14556:         values are XML containing access control settings (see below) 
1.747     albertel 14557: 
                   14558: Internal notes:
                   14559: 
1.749     raeburn  14560:  access controls are stored in file_permissions.db as key=value pairs.
                   14561:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14562:         where scope -> public,guest,course,group,domains or users.
                   14563:               end -> UNIX time for end of access (0 -> no end date)
                   14564:               start -> UNIX time for start of access
                   14565: 
                   14566:     value -> XML description of access control
                   14567:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14568:             <start></start>
                   14569:             <end></end>
                   14570: 
                   14571:             <password></password>  for scope type = guest
                   14572: 
                   14573:             <domain></domain>     for scope type = course or group
                   14574:             <number></number>
                   14575:             <roles id="">
                   14576:              <role></role>
                   14577:              <access></access>
                   14578:              <section></section>
                   14579:              <group></group>
                   14580:             </roles>
                   14581: 
                   14582:             <dom></dom>         for scope type = domains
                   14583: 
                   14584:             <users>             for scope type = users
                   14585:              <user>
                   14586:               <uname></uname>
                   14587:               <udom></udom>
                   14588:              </user>
                   14589:             </users>
                   14590:            </scope> 
                   14591:               
                   14592:  Access data is also aggregated for each file in an additional key=value pair:
                   14593:  key -> path to file/file_name\0accesscontrol 
                   14594:  value -> reference to hash
                   14595:           hash contains key = value pairs
                   14596:           where key = uniqueID:scope_end_start
                   14597:                 value = UNIX time record was last updated
                   14598: 
                   14599:           Used to improve speed of look-ups of access controls for each file.  
                   14600:  
                   14601:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14602: 
1.1198    raeburn  14603: =item *
                   14604: 
1.749     raeburn  14605: modify_access_controls():
                   14606: 
                   14607: Modifies access controls for a portfolio file
                   14608: Args
                   14609: 1. file name
                   14610: 2. reference to hash of required changes,
                   14611: 3. domain
                   14612: 4. username
                   14613:   where domain,username are the domain of the portfolio owner 
                   14614:   (either a user or a course) 
                   14615: 
                   14616: Returns:
                   14617: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14618: 2. result of deletions ('ok' or 'error', with error message).
                   14619: 3. reference to hash of any new or updated access controls.
                   14620: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14621:    key = integer (inbound ID)
1.1198    raeburn  14622:    value = uniqueID
                   14623: 
                   14624: =item *
                   14625: 
                   14626: get_timebased_id():
                   14627: 
                   14628: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14629: course via the Course Editor (e.g., folders, composite pages, 
                   14630: group bulletin boards).
                   14631: 
                   14632: Args: (first three required; six others optional)
                   14633: 
                   14634: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14635:    docssequence, or name of group
                   14636: 
                   14637: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14638:    e.g., num, boardids
                   14639: 
                   14640: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14641:    file will be named nohist_namespace.db
                   14642: 
                   14643: 4. cdom: domain of course; default is current course domain from %env
                   14644: 
                   14645: 5. cnum: course number; default is current course number from %env
                   14646: 
                   14647: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14648:    unix timestamp to form the suffix, if the plain timestamp is already
                   14649:    in use.  Default is to not do this, but simply increment the unix 
                   14650:    timestamp by 1 until a unique key is obtained.
                   14651: 
                   14652: 7. who: holder of locking key; defaults to user:domain for user.
                   14653: 
                   14654: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14655:    retrying); default is 3.
                   14656: 
                   14657: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14658: 
                   14659: Returns:
                   14660: 
                   14661: 1. suffix obtained (numeric)
                   14662: 
                   14663: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14664: 
                   14665: 3. error: contains (localized) error message if an error occurred.
                   14666: 
1.747     albertel 14667: 
1.608     albertel 14668: =back
                   14669: 
1.243     albertel 14670: =head2 HTTP Helper Routines
                   14671: 
                   14672: =over 4
                   14673: 
1.191     harris41 14674: =item *
                   14675: 
                   14676: escape() : unpack non-word characters into CGI-compatible hex codes
                   14677: 
                   14678: =item *
                   14679: 
                   14680: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14681: 
1.243     albertel 14682: =back
                   14683: 
                   14684: =head1 PRIVATE SUBROUTINES
                   14685: 
                   14686: =head2 Underlying communication routines (Shouldn't call)
                   14687: 
                   14688: =over 4
                   14689: 
                   14690: =item *
                   14691: 
                   14692: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14693: 
                   14694: =item *
                   14695: 
                   14696: reply() : uses subreply to send a message to remote machine, logs all failures
                   14697: 
                   14698: =item *
                   14699: 
                   14700: critical() : passes a critical message to another server; if cannot
                   14701: get through then place message in connection buffer directory and
                   14702: returns con_delayed, if incapable of saving message, returns
                   14703: con_failed
                   14704: 
                   14705: =item *
                   14706: 
                   14707: reconlonc() : tries to reconnect lonc client processes.
                   14708: 
                   14709: =back
                   14710: 
                   14711: =head2 Resource Access Logging
                   14712: 
                   14713: =over 4
                   14714: 
                   14715: =item *
                   14716: 
                   14717: flushcourselogs() : flush (save) buffer logs and access logs
                   14718: 
                   14719: =item *
                   14720: 
                   14721: courselog($what) : save message for course in hash
                   14722: 
                   14723: =item *
                   14724: 
                   14725: courseacclog($what) : save message for course using &courselog().  Perform
                   14726: special processing for specific resource types (problems, exams, quizzes, etc).
                   14727: 
1.191     harris41 14728: =item *
                   14729: 
                   14730: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14731: as a PerlChildExitHandler
1.243     albertel 14732: 
                   14733: =back
                   14734: 
                   14735: =head2 Other
                   14736: 
                   14737: =over 4
                   14738: 
                   14739: =item *
                   14740: 
                   14741: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14742: 
                   14743: =back
                   14744: 
                   14745: =cut
1.877     foxr     14746: 

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