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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1307  ! raeburn     4: # $Id: lonnet.pm,v 1.1306 2016/04/15 18:53:38 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);
1.1307  ! raeburn  1291:     my $domneedscache;
1.1129    raeburn  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.1307  ! raeburn  1306:         } else {
        !          1307:             $domneedscache = $dom_in_use;
1.1129    raeburn  1308:         }
                   1309:     }
                   1310:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1311:         ($is_balancer,$currtargets,$currrules) = 
                   1312:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1313:         if ($is_balancer) {
                   1314:             if (ref($currrules) eq 'HASH') {
                   1315:                 if ($homeintdom) {
                   1316:                     if ($uname ne '') {
                   1317:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1318:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1319:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1320:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1321:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1322:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1323:                             }
                   1324:                         }
                   1325:                         if ($rule_in_effect eq '') {
                   1326:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1327:                             if ($userenv{'inststatus'} ne '') {
                   1328:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1329:                                 my ($othertitle,$usertypes,$types) =
                   1330:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1331:                                 if (ref($types) eq 'ARRAY') {
                   1332:                                     foreach my $type (@{$types}) {
                   1333:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1334:                                             if (exists($currrules->{$type})) {
                   1335:                                                 $rule_in_effect = $currrules->{$type};
                   1336:                                             }
                   1337:                                         }
                   1338:                                     }
                   1339:                                 }
                   1340:                             } else {
                   1341:                                 if (exists($currrules->{'default'})) {
                   1342:                                     $rule_in_effect = $currrules->{'default'};
                   1343:                                 }
                   1344:                             }
                   1345:                         }
                   1346:                     } else {
                   1347:                         if (exists($currrules->{'default'})) {
                   1348:                             $rule_in_effect = $currrules->{'default'};
                   1349:                         }
                   1350:                     }
                   1351:                 } else {
                   1352:                     if ($currrules->{'_LC_external'} ne '') {
                   1353:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1354:                     }
                   1355:                 }
                   1356:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1357:                                                        $uname,$udom);
                   1358:             }
                   1359:         }
                   1360:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1361:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1362:         unless (defined($cached)) {
                   1363:             my %domconfig =
                   1364:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1365:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307  ! raeburn  1366:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
        !          1367:             } else {
        !          1368:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1369:             }
                   1370:         }
                   1371:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1372:             ($is_balancer,$currtargets,$currrules) = 
                   1373:                 &check_balancer_result($result,@hosts);
                   1374:             if ($is_balancer) {
1.1129    raeburn  1375:                 if (ref($currrules) eq 'HASH') {
                   1376:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1377:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1378:                     }
                   1379:                 }
                   1380:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1381:                                                        $uname,$udom);
                   1382:             }
                   1383:         } else {
                   1384:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1385:                 $is_balancer = 1;
                   1386:                 $offloadto = &this_host_spares($dom_in_use);
                   1387:             }
1.1307  ! raeburn  1388:             unless (defined($cached)) {
        !          1389:                 $domneedscache = $serverhomedom;
        !          1390:             }
1.1129    raeburn  1391:         }
                   1392:     } else {
                   1393:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1394:             $is_balancer = 1;
                   1395:             $offloadto = &this_host_spares($dom_in_use);
                   1396:         }
1.1307  ! raeburn  1397:         unless (defined($cached)) {
        !          1398:             $domneedscache = $serverhomedom;
        !          1399:         }
        !          1400:     }
        !          1401:     if ($domneedscache) {
        !          1402:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1403:     }
1.1176    raeburn  1404:     if ($is_balancer) {
                   1405:         my $lowest_load = 30000;
                   1406:         if (ref($offloadto) eq 'HASH') {
                   1407:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1408:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1409:                     ($otherserver,$lowest_load) =
                   1410:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1411:                 }
1.1129    raeburn  1412:             }
1.1176    raeburn  1413:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1414: 
1.1176    raeburn  1415:             if (!$found_server) {
                   1416:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1417:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1418:                         ($otherserver,$lowest_load) =
                   1419:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1420:                     }
                   1421:                 }
                   1422:             }
                   1423:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1424:             if (@{$offloadto} == 1) {
                   1425:                 $otherserver = $offloadto->[0];
                   1426:             } elsif (@{$offloadto} > 1) {
                   1427:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1428:                     ($otherserver,$lowest_load) =
                   1429:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1430:                 }
                   1431:             }
                   1432:         }
1.1176    raeburn  1433:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1434:             $is_balancer = 0;
                   1435:             if ($uname ne '' && $udom ne '') {
                   1436:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1437:                     
                   1438:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1439:                              'user.loadbalcheck.time' => time});
                   1440:                 }
1.1129    raeburn  1441:             }
                   1442:         }
                   1443:     }
                   1444:     return ($is_balancer,$otherserver);
                   1445: }
                   1446: 
1.1191    raeburn  1447: sub check_balancer_result {
                   1448:     my ($result,@hosts) = @_;
                   1449:     my ($is_balancer,$currtargets,$currrules);
                   1450:     if (ref($result) eq 'HASH') {
                   1451:         if ($result->{'lonhost'} ne '') {
                   1452:             my $currbalancer = $result->{'lonhost'};
                   1453:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1454:                 $is_balancer = 1;
                   1455:                 $currtargets = $result->{'targets'};
                   1456:                 $currrules = $result->{'rules'};
                   1457:             }
                   1458:         } else {
                   1459:             foreach my $key (keys(%{$result})) {
                   1460:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1461:                     (ref($result->{$key}) eq 'HASH')) {
                   1462:                     $is_balancer = 1;
                   1463:                     $currrules = $result->{$key}{'rules'};
                   1464:                     $currtargets = $result->{$key}{'targets'};
                   1465:                     last;
                   1466:                 }
                   1467:             }
                   1468:         }
                   1469:     }
                   1470:     return ($is_balancer,$currtargets,$currrules);
                   1471: }
                   1472: 
1.1129    raeburn  1473: sub get_loadbalancer_targets {
                   1474:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1475:     my $offloadto;
1.1175    raeburn  1476:     if ($rule_in_effect eq 'none') {
                   1477:         return [$perlvar{'lonHostID'}];
                   1478:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1479:         $offloadto = $currtargets;
                   1480:     } else {
                   1481:         if ($rule_in_effect eq 'homeserver') {
                   1482:             my $homeserver = &homeserver($uname,$udom);
                   1483:             if ($homeserver ne 'no_host') {
                   1484:                 $offloadto = [$homeserver];
                   1485:             }
                   1486:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1487:             my %domconfig =
                   1488:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1489:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1490:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1491:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1492:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1493:                     }
                   1494:                 }
                   1495:             } else {
1.1178    raeburn  1496:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1497:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1498:                 if (&hostname($remotebalancer) ne '') {
                   1499:                     $offloadto = [$remotebalancer];
                   1500:                 }
                   1501:             }
                   1502:         } elsif (&hostname($rule_in_effect) ne '') {
                   1503:             $offloadto = [$rule_in_effect];
                   1504:         }
                   1505:     }
                   1506:     return $offloadto;
                   1507: }
                   1508: 
1.1127    raeburn  1509: sub internet_dom_servers {
                   1510:     my ($dom) = @_;
                   1511:     my (%uniqservers,%servers);
                   1512:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1513:     my @machinedoms = &machine_domains($primaryserver);
                   1514:     foreach my $mdom (@machinedoms) {
                   1515:         my %currservers = %servers;
                   1516:         my %server = &get_servers($mdom);
                   1517:         %servers = (%currservers,%server);
                   1518:     }
                   1519:     my %by_hostname;
                   1520:     foreach my $id (keys(%servers)) {
                   1521:         push(@{$by_hostname{$servers{$id}}},$id);
                   1522:     }
                   1523:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1524:         if (@{$by_hostname{$hostname}} > 1) {
                   1525:             my $match = 0;
                   1526:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1527:                 if (&host_domain($id) eq $dom) {
                   1528:                     $uniqservers{$id} = $hostname;
                   1529:                     $match = 1;
                   1530:                 }
                   1531:             }
                   1532:             unless ($match) {
                   1533:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1534:             }
                   1535:         } else {
                   1536:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1537:         }
                   1538:     }
                   1539:     return %uniqservers;
                   1540: }
                   1541: 
1.1       albertel 1542: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1543: 
1.599     albertel 1544: my %homecache;
1.1       albertel 1545: sub homeserver {
1.230     stredwic 1546:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1547:     my $index="$uname:$udom";
1.426     albertel 1548: 
1.599     albertel 1549:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1550: 
                   1551:     my %servers = &get_servers($udom,'library');
                   1552:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1553:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1554: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1555: 
                   1556: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1557: 	if ($answer eq 'found') {
                   1558: 	    delete($badServerCache{$tryserver}); 
                   1559: 	    return $homecache{$index}=$tryserver;
                   1560: 	} elsif ($answer eq 'no_host') {
                   1561: 	    $badServerCache{$tryserver}=1;
                   1562: 	}
1.1       albertel 1563:     }    
                   1564:     return 'no_host';
1.70      www      1565: }
                   1566: 
1.1300    raeburn  1567: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1568: 
                   1569: sub idget {
1.1300    raeburn  1570:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1571:     my %returnhash=();
1.1300    raeburn  1572:     my @ids=(); 
                   1573:     if (ref($idsref) eq 'ARRAY') {
                   1574:         @ids = @{$idsref};
                   1575:     } else {
                   1576:         return %returnhash; 
                   1577:     }
                   1578:     if ($namespace eq '') {
                   1579:         $namespace = 'ids';
                   1580:     }
1.70      www      1581:     
1.841     albertel 1582:     my %servers = &get_servers($udom,'library');
                   1583:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1584: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1585: 	if ($namespace eq 'ids') {
                   1586: 	    $idlist=~tr/A-Z/a-z/;
                   1587: 	}
                   1588: 	my $reply;
                   1589: 	if ($namespace eq 'ids') {
                   1590: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1591: 	} else {
                   1592: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1593: 	}
1.841     albertel 1594: 	my @answer=();
                   1595: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1596: 	    @answer=split(/\&/,$reply);
                   1597: 	}                    ;
                   1598: 	my $i;
                   1599: 	for ($i=0;$i<=$#ids;$i++) {
                   1600: 	    if ($answer[$i]) {
1.1299    raeburn  1601: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1602: 	    }
1.841     albertel 1603: 	}
1.1300    raeburn  1604:     }
1.70      www      1605:     return %returnhash;
                   1606: }
                   1607: 
                   1608: # ------------------------------------- Find the IDs behind a list of usernames
                   1609: 
                   1610: sub idrget {
                   1611:     my ($udom,@unames)=@_;
                   1612:     my %returnhash=();
1.800     albertel 1613:     foreach my $uname (@unames) {
                   1614:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1615:     }
1.70      www      1616:     return %returnhash;
                   1617: }
                   1618: 
1.1300    raeburn  1619: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1620: 
                   1621: sub idput {
1.1300    raeburn  1622:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1623:     my %servers=();
1.1300    raeburn  1624:     my %ids=();
                   1625:     my %byid = ();
                   1626:     if (ref($idsref) eq 'HASH') {
                   1627:         %ids=%{$idsref};
                   1628:     }
                   1629:     if ($namespace eq '') {
                   1630:         $namespace = 'ids'; 
                   1631:     }
1.800     albertel 1632:     foreach my $uname (keys(%ids)) {
                   1633: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1634:         if ($uhom eq '') {
                   1635:             $uhom=&homeserver($uname,$udom);
                   1636:         }
1.70      www      1637:         if ($uhom ne 'no_host') {
1.800     albertel 1638:             my $esc_unam=&escape($uname);
1.1300    raeburn  1639:             if ($namespace eq 'ids') {
                   1640:                 my $id=&escape($ids{$uname});
                   1641:                 $id=~tr/A-Z/a-z/;
                   1642:                 my $esc_unam=&escape($uname);
                   1643:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1644:             } else {
1.1300    raeburn  1645:                 my @currids = split(/,/,$ids{$uname});
                   1646:                 foreach my $id (@currids) {
                   1647:                     $byid{$uhom}{$id} .= $uname.',';
                   1648:                 }
                   1649:             }
                   1650:         }
                   1651:     }
                   1652:     if ($namespace eq 'clickers') {
                   1653:         foreach my $server (keys(%byid)) {
                   1654:             if (ref($byid{$server}) eq 'HASH') {
                   1655:                 foreach my $id (keys(%{$byid{$server}})) {
                   1656:                     $byid{$server} =~ s/,$//;
                   1657:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1658:                 }
1.70      www      1659:             }
                   1660:         }
1.191     harris41 1661:     }
1.800     albertel 1662:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1663:         $servers{$server} =~ s/\&$//;
                   1664:         if ($namespace eq 'ids') {     
                   1665:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1666:         } else {
                   1667:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1668:         }
1.191     harris41 1669:     }
1.344     www      1670: }
                   1671: 
1.1300    raeburn  1672: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1673: 
                   1674: sub iddel {
1.1300    raeburn  1675:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1676:     my %result=();
1.1300    raeburn  1677:     my %ids=();
                   1678:     my %byid = ();
                   1679:     if (ref($idshashref) eq 'HASH') {
                   1680:         %ids=%{$idshashref};
                   1681:     } else {
1.1231    raeburn  1682:         return %result;
                   1683:     }
1.1300    raeburn  1684:     if ($namespace eq '') {
                   1685:         $namespace = 'ids';
                   1686:     }
1.1231    raeburn  1687:     my %servers=();
1.1300    raeburn  1688:     while (my ($id,$unamestr) = each(%ids)) {
                   1689:         if ($namespace eq 'ids') {
                   1690:             my $uhom = $uhome;
                   1691:             if ($uhom eq '') { 
                   1692:                 $uhom=&homeserver($unamestr,$udom);
                   1693:             }
                   1694:             if ($uhom ne 'no_host') {
                   1695:                 $servers{$uhom}.='&'.&escape($id);
                   1696:             }
                   1697:          } else {
                   1698:             my @curritems = split(/,/,$ids{$id});
                   1699:             foreach my $uname (@curritems) {
                   1700:                 my $uhom = $uhome;
                   1701:                 if ($uhom eq '') {
                   1702:                     $uhom=&homeserver($uname,$udom);
                   1703:                 }
                   1704:                 if ($uhom ne 'no_host') { 
                   1705:                     $byid{$uhom}{$id} .= $uname.',';
                   1706:                 }
                   1707:             }
1.1231    raeburn  1708:         }
1.1300    raeburn  1709:     }
                   1710:     if ($namespace eq 'clickers') {
                   1711:         foreach my $server (keys(%byid)) {
                   1712:             if (ref($byid{$server}) eq 'HASH') {
                   1713:                 foreach my $id (keys(%{$byid{$server}})) {
                   1714:                     $byid{$server}{$id} =~ s/,$//;
                   1715:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1716:                 }
1.1231    raeburn  1717:             }
                   1718:         }
                   1719:     }
                   1720:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1721:         $servers{$server} =~ s/\&$//;
                   1722:         if ($namespace eq 'ids') {
                   1723:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1724:         } elsif ($namespace eq 'clickers') {
                   1725:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1726:         }
1.1231    raeburn  1727:     }
                   1728:     return %result;
                   1729: }
                   1730: 
1.1300    raeburn  1731: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1732: 
                   1733: sub updateclickers {
                   1734:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1735:     my %clickers;
                   1736:     if (ref($idshashref) eq 'HASH') {
                   1737:         %clickers=%{$idshashref};
                   1738:     } else {
                   1739:         return;
                   1740:     }
                   1741:     my $items='';
                   1742:     foreach my $item (keys(%clickers)) {
                   1743:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1744:     }
                   1745:     $items=~s/\&$//;
                   1746:     my $request = "updateclickers:$udom:$action:$items";
                   1747:     if ($critical) {
                   1748:         return &critical($request,$uhome);
                   1749:     } else {
                   1750:         return &reply($request,$uhome);
                   1751:     }
                   1752: }
                   1753: 
1.1023    raeburn  1754: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1755: sub dump_dom {
1.1165    droeschl 1756:     my ($namespace, $udom, $regexp) = @_;
                   1757: 
                   1758:     $udom ||= $env{'user.domain'};
                   1759: 
                   1760:     return () unless $udom;
                   1761: 
                   1762:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1763: }
                   1764: 
1.1023    raeburn  1765: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1766: 
                   1767: sub get_dom {
1.860     raeburn  1768:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1769:     return if ($udom eq 'public');
1.806     raeburn  1770:     my $items='';
                   1771:     foreach my $item (@$storearr) {
                   1772:         $items.=&escape($item).'&';
                   1773:     }
                   1774:     $items=~s/\&$//;
1.860     raeburn  1775:     if (!$udom) {
                   1776:         $udom=$env{'user.domain'};
1.1267    raeburn  1777:         return if ($udom eq 'public');
1.860     raeburn  1778:         if (defined(&domain($udom,'primary'))) {
                   1779:             $uhome=&domain($udom,'primary');
                   1780:         } else {
1.874     albertel 1781:             undef($uhome);
1.860     raeburn  1782:         }
                   1783:     } else {
                   1784:         if (!$uhome) {
                   1785:             if (defined(&domain($udom,'primary'))) {
                   1786:                 $uhome=&domain($udom,'primary');
                   1787:             }
                   1788:         }
                   1789:     }
                   1790:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1791:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1792:         my %returnhash;
1.875     albertel 1793:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1794:             return %returnhash;
                   1795:         }
1.806     raeburn  1796:         my @pairs=split(/\&/,$rep);
                   1797:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1798:             return @pairs;
                   1799:         }
                   1800:         my $i=0;
                   1801:         foreach my $item (@$storearr) {
                   1802:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1803:             $i++;
                   1804:         }
                   1805:         return %returnhash;
                   1806:     } else {
1.880     banghart 1807:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1808:     }
                   1809: }
                   1810: 
                   1811: # -------------------------------------------- put items in domain db files 
                   1812: 
                   1813: sub put_dom {
1.860     raeburn  1814:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1815:     if (!$udom) {
                   1816:         $udom=$env{'user.domain'};
                   1817:         if (defined(&domain($udom,'primary'))) {
                   1818:             $uhome=&domain($udom,'primary');
                   1819:         } else {
1.874     albertel 1820:             undef($uhome);
1.860     raeburn  1821:         }
                   1822:     } else {
                   1823:         if (!$uhome) {
                   1824:             if (defined(&domain($udom,'primary'))) {
                   1825:                 $uhome=&domain($udom,'primary');
                   1826:             }
                   1827:         }
                   1828:     } 
                   1829:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1830:         my $items='';
                   1831:         foreach my $item (keys(%$storehash)) {
                   1832:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1833:         }
                   1834:         $items=~s/\&$//;
                   1835:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1836:     } else {
1.860     raeburn  1837:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1838:     }
                   1839: }
                   1840: 
1.1023    raeburn  1841: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1842: sub newput_dom {
1.1023    raeburn  1843:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1844:     my $result;
                   1845:     if (!$udom) {
                   1846:         $udom=$env{'user.domain'};
                   1847:     }
1.1023    raeburn  1848:     if ($udom) {
                   1849:         my $uname = &get_domainconfiguser($udom);
                   1850:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1851:     }
                   1852:     return $result;
                   1853: }
                   1854: 
1.1023    raeburn  1855: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1856: sub del_dom {
1.1023    raeburn  1857:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1858:     if (ref($storearr) eq 'ARRAY') {
                   1859:         if (!$udom) {
                   1860:             $udom=$env{'user.domain'};
                   1861:         }
1.1023    raeburn  1862:         if ($udom) {
                   1863:             my $uname = &get_domainconfiguser($udom); 
                   1864:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1865:         }
                   1866:     }
                   1867: }
                   1868: 
1.1023    raeburn  1869: # ----------------------------------construct domainconfig user for a domain 
                   1870: sub get_domainconfiguser {
                   1871:     my ($udom) = @_;
                   1872:     return $udom.'-domainconfig';
                   1873: }
                   1874: 
1.837     raeburn  1875: sub retrieve_inst_usertypes {
                   1876:     my ($udom) = @_;
                   1877:     my (%returnhash,@order);
1.989     raeburn  1878:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1879:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1880:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1881:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1882:     } else {
                   1883:         if (defined(&domain($udom,'primary'))) {
                   1884:             my $uhome=&domain($udom,'primary');
                   1885:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1886:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1887:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1888:                 return (\%returnhash,\@order);
                   1889:             }
                   1890:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1891:             my @pairs=split(/\&/,$hashitems);
                   1892:             foreach my $item (@pairs) {
                   1893:                 my ($key,$value)=split(/=/,$item,2);
                   1894:                 $key = &unescape($key);
                   1895:                 next if ($key =~ /^error: 2 /);
                   1896:                 $returnhash{$key}=&thaw_unescape($value);
                   1897:             }
                   1898:             my @esc_order = split(/\&/,$orderitems);
                   1899:             foreach my $item (@esc_order) {
                   1900:                 push(@order,&unescape($item));
                   1901:             }
                   1902:         } else {
1.1256    raeburn  1903:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1904:         }
1.1256    raeburn  1905:         return (\%returnhash,\@order);
1.837     raeburn  1906:     }
                   1907: }
                   1908: 
1.868     raeburn  1909: sub is_domainimage {
                   1910:     my ($url) = @_;
1.1306    raeburn  1911:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1912:         if (&domain($1) ne '') {
                   1913:             return '1';
                   1914:         }
                   1915:     }
                   1916:     return;
                   1917: }
                   1918: 
1.899     raeburn  1919: sub inst_directory_query {
                   1920:     my ($srch) = @_;
                   1921:     my $udom = $srch->{'srchdomain'};
                   1922:     my %results;
                   1923:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1924:     my $outcome;
1.899     raeburn  1925:     if ($homeserver ne '') {
1.904     albertel 1926: 	my $queryid=&reply("querysend:instdirsearch:".
                   1927: 			   &escape($srch->{'srchby'}).':'.
                   1928: 			   &escape($srch->{'srchterm'}).':'.
                   1929: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1930: 	my $host=&hostname($homeserver);
                   1931: 	if ($queryid !~/^\Q$host\E\_/) {
                   1932: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1933: 	    return;
                   1934: 	}
                   1935: 	my $response = &get_query_reply($queryid);
                   1936: 	my $maxtries = 5;
                   1937: 	my $tries = 1;
                   1938: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1939: 	    $response = &get_query_reply($queryid);
                   1940: 	    $tries ++;
                   1941: 	}
                   1942: 
                   1943:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1944:             if ($response eq 'unavailable') {
                   1945:                 $outcome = $response;
                   1946:             } else {
                   1947:                 $outcome = 'ok';
                   1948:                 my @matches = split(/\n/,$response);
                   1949:                 foreach my $match (@matches) {
                   1950:                     my ($key,$value) = split(/=/,$match);
                   1951:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1952:                 }
1.899     raeburn  1953:             }
                   1954:         }
                   1955:     }
1.909     raeburn  1956:     return ($outcome,%results);
1.899     raeburn  1957: }
                   1958: 
                   1959: sub usersearch {
                   1960:     my ($srch) = @_;
                   1961:     my $dom = $srch->{'srchdomain'};
                   1962:     my %results;
                   1963:     my %libserv = &all_library();
                   1964:     my $query = 'usersearch';
                   1965:     foreach my $tryserver (keys(%libserv)) {
                   1966:         if (&host_domain($tryserver) eq $dom) {
                   1967:             my $host=&hostname($tryserver);
                   1968:             my $queryid=
1.911     raeburn  1969:                 &reply("querysend:".&escape($query).':'.
                   1970:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1971:                        &escape($srch->{'srchtype'}).':'.
                   1972:                        &escape($srch->{'srchterm'}),$tryserver);
                   1973:             if ($queryid !~/^\Q$host\E\_/) {
                   1974:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1975:                 next;
1.899     raeburn  1976:             }
                   1977:             my $reply = &get_query_reply($queryid);
                   1978:             my $maxtries = 1;
                   1979:             my $tries = 1;
                   1980:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1981:                 $reply = &get_query_reply($queryid);
                   1982:                 $tries ++;
                   1983:             }
                   1984:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1985:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1986:             } else {
1.911     raeburn  1987:                 my @matches;
                   1988:                 if ($reply =~ /\n/) {
                   1989:                     @matches = split(/\n/,$reply);
                   1990:                 } else {
                   1991:                     @matches = split(/\&/,$reply);
                   1992:                 }
1.899     raeburn  1993:                 foreach my $match (@matches) {
                   1994:                     my ($uname,$udom,%userhash);
1.911     raeburn  1995:                     foreach my $entry (split(/:/,$match)) {
                   1996:                         my ($key,$value) =
                   1997:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1998:                         $userhash{$key} = $value;
                   1999:                         if ($key eq 'username') {
                   2000:                             $uname = $value;
                   2001:                         } elsif ($key eq 'domain') {
                   2002:                             $udom = $value;
1.911     raeburn  2003:                         }
1.899     raeburn  2004:                     }
                   2005:                     $results{$uname.':'.$udom} = \%userhash;
                   2006:                 }
                   2007:             }
                   2008:         }
                   2009:     }
                   2010:     return %results;
                   2011: }
                   2012: 
1.912     raeburn  2013: sub get_instuser {
                   2014:     my ($udom,$uname,$id) = @_;
                   2015:     my $homeserver = &domain($udom,'primary');
                   2016:     my ($outcome,%results);
                   2017:     if ($homeserver ne '') {
                   2018:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2019:                            &escape($id).':'.&escape($udom),$homeserver);
                   2020:         my $host=&hostname($homeserver);
                   2021:         if ($queryid !~/^\Q$host\E\_/) {
                   2022:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2023:             return;
                   2024:         }
                   2025:         my $response = &get_query_reply($queryid);
                   2026:         my $maxtries = 5;
                   2027:         my $tries = 1;
                   2028:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2029:             $response = &get_query_reply($queryid);
                   2030:             $tries ++;
                   2031:         }
                   2032:         if (!&error($response) && $response ne 'refused') {
                   2033:             if ($response eq 'unavailable') {
                   2034:                 $outcome = $response;
                   2035:             } else {
                   2036:                 $outcome = 'ok';
                   2037:                 my @matches = split(/\n/,$response);
                   2038:                 foreach my $match (@matches) {
                   2039:                     my ($key,$value) = split(/=/,$match);
                   2040:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2041:                 }
                   2042:             }
                   2043:         }
                   2044:     }
                   2045:     my %userinfo;
                   2046:     if (ref($results{$uname}) eq 'HASH') {
                   2047:         %userinfo = %{$results{$uname}};
                   2048:     } 
                   2049:     return ($outcome,%userinfo);
                   2050: }
                   2051: 
1.1290    raeburn  2052: sub get_multiple_instusers {
                   2053:     my ($udom,$users,$caller) = @_;
                   2054:     my ($outcome,$results);
                   2055:     if (ref($users) eq 'HASH') {
                   2056:         my $count = keys(%{$users}); 
                   2057:         my $requested = &freeze_escape($users);
                   2058:         my $homeserver = &domain($udom,'primary');
                   2059:         if ($homeserver ne '') {
                   2060:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2061:             my $host=&hostname($homeserver);
                   2062:             if ($queryid !~/^\Q$host\E\_/) {
                   2063:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2064:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2065:                 return ($outcome,$results);
                   2066:             }
                   2067:             my $response = &get_query_reply($queryid);
                   2068:             my $maxtries = 5;
                   2069:             if ($count > 100) {
                   2070:                 $maxtries = 1+int($count/20);
                   2071:             }
                   2072:             my $tries = 1;
                   2073:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2074:                 $response = &get_query_reply($queryid);
                   2075:                 $tries ++;
                   2076:             }
                   2077:             if ($response eq '') {
                   2078:                 $results = {};
                   2079:                 foreach my $key (keys(%{$users})) {
                   2080:                     my ($uname,$id);
                   2081:                     if ($caller eq 'id') {
                   2082:                         $id = $key;
                   2083:                     } else {
                   2084:                         $uname = $key;
                   2085:                     }
                   2086:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2087:                     $outcome = $resp;
1.1290    raeburn  2088:                     if ($resp eq 'ok') {
                   2089:                         %{$results} = (%{$results}, %info);
                   2090:                     } else {
                   2091:                         last;
                   2092:                     }
                   2093:                 }
                   2094:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2095:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2096:                     $outcome = $response;
                   2097:                 } else {
1.1291    raeburn  2098:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2099:                     if ($outcome eq 'ok') {
                   2100:                         $results = &thaw_unescape($userdata); 
                   2101:                     }
                   2102:                 }
                   2103:             }
                   2104:         }
                   2105:     }
                   2106:     return ($outcome,$results);
                   2107: }
                   2108: 
1.912     raeburn  2109: sub inst_rulecheck {
1.923     raeburn  2110:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2111:     my %returnhash;
                   2112:     if ($udom ne '') {
                   2113:         if (ref($rules) eq 'ARRAY') {
                   2114:             @{$rules} = map {&escape($_);} (@{$rules});
                   2115:             my $rulestr = join(':',@{$rules});
                   2116:             my $homeserver=&domain($udom,'primary');
                   2117:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2118:                 my $response;
                   2119:                 if ($item eq 'username') {                
                   2120:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2121:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2122:                                               $homeserver));
1.923     raeburn  2123:                 } elsif ($item eq 'id') {
                   2124:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2125:                                               ':'.&escape($id).':'.$rulestr,
                   2126:                                               $homeserver));
1.945     raeburn  2127:                 } elsif ($item eq 'selfcreate') {
                   2128:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2129:                                                &escape($udom).':'.&escape($uname).
                   2130:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2131:                 }
1.912     raeburn  2132:                 if ($response ne 'refused') {
                   2133:                     my @pairs=split(/\&/,$response);
                   2134:                     foreach my $item (@pairs) {
                   2135:                         my ($key,$value)=split(/=/,$item,2);
                   2136:                         $key = &unescape($key);
                   2137:                         next if ($key =~ /^error: 2 /);
                   2138:                         $returnhash{$key}=&thaw_unescape($value);
                   2139:                     }
                   2140:                 }
                   2141:             }
                   2142:         }
                   2143:     }
                   2144:     return %returnhash;
                   2145: }
                   2146: 
                   2147: sub inst_userrules {
1.923     raeburn  2148:     my ($udom,$check) = @_;
1.912     raeburn  2149:     my (%ruleshash,@ruleorder);
                   2150:     if ($udom ne '') {
                   2151:         my $homeserver=&domain($udom,'primary');
                   2152:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2153:             my $response;
                   2154:             if ($check eq 'id') {
                   2155:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2156:                                  $homeserver);
1.943     raeburn  2157:             } elsif ($check eq 'email') {
                   2158:                 $response=&reply('instemailrules:'.&escape($udom),
                   2159:                                  $homeserver);
1.923     raeburn  2160:             } else {
                   2161:                 $response=&reply('instuserrules:'.&escape($udom),
                   2162:                                  $homeserver);
                   2163:             }
1.912     raeburn  2164:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2165:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2166:                 ($response ne 'no_such_host')) {
                   2167:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2168:                 my @pairs=split(/\&/,$hashitems);
                   2169:                 foreach my $item (@pairs) {
                   2170:                     my ($key,$value)=split(/=/,$item,2);
                   2171:                     $key = &unescape($key);
                   2172:                     next if ($key =~ /^error: 2 /);
                   2173:                     $ruleshash{$key}=&thaw_unescape($value);
                   2174:                 }
                   2175:                 my @esc_order = split(/\&/,$orderitems);
                   2176:                 foreach my $item (@esc_order) {
                   2177:                     push(@ruleorder,&unescape($item));
                   2178:                 }
                   2179:             }
                   2180:         }
                   2181:     }
                   2182:     return (\%ruleshash,\@ruleorder);
                   2183: }
                   2184: 
1.976     raeburn  2185: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2186: 
                   2187: sub get_domain_defaults {
1.1240    raeburn  2188:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2189:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2190:     my $cachetime = 60*60*24;
1.1240    raeburn  2191:     unless ($ignore_cache) {
                   2192:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2193:         if (defined($cached)) {
                   2194:             if (ref($result) eq 'HASH') {
                   2195:                 return %{$result};
                   2196:             }
1.943     raeburn  2197:         }
                   2198:     }
                   2199:     my %domdefaults;
                   2200:     my %domconfig =
1.989     raeburn  2201:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2202:                                   'requestcourses','inststatus',
1.1183    raeburn  2203:                                   'coursedefaults','usersessions',
1.1258    raeburn  2204:                                   'requestauthor','selfenrollment',
                   2205:                                   'coursecategories'],$domain);
1.1305    raeburn  2206:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2207:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2208:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2209:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2210:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2211:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2212:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2213:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2214:     } else {
                   2215:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2216:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2217:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2218:     }
1.976     raeburn  2219:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2220:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2221:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2222:         } else {
                   2223:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2224:         }
1.1177    raeburn  2225:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2226:         foreach my $item (@usertools) {
                   2227:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2228:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2229:             }
                   2230:         }
1.1229    raeburn  2231:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2232:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2233:         }
1.976     raeburn  2234:     }
1.985     raeburn  2235:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2236:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2237:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2238:         }
                   2239:     }
1.1183    raeburn  2240:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2241:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2242:     }
1.989     raeburn  2243:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2244:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2245:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2246:         }
                   2247:     }
1.1047    raeburn  2248:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2249:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2250:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2251:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2252:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2253:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2254:         }
1.1254    raeburn  2255:         foreach my $type (@coursetypes) {
                   2256:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2257:                 unless ($type eq 'community') {
                   2258:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2259:                 }
                   2260:             }
                   2261:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2262:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2263:             }
1.1277    raeburn  2264:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2265:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2266:                     $domdefaults{$type.'postsubtimeout'} = 
                   2267:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2268:                 }
                   2269:             }
1.1230    raeburn  2270:         }
1.1286    raeburn  2271:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2272:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2273:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2274:                 if (@clonecodes) {
                   2275:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2276:                 }
                   2277:             }
                   2278:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2279:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2280:         }
1.1047    raeburn  2281:     }
1.1073    raeburn  2282:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2283:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2284:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2285:         }
                   2286:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2287:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2288:         }
1.1279    raeburn  2289:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2290:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2291:         }
1.1073    raeburn  2292:     }
1.1254    raeburn  2293:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2294:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2295:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2296:                             'approval','limit');
                   2297:             foreach my $type (@coursetypes) {
                   2298:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2299:                     my @mgrdc = ();
                   2300:                     foreach my $item (@settings) {
                   2301:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2302:                             push(@mgrdc,$item);
                   2303:                         }
                   2304:                     }
                   2305:                     if (@mgrdc) {
                   2306:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2307:                     }
                   2308:                 }
                   2309:             }
                   2310:         }
                   2311:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2312:             foreach my $type (@coursetypes) {
                   2313:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2314:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2315:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2316:                     }
                   2317:                 }
                   2318:             }
                   2319:         }
                   2320:     }
1.1258    raeburn  2321:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2322:         $domdefaults{'catauth'} = 'std';
                   2323:         $domdefaults{'catunauth'} = 'std';
                   2324:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2325:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2326:         }
                   2327:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2328:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2329:         }
                   2330:     }
1.1219    raeburn  2331:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2332:     return %domdefaults;
                   2333: }
                   2334: 
1.344     www      2335: # --------------------------------------------------- Assign a key to a student
                   2336: 
                   2337: sub assign_access_key {
1.364     www      2338: #
                   2339: # a valid key looks like uname:udom#comments
                   2340: # comments are being appended
                   2341: #
1.498     www      2342:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2343:     $kdom=
1.620     albertel 2344:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2345:     $knum=
1.620     albertel 2346:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2347:     $cdom=
1.620     albertel 2348:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2349:     $cnum=
1.620     albertel 2350:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2351:     $udom=$env{'user.name'} unless (defined($udom));
                   2352:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2353:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2354:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2355:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2356:                                                   # assigned to this person
                   2357:                                                   # - this should not happen,
1.345     www      2358:                                                   # unless something went wrong
                   2359:                                                   # the first time around
                   2360: # ready to assign
1.364     www      2361:         $logentry=$1.'; '.$logentry;
1.496     www      2362:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2363:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2364: # key now belongs to user
1.346     www      2365: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2366:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2367:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2368:                 return 'ok';
                   2369:             } else {
                   2370:                 return 
                   2371:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2372: 	    }
                   2373:         } else {
                   2374:             return 'error: Could not assign key, try again later.';
                   2375:         }
1.364     www      2376:     } elsif (!$existing{$ckey}) {
1.345     www      2377: # the key does not exist
                   2378: 	return 'error: The key does not exist';
                   2379:     } else {
                   2380: # the key is somebody else's
                   2381: 	return 'error: The key is already in use';
                   2382:     }
1.344     www      2383: }
                   2384: 
1.364     www      2385: # ------------------------------------------ put an additional comment on a key
                   2386: 
                   2387: sub comment_access_key {
                   2388: #
                   2389: # a valid key looks like uname:udom#comments
                   2390: # comments are being appended
                   2391: #
                   2392:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2393:     $cdom=
1.620     albertel 2394:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2395:     $cnum=
1.620     albertel 2396:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2397:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2398:     if ($existing{$ckey}) {
                   2399:         $existing{$ckey}.='; '.$logentry;
                   2400: # ready to assign
1.367     www      2401:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2402:                                                  $cdom,$cnum) eq 'ok') {
                   2403: 	    return 'ok';
                   2404:         } else {
                   2405: 	    return 'error: Count not store comment.';
                   2406:         }
                   2407:     } else {
                   2408: # the key does not exist
                   2409: 	return 'error: The key does not exist';
                   2410:     }
                   2411: }
                   2412: 
1.344     www      2413: # ------------------------------------------------------ Generate a set of keys
                   2414: 
                   2415: sub generate_access_keys {
1.364     www      2416:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2417:     $cdom=
1.620     albertel 2418:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2419:     $cnum=
1.620     albertel 2420:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2421:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2422:     unless (($cdom) && ($cnum)) { return 0; }
                   2423:     if ($number>10000) { return 0; }
                   2424:     sleep(2); # make sure don't get same seed twice
                   2425:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2426:     my $total=0;
                   2427:     for (my $i=1;$i<=$number;$i++) {
                   2428:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2429:                   sprintf("%lx",int(100000*rand)).'-'.
                   2430:                   sprintf("%lx",int(100000*rand));
                   2431:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2432:        $newkey=~s/0/h/g; # and also 0 and O
                   2433:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2434:        if ($existing{$newkey}) {
                   2435:            $i--;
                   2436:        } else {
1.364     www      2437: 	  if (&put('accesskeys',
                   2438:               { $newkey => '# generated '.localtime().
1.620     albertel 2439:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2440:                            '; '.$logentry },
                   2441: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2442:               $total++;
                   2443: 	  }
                   2444:        }
                   2445:     }
1.620     albertel 2446:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2447:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2448:     return $total;
                   2449: }
                   2450: 
                   2451: # ------------------------------------------------------- Validate an accesskey
                   2452: 
                   2453: sub validate_access_key {
                   2454:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2455:     $cdom=
1.620     albertel 2456:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2457:     $cnum=
1.620     albertel 2458:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2459:     $udom=$env{'user.domain'} unless (defined($udom));
                   2460:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2461:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2462:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2463: }
                   2464: 
                   2465: # ------------------------------------- Find the section of student in a course
1.652     albertel 2466: sub devalidate_getsection_cache {
                   2467:     my ($udom,$unam,$courseid)=@_;
                   2468:     my $hashid="$udom:$unam:$courseid";
                   2469:     &devalidate_cache_new('getsection',$hashid);
                   2470: }
1.298     matthew  2471: 
1.815     albertel 2472: sub courseid_to_courseurl {
                   2473:     my ($courseid) = @_;
                   2474:     #already url style courseid
                   2475:     return $courseid if ($courseid =~ m{^/});
                   2476: 
                   2477:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2478: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2479: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2480: 	return "/$cdom/$cnum";
                   2481:     }
                   2482: 
                   2483:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2484:     if (exists($courseinfo{'num'})) {
                   2485: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2486:     }
                   2487: 
                   2488:     return undef;
                   2489: }
                   2490: 
1.298     matthew  2491: sub getsection {
                   2492:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2493:     my $cachetime=1800;
1.551     albertel 2494: 
                   2495:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2496:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2497:     if (defined($cached)) { return $result; }
                   2498: 
1.298     matthew  2499:     my %Pending; 
                   2500:     my %Expired;
                   2501:     #
                   2502:     # Each role can either have not started yet (pending), be active, 
                   2503:     #    or have expired.
                   2504:     #
                   2505:     # If there is an active role, we are done.
                   2506:     #
                   2507:     # If there is more than one role which has not started yet, 
                   2508:     #     choose the one which will start sooner
                   2509:     # If there is one role which has not started yet, return it.
                   2510:     #
                   2511:     # If there is more than one expired role, choose the one which ended last.
                   2512:     # If there is a role which has expired, return it.
                   2513:     #
1.815     albertel 2514:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2515:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2516:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2517:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2518:         my $section=$1;
                   2519:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2520:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2521:         my $now=time;
1.548     albertel 2522:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2523:             $Expired{$end}=$section;
                   2524:             next;
                   2525:         }
1.548     albertel 2526:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2527:             $Pending{$start}=$section;
                   2528:             next;
                   2529:         }
1.599     albertel 2530:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2531:     }
                   2532:     #
                   2533:     # Presumedly there will be few matching roles from the above
                   2534:     # loop and the sorting time will be negligible.
                   2535:     if (scalar(keys(%Pending))) {
                   2536:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2537:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2538:     } 
                   2539:     if (scalar(keys(%Expired))) {
                   2540:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2541:         my $time = pop(@sorted);
1.599     albertel 2542:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2543:     }
1.599     albertel 2544:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2545: }
1.70      www      2546: 
1.599     albertel 2547: sub save_cache {
                   2548:     &purge_remembered();
1.722     albertel 2549:     #&Apache::loncommon::validate_page();
1.620     albertel 2550:     undef(%env);
1.780     albertel 2551:     undef($env_loaded);
1.599     albertel 2552: }
1.452     albertel 2553: 
1.599     albertel 2554: my $to_remember=-1;
                   2555: my %remembered;
                   2556: my %accessed;
                   2557: my $kicks=0;
                   2558: my $hits=0;
1.849     albertel 2559: sub make_key {
                   2560:     my ($name,$id) = @_;
1.872     albertel 2561:     if (length($id) > 65 
                   2562: 	&& length(&escape($id)) > 200) {
                   2563: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2564:     }
1.849     albertel 2565:     return &escape($name.':'.$id);
                   2566: }
                   2567: 
1.599     albertel 2568: sub devalidate_cache_new {
                   2569:     my ($name,$id,$debug) = @_;
                   2570:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2571:     $id=&make_key($name,$id);
1.599     albertel 2572:     $memcache->delete($id);
                   2573:     delete($remembered{$id});
                   2574:     delete($accessed{$id});
                   2575: }
                   2576: 
                   2577: sub is_cached_new {
                   2578:     my ($name,$id,$debug) = @_;
1.849     albertel 2579:     $id=&make_key($name,$id);
1.599     albertel 2580:     if (exists($remembered{$id})) {
1.1133    foxr     2581: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2582: 	$accessed{$id}=[&gettimeofday()];
                   2583: 	$hits++;
                   2584: 	return ($remembered{$id},1);
                   2585:     }
                   2586:     my $value = $memcache->get($id);
                   2587:     if (!(defined($value))) {
                   2588: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2589: 	return (undef,undef);
1.416     albertel 2590:     }
1.599     albertel 2591:     if ($value eq '__undef__') {
                   2592: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2593: 	$value=undef;
                   2594:     }
                   2595:     &make_room($id,$value,$debug);
                   2596:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2597:     return ($value,1);
                   2598: }
                   2599: 
                   2600: sub do_cache_new {
                   2601:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2602:     $id=&make_key($name,$id);
1.599     albertel 2603:     my $setvalue=$value;
                   2604:     if (!defined($setvalue)) {
                   2605: 	$setvalue='__undef__';
                   2606:     }
1.623     albertel 2607:     if (!defined($time) ) {
                   2608: 	$time=600;
                   2609:     }
1.599     albertel 2610:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2611:     my $result = $memcache->set($id,$setvalue,$time);
                   2612:     if (! $result) {
1.872     albertel 2613: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2614: 	$memcache->disconnect_all();
1.872     albertel 2615:     }
1.600     albertel 2616:     # need to make a copy of $value
1.919     albertel 2617:     &make_room($id,$value,$debug);
1.599     albertel 2618:     return $value;
                   2619: }
                   2620: 
                   2621: sub make_room {
                   2622:     my ($id,$value,$debug)=@_;
1.919     albertel 2623: 
                   2624:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2625:                                     : $value;
1.599     albertel 2626:     if ($to_remember<0) { return; }
                   2627:     $accessed{$id}=[&gettimeofday()];
                   2628:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2629:     my $to_kick;
                   2630:     my $max_time=0;
                   2631:     foreach my $other (keys(%accessed)) {
                   2632: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2633: 	    $to_kick=$other;
                   2634: 	    $max_time=&tv_interval($accessed{$other});
                   2635: 	}
                   2636:     }
                   2637:     delete($remembered{$to_kick});
                   2638:     delete($accessed{$to_kick});
                   2639:     $kicks++;
                   2640:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2641:     return;
                   2642: }
                   2643: 
1.599     albertel 2644: sub purge_remembered {
1.604     albertel 2645:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2646:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2647:     undef(%remembered);
                   2648:     undef(%accessed);
1.428     albertel 2649: }
1.70      www      2650: # ------------------------------------- Read an entry from a user's environment
                   2651: 
                   2652: sub userenvironment {
                   2653:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2654:     my $items;
                   2655:     foreach my $item (@what) {
                   2656:         $items.=&escape($item).'&';
                   2657:     }
                   2658:     $items=~s/\&$//;
1.70      www      2659:     my %returnhash=();
1.1009    raeburn  2660:     my $uhome = &homeserver($unam,$udom);
                   2661:     unless ($uhome eq 'no_host') {
                   2662:         my @answer=split(/\&/, 
                   2663:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2664:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2665:             return %returnhash;
                   2666:         }
1.1009    raeburn  2667:         my $i;
                   2668:         for ($i=0;$i<=$#what;$i++) {
                   2669: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2670:         }
1.70      www      2671:     }
                   2672:     return %returnhash;
1.1       albertel 2673: }
                   2674: 
1.617     albertel 2675: # ---------------------------------------------------------- Get a studentphoto
                   2676: sub studentphoto {
                   2677:     my ($udom,$unam,$ext) = @_;
                   2678:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2679:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2680:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2681:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2682:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2683:             } else {
                   2684:                 my ($result,$perm_reqd)=
1.707     albertel 2685: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2686:                 if ($result eq 'ok') {
                   2687:                     if (!($perm_reqd eq 'yes')) {
                   2688:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2689:                     }
                   2690:                 }
                   2691:             }
                   2692:         }
                   2693:     } else {
                   2694:         my ($result,$perm_reqd) = 
1.707     albertel 2695: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2696:         if ($result eq 'ok') {
                   2697:             if (!($perm_reqd eq 'yes')) {
                   2698:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2699:             }
                   2700:         }
                   2701:     }
                   2702:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2703: }
                   2704: 
                   2705: sub retrievestudentphoto {
                   2706:     my ($udom,$unam,$ext,$type) = @_;
                   2707:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2708:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2709:     if ($ret eq 'ok') {
                   2710:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2711:         if ($type eq 'thumbnail') {
                   2712:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2713:         }
                   2714:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2715:         return $tokenurl;
                   2716:     } else {
                   2717:         if ($type eq 'thumbnail') {
                   2718:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2719:         } else { 
                   2720:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2721:         }
1.617     albertel 2722:     }
                   2723: }
                   2724: 
1.263     www      2725: # -------------------------------------------------------------------- New chat
                   2726: 
                   2727: sub chatsend {
1.724     raeburn  2728:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2729:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2730:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2731:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2732:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2733: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2734: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2735: }
                   2736: 
                   2737: # ------------------------------------------ Find current version of a resource
                   2738: 
                   2739: sub getversion {
                   2740:     my $fname=&clutter(shift);
1.1189    raeburn  2741:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2742:     return &currentversion(&filelocation('',$fname));
                   2743: }
                   2744: 
                   2745: sub currentversion {
                   2746:     my $fname=shift;
                   2747:     my $author=$fname;
                   2748:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2749:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2750:     my $home=&homeserver($uname,$udom);
1.292     www      2751:     if ($home eq 'no_host') { 
                   2752:         return -1; 
                   2753:     }
1.1112    www      2754:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2755:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2756: 	return -1;
                   2757:     }
1.1112    www      2758:     return $answer;
1.263     www      2759: }
                   2760: 
1.1111    www      2761: #
                   2762: # Return special version number of resource if set by override, empty otherwise
                   2763: #
                   2764: sub usedversion {
                   2765:     my $fname=shift;
                   2766:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2767:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2768:     if ($urlversion) { return $urlversion; }
                   2769:     return '';
                   2770: }
                   2771: 
1.1       albertel 2772: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2773: 
1.1       albertel 2774: sub subscribe {
                   2775:     my $fname=shift;
1.761     raeburn  2776:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2777:     $fname=~s/[\n\r]//g;
1.1       albertel 2778:     my $author=$fname;
                   2779:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2780:     my ($udom,$uname)=split(/\//,$author);
                   2781:     my $home=homeserver($uname,$udom);
1.335     albertel 2782:     if ($home eq 'no_host') {
                   2783:         return 'not_found';
1.1       albertel 2784:     }
                   2785:     my $answer=reply("sub:$fname",$home);
1.64      www      2786:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2787: 	$answer.=' by '.$home;
                   2788:     }
1.1       albertel 2789:     return $answer;
                   2790: }
                   2791:     
1.8       www      2792: # -------------------------------------------------------------- Replicate file
                   2793: 
                   2794: sub repcopy {
                   2795:     my $filename=shift;
1.23      www      2796:     $filename=~s/\/+/\//g;
1.1142    raeburn  2797:     my $londocroot = $perlvar{'lonDocRoot'};
                   2798:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2799:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2800:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2801: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2802: 	return &repcopy_userfile($filename);
                   2803:     }
1.532     albertel 2804:     $filename=~s/[\n\r]//g;
1.8       www      2805:     my $transname="$filename.in.transfer";
1.828     www      2806: # FIXME: this should flock
1.607     raeburn  2807:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2808:     my $remoteurl=subscribe($filename);
1.64      www      2809:     if ($remoteurl =~ /^con_lost by/) {
                   2810: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2811:            return 'unavailable';
1.8       www      2812:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2813: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2814: 	   return 'not_found';
1.64      www      2815:     } elsif ($remoteurl =~ /^rejected by/) {
                   2816: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2817:            return 'forbidden';
1.20      www      2818:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2819:            return 'ok';
1.8       www      2820:     } else {
1.290     www      2821:         my $author=$filename;
                   2822:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2823:         my ($udom,$uname)=split(/\//,$author);
                   2824:         my $home=homeserver($uname,$udom);
                   2825:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2826:            my @parts=split(/\//,$filename);
                   2827:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2828:            if ($path ne "$londocroot/res") {
1.8       www      2829:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2830: 	       return 'bad_request';
1.8       www      2831:            }
                   2832:            my $count;
                   2833:            for ($count=5;$count<$#parts;$count++) {
                   2834:                $path.="/$parts[$count]";
                   2835:                if ((-e $path)!=1) {
                   2836: 		   mkdir($path,0777);
                   2837:                }
                   2838:            }
                   2839:            my $ua=new LWP::UserAgent;
                   2840:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2841:            my $response=$ua->request($request,$transname);
                   2842:            if ($response->is_error()) {
                   2843: 	       unlink($transname);
                   2844:                my $message=$response->status_line;
1.672     albertel 2845:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2846:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2847:                return 'unavailable';
1.8       www      2848:            } else {
1.16      www      2849: 	       if ($remoteurl!~/\.meta$/) {
                   2850:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2851:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2852:                   if ($mresponse->is_error()) {
                   2853: 		      unlink($filename.'.meta');
                   2854:                       &logthis(
1.672     albertel 2855:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2856:                   }
                   2857: 	       }
1.8       www      2858:                rename($transname,$filename);
1.607     raeburn  2859:                return 'ok';
1.8       www      2860:            }
1.290     www      2861:        }
1.8       www      2862:     }
1.330     www      2863: }
                   2864: 
                   2865: # ------------------------------------------------ Get server side include body
                   2866: sub ssi_body {
1.381     albertel 2867:     my ($filelink,%form)=@_;
1.606     matthew  2868:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2869:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2870:     }
1.953     www      2871:     my $output='';
                   2872:     my $response;
1.980     raeburn  2873:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2874:        ($output,$response)=&externalssi($filelink);
1.953     www      2875:     } else {
1.1004    droeschl 2876:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2877:        $filelink .= 'inhibitmenu=yes';
1.953     www      2878:        ($output,$response)=&ssi($filelink,%form);
                   2879:     }
1.778     albertel 2880:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2881:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2882:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2883:     if (wantarray) {
                   2884:         return ($output, $response);
                   2885:     } else {
                   2886:         return $output;
                   2887:     }
1.8       www      2888: }
                   2889: 
1.15      www      2890: # --------------------------------------------------------- Server Side Include
                   2891: 
1.782     albertel 2892: sub absolute_url {
                   2893:     my ($host_name) = @_;
                   2894:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2895:     if ($host_name eq '') {
                   2896: 	$host_name = $ENV{'SERVER_NAME'};
                   2897:     }
                   2898:     return $protocol.$host_name;
                   2899: }
                   2900: 
1.942     foxr     2901: #
                   2902: #   Server side include.
                   2903: # Parameters:
                   2904: #  fn     Possibly encrypted resource name/id.
                   2905: #  form   Hash that describes how the rendering should be done
                   2906: #         and other things.
1.944     foxr     2907: # Returns:
1.950     raeburn  2908: #   Scalar context: The content of the response.
                   2909: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2910: #     
1.15      www      2911: sub ssi {
                   2912: 
1.944     foxr     2913:     my ($fn,%form)=@_;
1.15      www      2914:     my $ua=new LWP::UserAgent;
1.23      www      2915:     my $request;
1.711     albertel 2916: 
                   2917:     $form{'no_update_last_known'}=1;
1.895     albertel 2918:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2919:     if (%form) {
1.782     albertel 2920:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2921:       $request->content(join('&',map { 
                   2922:             my $name = escape($_);
                   2923:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2924:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2925:             : &escape($form{$_}) );    
                   2926:         } keys(%form)));
1.23      www      2927:     } else {
1.782     albertel 2928:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2929:     }
                   2930: 
1.15      www      2931:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2932:     my $response= $ua->request($request);
1.1182    foxr     2933:     my $content = $response->content;
                   2934: 
                   2935: 
1.944     foxr     2936:     if (wantarray) {
1.1173    foxr     2937: 	return ($content, $response);
1.944     foxr     2938:     } else {
1.1173    foxr     2939: 	return $content;
1.942     foxr     2940:     }
1.324     www      2941: }
                   2942: 
                   2943: sub externalssi {
                   2944:     my ($url)=@_;
                   2945:     my $ua=new LWP::UserAgent;
                   2946:     my $request=new HTTP::Request('GET',$url);
                   2947:     my $response=$ua->request($request);
1.954     raeburn  2948:     if (wantarray) {
                   2949:         return ($response->content, $response);
                   2950:     } else {
                   2951:         return $response->content;
                   2952:     }
1.15      www      2953: }
1.254     www      2954: 
1.492     albertel 2955: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2956: 
                   2957: sub allowuploaded {
                   2958:     my ($srcurl,$url)=@_;
                   2959:     $url=&clutter(&declutter($url));
                   2960:     my $dir=$url;
                   2961:     $dir=~s/\/[^\/]+$//;
                   2962:     my %httpref=();
                   2963:     my $httpurl=&hreflocation('',$url);
                   2964:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2965:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2966: }
1.477     raeburn  2967: 
1.1193    raeburn  2968: #
                   2969: # Determine if the current user should be able to edit a particular resource,
                   2970: # when viewing in course context.
                   2971: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2972: #     Functions.
                   2973: # (b) When displaying folder contents in course editor, used to determine if
                   2974: #     "Edit" link will be displayed alongside resource.
                   2975: #
1.1196    raeburn  2976: #  input: six args -- filename (decluttered), course number, course domain,
                   2977: #                   url, symb (if registered) and group (if this is a group
                   2978: #                   item -- e.g., bulletin board, group page etc.).
                   2979: #  output: array of five scalars -- 
1.1193    raeburn  2980: #          $cfile -- url for file editing if editable on current server
                   2981: #          $home -- homeserver of resource (i.e., for author if published,
                   2982: #                                           or course if uploaded.).
                   2983: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2984: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2985: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2986: #
                   2987: 
                   2988: sub can_edit_resource {
1.1194    raeburn  2989:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2990:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2991: #
                   2992: # For aboutme pages user can only edit his/her own.
                   2993: #
1.1199    raeburn  2994:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2995:         my ($sdom,$sname) = ($1,$2);
                   2996:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2997:             $home = $env{'user.home'};
                   2998:             $cfile = $resurl;
                   2999:             if ($env{'form.forceedit'}) {
                   3000:                 $forceview = 1;
                   3001:             } else {
                   3002:                 $forceedit = 1;
                   3003:             }
                   3004:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3005:         } else {
                   3006:             return;
                   3007:         }
                   3008:     }
                   3009: 
                   3010:     if ($env{'request.course.id'}) {
                   3011:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3012:         if ($group ne '') {
                   3013: # if this is a group homepage or group bulletin board, check group privs
                   3014:             my $allowed = 0;
1.1197    raeburn  3015:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3016:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3017:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3018:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3019:                     $allowed = 1;
                   3020:                 }
1.1197    raeburn  3021:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3022:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3023:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3024:                     $allowed = 1;
                   3025:                 }
                   3026:             }
                   3027:             if ($allowed) {
                   3028:                 $home=&homeserver($cnum,$cdom);
                   3029:                 if ($env{'form.forceedit'}) {
                   3030:                     $forceview = 1;
                   3031:                 } else {
                   3032:                     $forceedit = 1;
                   3033:                 }
                   3034:                 $cfile = $resurl;
                   3035:             } else {
                   3036:                 return;
                   3037:             }
                   3038:         } else {
1.1208    raeburn  3039:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3040:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3041:                     return;
                   3042:                 }
                   3043:             } elsif (!$crsedit) {
1.1194    raeburn  3044: #
                   3045: # No edit allowed where CC has switched to student role.
                   3046: #
                   3047:                 return;
                   3048:             }
                   3049:         }
                   3050:     }
                   3051: 
1.1193    raeburn  3052:     if ($file ne '') {
                   3053:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3054:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3055:                 $uploaded = 1;
                   3056:                 $incourse = 1;
1.1193    raeburn  3057:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3058:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3059:                     if ($env{'form.forceedit'}) {
                   3060:                         $forceview = 1;
                   3061:                     } else {
                   3062:                         $forceedit = 1;
                   3063:                     }
1.1194    raeburn  3064:                 }
                   3065:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3066:                 $incourse = 1;
                   3067:                 if ($env{'form.forceedit'}) {
                   3068:                     $forceview = 1;
                   3069:                 } else {
                   3070:                     $forceedit = 1;
                   3071:                 }
                   3072:                 $cfile = $resurl;
                   3073:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3074:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3075:                     $incourse = 1;
                   3076:                     if ($env{'form.forceedit'}) {
                   3077:                         $forceview = 1;
                   3078:                     } else {
                   3079:                         $forceedit = 1;
                   3080:                     }
                   3081:                     $cfile = $resurl;
1.1199    raeburn  3082:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3083:                     $incourse = 1;
                   3084:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3085:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3086:                     $incourse = 1;
1.1199    raeburn  3087:                     if ($env{'form.forceedit'}) {
                   3088:                         $forceview = 1;
                   3089:                     } else {
                   3090:                         $forceedit = 1;
                   3091:                     }
                   3092:                     $cfile = $resurl;
1.1298    raeburn  3093:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3094:                     $incourse = 1;
                   3095:                     if ($env{'form.forceedit'}) {
                   3096:                         $forceview = 1;
                   3097:                     } else {
                   3098:                         $forceedit = 1;
                   3099:                     }
                   3100:                     $cfile = $resurl;
1.1208    raeburn  3101:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3102:                     $incourse = 1;
                   3103:                     if ($env{'form.forceedit'}) {
                   3104:                         $forceview = 1;
                   3105:                     } else {
                   3106:                         $forceedit = 1;
                   3107:                     }
                   3108:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3109:                 }
                   3110:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3111:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3112:                 if (&is_on_map($template)) { 
                   3113:                     $incourse = 1;
                   3114:                     $forceview = 1;
                   3115:                     $cfile = $template;
1.1193    raeburn  3116:                 }
1.1199    raeburn  3117:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3118:                     $incourse = 1;
                   3119:                     if ($env{'form.forceedit'}) {
                   3120:                         $forceview = 1;
                   3121:                     } else {
                   3122:                         $forceedit = 1;
                   3123:                     }
                   3124:                     $cfile = $resurl;
1.1298    raeburn  3125:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3126:                 $incourse = 1;
                   3127:                 if ($env{'form.forceedit'}) {
                   3128:                     $forceview = 1;
                   3129:                 } else {
                   3130:                     $forceedit = 1;
                   3131:                 }
                   3132:                 $cfile = $resurl;
1.1199    raeburn  3133:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3134:                 $incourse = 1;
                   3135:                 $forceview = 1;
                   3136:                 if ($symb) {
                   3137:                     my ($map,$id,$res)=&decode_symb($symb);
                   3138:                     $env{'request.symb'} = $symb;
                   3139:                     $cfile = &clutter($res);
                   3140:                 } else {
                   3141:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3142:                     my $escfile = &unescape($cfile);
                   3143:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3144:                         $cfile = '/adm/wrapper'.$escfile;
                   3145:                     } else {
                   3146:                         $escfile =~ s{^http://}{};
                   3147:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3148:                     }
1.1199    raeburn  3149:                 }
1.1234    raeburn  3150:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3151:                 if ($env{'form.forceedit'}) {
                   3152:                     $forceview = 1;
                   3153:                 } else {
                   3154:                     $forceedit = 1;
                   3155:                 }
                   3156:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3157:             }
                   3158:         }
1.1194    raeburn  3159:         if ($uploaded || $incourse) {
                   3160:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3161:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3162:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3163:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3164:             # Check that the user has permission to edit this resource
                   3165:             my $setpriv = 1;
                   3166:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3167:             if (defined($cfudom)) {
                   3168:                 $home=&homeserver($cfuname,$cfudom);
                   3169:                 $cfile=$file;
                   3170:             }
                   3171:         }
1.1194    raeburn  3172:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3173:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3174:             my @ids=&current_machine_ids();
                   3175:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3176:                 $switchserver=1;
                   3177:             }
                   3178:         }
                   3179:     }
1.1194    raeburn  3180:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3181: }
                   3182: 
                   3183: sub is_course_upload {
                   3184:     my ($file,$cnum,$cdom) = @_;
                   3185:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3186:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3187:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3188:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3189:         return 1;
                   3190:     }
                   3191:     return;
                   3192: }
                   3193: 
1.1194    raeburn  3194: sub in_course {
1.1195    raeburn  3195:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3196:     if ($hideprivileged) {
                   3197:         my $skipuser;
1.1219    raeburn  3198:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3199:         my @possdoms = ($cdom);  
                   3200:         if ($coursehash{'checkforpriv'}) { 
                   3201:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3202:         }
                   3203:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3204:             $skipuser = 1;
                   3205:             if ($coursehash{'nothideprivileged'}) {
                   3206:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3207:                     my $user;
                   3208:                     if ($item =~ /:/) {
                   3209:                         $user = $item;
                   3210:                     } else {
                   3211:                         $user = join(':',split(/[\@]/,$item));
                   3212:                     }
                   3213:                     if ($user eq $uname.':'.$udom) {
                   3214:                         undef($skipuser);
                   3215:                         last;
                   3216:                     }
                   3217:                 }
                   3218:             }
                   3219:             if ($skipuser) {
                   3220:                 return 0;
                   3221:             }
                   3222:         }
                   3223:     }
1.1194    raeburn  3224:     $type ||= 'any';
                   3225:     if (!defined($cdom) || !defined($cnum)) {
                   3226:         my $cid  = $env{'request.course.id'};
                   3227:         $cdom = $env{'course.'.$cid.'.domain'};
                   3228:         $cnum = $env{'course.'.$cid.'.num'};
                   3229:     }
                   3230:     my $typesref;
1.1195    raeburn  3231:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3232:         $typesref = ['active','previous','future'];
                   3233:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3234:         $typesref = [$type];
                   3235:     }
                   3236:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3237:                               $typesref,undef,[$cdom]);
                   3238:     my ($tmp) = keys(%roles);
                   3239:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3240:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3241:     if (@course_roles > 0) {
                   3242:         return 1;
                   3243:     }
                   3244:     return 0;
                   3245: }
                   3246: 
1.478     albertel 3247: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3248: # input: action, courseID, current domain, intended
1.637     raeburn  3249: #        path to file, source of file, instruction to parse file for objects,
                   3250: #        ref to hash for embedded objects,
                   3251: #        ref to hash for codebase of java objects.
1.1095    raeburn  3252: #        reference to scalar to accommodate mime type determined
                   3253: #          from File::MMagic if $parser = parse.
1.637     raeburn  3254: #
1.485     raeburn  3255: # output: url to file (if action was uploaddoc), 
                   3256: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3257: #
1.478     albertel 3258: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3259: # course.
1.477     raeburn  3260: #
1.478     albertel 3261: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3262: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3263: #          course's home server.
1.477     raeburn  3264: #
1.478     albertel 3265: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3266: #          be copied from $source (current location) to 
                   3267: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3268: #         and will then be copied to
                   3269: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3270: #         course's home server.
1.485     raeburn  3271: #
1.481     raeburn  3272: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3273: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3274: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3275: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3276: #         in course's home server.
1.637     raeburn  3277: #
1.477     raeburn  3278: 
                   3279: sub process_coursefile {
1.1095    raeburn  3280:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3281:         $mimetype)=@_;
1.477     raeburn  3282:     my $fetchresult;
1.638     albertel 3283:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3284:     if ($action eq 'propagate') {
1.638     albertel 3285:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3286: 			     $home);
1.481     raeburn  3287:     } else {
1.477     raeburn  3288:         my $fpath = '';
                   3289:         my $fname = $file;
1.478     albertel 3290:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3291:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3292:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3293:         if ($action eq 'copy') {
                   3294:             if ($source eq '') {
                   3295:                 $fetchresult = 'no source file';
                   3296:                 return $fetchresult;
                   3297:             } else {
                   3298:                 my $destination = $filepath.'/'.$fname;
                   3299:                 rename($source,$destination);
                   3300:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3301:                                  $home);
1.481     raeburn  3302:             }
                   3303:         } elsif ($action eq 'uploaddoc') {
                   3304:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3305:             print $fh $env{'form.'.$source};
1.481     raeburn  3306:             close($fh);
1.637     raeburn  3307:             if ($parser eq 'parse') {
1.1024    raeburn  3308:                 my $mm = new File::MMagic;
1.1095    raeburn  3309:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3310:                 if ($type eq 'text/html') {
1.1024    raeburn  3311:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3312:                     unless ($parse_result eq 'ok') {
                   3313:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3314:                     }
1.637     raeburn  3315:                 }
1.1095    raeburn  3316:                 if (ref($mimetype)) {
                   3317:                     $$mimetype = $type;
                   3318:                 } 
1.637     raeburn  3319:             }
1.477     raeburn  3320:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3321:                                  $home);
1.481     raeburn  3322:             if ($fetchresult eq 'ok') {
                   3323:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3324:             } else {
                   3325:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3326:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3327:                 return '/adm/notfound.html';
                   3328:             }
1.477     raeburn  3329:         }
                   3330:     }
1.485     raeburn  3331:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3332:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3333:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3334:     }
                   3335:     return $fetchresult;
                   3336: }
                   3337: 
1.637     raeburn  3338: sub build_filepath {
                   3339:     my ($fpath) = @_;
                   3340:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3341:     unless ($fpath eq '') {
                   3342:         my @parts=split('/',$fpath);
                   3343:         foreach my $part (@parts) {
                   3344:             $filepath.= '/'.$part;
                   3345:             if ((-e $filepath)!=1) {
                   3346:                 mkdir($filepath,0777);
                   3347:             }
                   3348:         }
                   3349:     }
                   3350:     return $filepath;
                   3351: }
                   3352: 
                   3353: sub store_edited_file {
1.638     albertel 3354:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3355:     my $file = $primary_url;
                   3356:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3357:     my $fpath = '';
                   3358:     my $fname = $file;
                   3359:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3360:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3361:     my $filepath = &build_filepath($fpath);
                   3362:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3363:     print $fh $content;
                   3364:     close($fh);
1.638     albertel 3365:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3366:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3367: 			  $home);
1.637     raeburn  3368:     if ($$fetchresult eq 'ok') {
                   3369:         return '/uploaded/'.$fpath.'/'.$fname;
                   3370:     } else {
1.638     albertel 3371:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3372: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3373:         return '/adm/notfound.html';
                   3374:     }
                   3375: }
                   3376: 
1.531     albertel 3377: sub clean_filename {
1.831     albertel 3378:     my ($fname,$args)=@_;
1.315     www      3379: # Replace Windows backslashes by forward slashes
1.257     www      3380:     $fname=~s/\\/\//g;
1.831     albertel 3381:     if (!$args->{'keep_path'}) {
                   3382:         # Get rid of everything but the actual filename
                   3383: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3384:     }
1.315     www      3385: # Replace spaces by underscores
                   3386:     $fname=~s/\s+/\_/g;
                   3387: # Replace all other weird characters by nothing
1.831     albertel 3388:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3389: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3390: # numbers
                   3391:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3392:     return $fname;
                   3393: }
1.1051    raeburn  3394: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3395: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3396: # image with the same aspect ratio as the original, but with dimensions which do 
                   3397: # not exceed $resizewidth and $resizeheight.
                   3398:  
1.984     neumanie 3399: sub resizeImage {
1.1051    raeburn  3400:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3401:     my $ima = Image::Magick->new;
                   3402:     my $resized;
                   3403:     if (-e $img_path) {
                   3404:         $ima->Read($img_path);
                   3405:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3406:             my $width = $ima->Get('width');
                   3407:             my $height = $ima->Get('height');
                   3408:             if ($width > $resizewidth) {
                   3409: 	        my $factor = $width/$resizewidth;
                   3410:                 my $newheight = $height/$factor;
                   3411:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3412:                 $resized = 1;
                   3413:             }
                   3414:         }
                   3415:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3416:             my $width = $ima->Get('width');
                   3417:             my $height = $ima->Get('height');
                   3418:             if ($height > $resizeheight) {
                   3419:                 my $factor = $height/$resizeheight;
                   3420:                 my $newwidth = $width/$factor;
                   3421:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3422:                 $resized = 1;
                   3423:             }
                   3424:         }
                   3425:         if ($resized) {
                   3426:             $ima->Write($img_path);
                   3427:         }
                   3428:     }
                   3429:     return;
1.977     amueller 3430: }
                   3431: 
1.608     albertel 3432: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3433: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3434: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3435: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3436: #                                    canceloverwrite, or ''. 
                   3437: #                   if 'coursedoc': upload to the current course
                   3438: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3439: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3440: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3441: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3442: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3443: #        $allfiles - reference to hash for embedded objects
                   3444: #        $codebase - reference to hash for codebase of java objects
                   3445: #        $desuname - username for permanent storage of uploaded file
                   3446: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3447: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3448: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3449: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3450: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3451: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3452: #                    from File::MMagic.
1.858     raeburn  3453: # 
1.686     albertel 3454: # output: url of file in userspace, or error: <message> 
                   3455: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3456: 
1.531     albertel 3457: sub userfileupload {
1.1090    raeburn  3458:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3459:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3460:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3461:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3462:     $fname=&clean_filename($fname);
1.1090    raeburn  3463:     # See if there is anything left
1.257     www      3464:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3465:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3466:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3467:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3468:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3469:         my $now = time;
1.1090    raeburn  3470:         my $filepath;
1.1095    raeburn  3471:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3472:              $filepath = 'tmp/helprequests/'.$now;
                   3473:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3474:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3475:                          '_'.$env{'user.domain'}.'/pending';
                   3476:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3477:             my ($docuname,$docudom);
                   3478:             if ($destudom) {
                   3479:                 $docudom = $destudom;
                   3480:             } else {
                   3481:                 $docudom = $env{'user.domain'};
                   3482:             }
                   3483:             if ($destuname) {
                   3484:                 $docuname = $destuname;
                   3485:             } else {
                   3486:                 $docuname = $env{'user.name'};
                   3487:             }
                   3488:             if (exists($env{'form.group'})) {
                   3489:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3490:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3491:             }
                   3492:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3493:             if ($context eq 'canceloverwrite') {
                   3494:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3495:                 if (-e  $tempfile) {
                   3496:                     my @info = stat($tempfile);
                   3497:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3498:                         unlink($tempfile);
                   3499:                     }
                   3500:                 }
                   3501:                 return;
1.523     raeburn  3502:             }
                   3503:         }
1.1090    raeburn  3504:         # Create the directory if not present
1.741     raeburn  3505:         my @parts=split(/\//,$filepath);
                   3506:         my $fullpath = $perlvar{'lonDaemons'};
                   3507:         for (my $i=0;$i<@parts;$i++) {
                   3508:             $fullpath .= '/'.$parts[$i];
                   3509:             if ((-e $fullpath)!=1) {
                   3510:                 mkdir($fullpath,0777);
                   3511:             }
                   3512:         }
                   3513:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3514:         print $fh $env{'form.'.$formname};
                   3515:         close($fh);
1.1090    raeburn  3516:         if ($context eq 'existingfile') {
                   3517:             my @info = stat($fullpath.'/'.$fname);
                   3518:             return ($fullpath.'/'.$fname,$info[9]);
                   3519:         } else {
                   3520:             return $fullpath.'/'.$fname;
                   3521:         }
1.523     raeburn  3522:     }
1.995     raeburn  3523:     if ($subdir eq 'scantron') {
                   3524:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3525:     } else {
1.995     raeburn  3526:         $fname="$subdir/$fname";
                   3527:     }
1.1090    raeburn  3528:     if ($context eq 'coursedoc') {
1.638     albertel 3529: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3530: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3531:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3532:             return &finishuserfileupload($docuname,$docudom,
                   3533: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3534: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3535:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3536:         } else {
1.1218    raeburn  3537:             if ($env{'form.folder'}) {
                   3538:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3539:             }
1.638     albertel 3540:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3541: 				       $fname,$formname,$parser,
1.1095    raeburn  3542: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3543:         }
1.719     banghart 3544:     } elsif (defined($destuname)) {
                   3545:         my $docuname=$destuname;
                   3546:         my $docudom=$destudom;
1.860     raeburn  3547: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3548: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3549:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3550:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3551:     } else {
1.638     albertel 3552:         my $docuname=$env{'user.name'};
                   3553:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3554:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3555:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3556:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3557:         }
1.860     raeburn  3558: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3559: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3560:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3561:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3562:     }
1.271     www      3563: }
                   3564: 
                   3565: sub finishuserfileupload {
1.860     raeburn  3566:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3567:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3568:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3569:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3570:   
1.860     raeburn  3571:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3572:     $file=$fname;
                   3573:     if ($fname=~m|/|) {
                   3574:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3575: 	$path.=$fnamepath.'/';
                   3576:     }
1.259     www      3577:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3578:     my $count;
                   3579:     for ($count=4;$count<=$#parts;$count++) {
                   3580:         $filepath.="/$parts[$count]";
                   3581:         if ((-e $filepath)!=1) {
                   3582: 	    mkdir($filepath,0777);
                   3583:         }
                   3584:     }
1.984     neumanie 3585: 
1.258     www      3586: # Save the file
                   3587:     {
1.701     albertel 3588: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3589: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3590: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3591: 	    return '/adm/notfound.html';
                   3592: 	}
1.1090    raeburn  3593:         if ($context eq 'overwrite') {
1.1117    foxr     3594:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3595:             my $target = $filepath.'/'.$file;
                   3596:             if (-e $source) {
                   3597:                 my @info = stat($source);
                   3598:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3599:                     unless (&File::Copy::move($source,$target)) {
                   3600:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3601:                         return "Moving from $source failed";
                   3602:                     }
                   3603:                 } else {
                   3604:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3605:                 }
                   3606:             } else {
                   3607:                 return "Temporary file: $source missing";
                   3608:             }
                   3609:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3610: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3611: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3612: 	    return '/adm/notfound.html';
                   3613: 	}
1.570     albertel 3614: 	close(FH);
1.1051    raeburn  3615:         if ($resizewidth && $resizeheight) {
                   3616:             my $mm = new File::MMagic;
                   3617:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3618:             if ($mime_type =~ m{^image/}) {
                   3619: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3620:             }  
1.977     amueller 3621: 	}
1.258     www      3622:     }
1.1152    raeburn  3623:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3624:         if (ref($mimetype)) {
                   3625:             if ($$mimetype eq '') {
                   3626:                 my $mm = new File::MMagic;
                   3627:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3628:                 $$mimetype = $type;
                   3629:             }
                   3630:         }
                   3631:     }
1.637     raeburn  3632:     if ($parser eq 'parse') {
1.1152    raeburn  3633:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3634:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3635:                                                        $allfiles,$codebase);
                   3636:             unless ($parse_result eq 'ok') {
                   3637:                 &logthis('Failed to parse '.$filepath.$file.
                   3638: 	   	         ' for embedded media: '.$parse_result); 
                   3639:             }
1.637     raeburn  3640:         }
                   3641:     }
1.860     raeburn  3642:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3643:         my $input = $filepath.'/'.$file;
                   3644:         my $output = $filepath.'/'.'tn-'.$file;
                   3645:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3646:         system("convert -sample $thumbsize $input $output");
                   3647:         if (-e $filepath.'/'.'tn-'.$file) {
                   3648:             $fetchthumb  = 1; 
                   3649:         }
                   3650:     }
1.858     raeburn  3651:  
1.259     www      3652: # Notify homeserver to grep it
                   3653: #
1.984     neumanie 3654:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3655:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3656:     if ($fetchresult eq 'ok') {
1.860     raeburn  3657:         if ($fetchthumb) {
                   3658:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3659:             if ($thumbresult ne 'ok') {
                   3660:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3661:                          $docuhome.': '.$thumbresult);
                   3662:             }
                   3663:         }
1.259     www      3664: #
1.258     www      3665: # Return the URL to it
1.494     albertel 3666:         return '/uploaded/'.$path.$file;
1.263     www      3667:     } else {
1.494     albertel 3668:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3669: 		 ': '.$fetchresult);
1.263     www      3670:         return '/adm/notfound.html';
1.858     raeburn  3671:     }
1.493     albertel 3672: }
                   3673: 
1.637     raeburn  3674: sub extract_embedded_items {
1.961     raeburn  3675:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3676:     my @state = ();
1.1164    raeburn  3677:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3678:     my %javafiles = (
                   3679:                       codebase => '',
                   3680:                       code => '',
                   3681:                       archive => ''
                   3682:                     );
                   3683:     my %mediafiles = (
                   3684:                       src => '',
                   3685:                       movie => '',
                   3686:                      );
1.648     raeburn  3687:     my $p;
                   3688:     if ($content) {
                   3689:         $p = HTML::LCParser->new($content);
                   3690:     } else {
1.961     raeburn  3691:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3692:     }
1.641     albertel 3693:     while (my $t=$p->get_token()) {
1.640     albertel 3694: 	if ($t->[0] eq 'S') {
                   3695: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3696: 	    push(@state, $tagname);
1.648     raeburn  3697:             if (lc($tagname) eq 'allow') {
                   3698:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3699:             }
1.640     albertel 3700: 	    if (lc($tagname) eq 'img') {
                   3701: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3702: 	    }
1.886     albertel 3703: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3704:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3705:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3706:                 }
1.886     albertel 3707: 	    }
1.645     raeburn  3708:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3709:                 my $src;
1.645     raeburn  3710:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3711:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3712:                 } else {
1.1164    raeburn  3713:                     if ($attr->{'src'} ne '') {
                   3714:                         $src = $attr->{'src'};
                   3715:                         &add_filetype($allfiles,$src,'src');
                   3716:                     }
                   3717:                 }
                   3718:                 my $text = $p->get_trimmed_text();
                   3719:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3720:                     my @swfargs = split(/,/,$1);
                   3721:                     foreach my $item (@swfargs) {
                   3722:                         $item =~ s/["']//g;
                   3723:                         $item =~ s/^\s+//;
                   3724:                         $item =~ s/\s+$//;
                   3725:                     }
                   3726:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3727:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3728:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3729:                         } else {
                   3730:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3731:                         }
                   3732:                     }
1.645     raeburn  3733:                 }
                   3734:             }
                   3735:             if (lc($tagname) eq 'link') {
                   3736:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3737:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3738:                 }
                   3739:             }
1.640     albertel 3740: 	    if (lc($tagname) eq 'object' ||
                   3741: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3742: 		foreach my $item (keys(%javafiles)) {
                   3743: 		    $javafiles{$item} = '';
                   3744: 		}
1.1164    raeburn  3745:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3746:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3747:                 }
1.640     albertel 3748: 	    }
                   3749: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3750: 		my $name = lc($attr->{'name'});
                   3751: 		foreach my $item (keys(%javafiles)) {
                   3752: 		    if ($name eq $item) {
                   3753: 			$javafiles{$item} = $attr->{'value'};
                   3754: 			last;
                   3755: 		    }
                   3756: 		}
1.1164    raeburn  3757:                 my $pathfrom;
1.640     albertel 3758: 		foreach my $item (keys(%mediafiles)) {
                   3759: 		    if ($name eq $item) {
1.1164    raeburn  3760:                         $pathfrom = $attr->{'value'};
                   3761:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3762: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3763: 			last;
                   3764: 		    }
                   3765: 		}
1.1164    raeburn  3766:                 if ($name eq 'flashvars') {
                   3767:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3768:                 }
                   3769:                 if ($pathfrom ne '') {
                   3770:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3771:                                          $pathfrom);
                   3772:                 }
1.640     albertel 3773: 	    }
                   3774: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3775: 		foreach my $item (keys(%javafiles)) {
                   3776: 		    if ($attr->{$item}) {
                   3777: 			$javafiles{$item} = $attr->{$item};
                   3778: 			last;
                   3779: 		    }
                   3780: 		}
                   3781: 		foreach my $item (keys(%mediafiles)) {
                   3782: 		    if ($attr->{$item}) {
                   3783: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3784: 			last;
                   3785: 		    }
                   3786: 		}
1.1164    raeburn  3787:                 if (lc($tagname) eq 'embed') {
                   3788:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3789:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3790:                                              $attr->{'src'});
                   3791:                     }
                   3792:                 }
1.640     albertel 3793: 	    }
1.1243    raeburn  3794:             if (lc($tagname) eq 'iframe') {
                   3795:                 my $src = $attr->{'src'} ;
                   3796:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3797:                     &add_filetype($allfiles,$src,'src');
                   3798:                 } elsif ($src =~ m{^/}) {
                   3799:                     if ($env{'request.course.id'}) {
                   3800:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3801:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3802:                         my $url = &hreflocation('',$fullpath);
                   3803:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3804:                             my $relpath = $1;
                   3805:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3806:                                 &add_filetype($allfiles,$1,'src');
                   3807:                             }
                   3808:                         }
                   3809:                     }
                   3810:                 }
                   3811:             }
1.1164    raeburn  3812:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3813:                 pop(@state);
1.1164    raeburn  3814:             }
1.640     albertel 3815: 	} elsif ($t->[0] eq 'E') {
                   3816: 	    my ($tagname) = ($t->[1]);
                   3817: 	    if ($javafiles{'codebase'} ne '') {
                   3818: 		$javafiles{'codebase'} .= '/';
                   3819: 	    }  
                   3820: 	    if (lc($tagname) eq 'applet' ||
                   3821: 		lc($tagname) eq 'object' ||
                   3822: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3823: 		) {
                   3824: 		foreach my $item (keys(%javafiles)) {
                   3825: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3826: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3827: 			&add_filetype($allfiles,$file,$item);
                   3828: 		    }
                   3829: 		}
                   3830: 	    } 
                   3831: 	    pop @state;
                   3832: 	}
                   3833:     }
1.1164    raeburn  3834:     foreach my $id (sort(keys(%flashvars))) {
                   3835:         if ($shockwave{$id} ne '') {
                   3836:             my @pairs = split(/\&/,$flashvars{$id});
                   3837:             foreach my $pair (@pairs) {
                   3838:                 my ($key,$value) = split(/\=/,$pair);
                   3839:                 if ($key eq 'thumb') {
                   3840:                     &add_filetype($allfiles,$value,$key);
                   3841:                 } elsif ($key eq 'content') {
                   3842:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3843:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3844:                     if ($ext ne '') {
                   3845:                         &add_filetype($allfiles,$path.$value,$ext);
                   3846:                     }
                   3847:                 }
                   3848:             }
                   3849:         }
                   3850:     }
1.637     raeburn  3851:     return 'ok';
                   3852: }
                   3853: 
1.639     albertel 3854: sub add_filetype {
                   3855:     my ($allfiles,$file,$type)=@_;
                   3856:     if (exists($allfiles->{$file})) {
                   3857: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3858: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3859: 	}
                   3860:     } else {
                   3861: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3862:     }
                   3863: }
                   3864: 
1.1164    raeburn  3865: sub embedded_dependency {
                   3866:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3867:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3868:         if (($identifier ne '') &&
                   3869:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3870:             ($pathfrom ne '')) {
                   3871:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3872:             foreach my $dep (@{$related->{$identifier}}) {
                   3873:                 &add_filetype($allfiles,$path.$dep,'object');
                   3874:             }
                   3875:         }
                   3876:     }
                   3877:     return;
                   3878: }
                   3879: 
1.493     albertel 3880: sub removeuploadedurl {
1.984     neumanie 3881:     my ($url)=@_;	
                   3882:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3883:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3884: }
                   3885: 
                   3886: sub removeuserfile {
                   3887:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3888:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3889:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3890:     if ($result eq 'ok') {	
1.798     raeburn  3891:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3892:             my $metafile = $fname.'.meta';
                   3893:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3894: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3895:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3896:             my $sqlresult = 
1.823     albertel 3897:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3898:                                         'portfolio_metadata',$group,
                   3899:                                         'delete');
1.798     raeburn  3900:         }
                   3901:     }
                   3902:     return $result;
1.257     www      3903: }
1.15      www      3904: 
1.530     albertel 3905: sub mkdiruserfile {
                   3906:     my ($docuname,$docudom,$dir)=@_;
                   3907:     my $home=&homeserver($docuname,$docudom);
                   3908:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3909: }
                   3910: 
1.531     albertel 3911: sub renameuserfile {
                   3912:     my ($docuname,$docudom,$old,$new)=@_;
                   3913:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3914:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3915:                         &escape("$old").':'.&escape("$new"),$home);
                   3916:     if ($result eq 'ok') {
                   3917:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3918:             my $oldmeta = $old.'.meta';
                   3919:             my $newmeta = $new.'.meta';
                   3920:             my $metaresult = 
                   3921:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3922: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3923:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3924:             my $sqlresult = 
1.823     albertel 3925:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3926:                                         'portfolio_metadata',$group,
                   3927:                                         'delete');
1.798     raeburn  3928:         }
                   3929:     }
                   3930:     return $result;
1.531     albertel 3931: }
                   3932: 
1.14      www      3933: # ------------------------------------------------------------------------- Log
                   3934: 
                   3935: sub log {
                   3936:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3937:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3938: }
                   3939: 
                   3940: # ------------------------------------------------------------------ Course Log
1.352     www      3941: #
                   3942: # This routine flushes several buffers of non-mission-critical nature
                   3943: #
1.157     www      3944: 
                   3945: sub flushcourselogs {
1.352     www      3946:     &logthis('Flushing log buffers');
                   3947: #
                   3948: # course logs
                   3949: # This is a log of all transactions in a course, which can be used
                   3950: # for data mining purposes
                   3951: #
                   3952: # It also collects the courseid database, which lists last transaction
                   3953: # times and course titles for all courseids
                   3954: #
                   3955:     my %courseidbuffer=();
1.921     raeburn  3956:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3957:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3958: 		          &escape($courselogs{$crsid}),
                   3959: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3960: 	    delete $courselogs{$crsid};
                   3961:         } else {
                   3962:             &logthis('Failed to flush log buffer for '.$crsid);
                   3963:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3964:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3965:                         " exceeded maximum size, deleting.</font>");
                   3966:                delete $courselogs{$crsid};
                   3967:             }
1.352     www      3968:         }
1.920     raeburn  3969:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3970:             'description' => $coursedescrbuf{$crsid},
                   3971:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3972:             'type'        => $coursetypebuf{$crsid},
                   3973:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3974:         };
1.191     harris41 3975:     }
1.352     www      3976: #
                   3977: # Write course id database (reverse lookup) to homeserver of courses 
                   3978: # Is used in pickcourse
                   3979: #
1.840     albertel 3980:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3981:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3982:                                     $courseidbuffer{$crs_home},
                   3983:                                     $crs_home,'timeonly');
1.352     www      3984:     }
                   3985: #
                   3986: # File accesses
                   3987: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3988: #
1.449     matthew  3989:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3990:         if ($entry =~ /___count$/) {
                   3991:             my ($dom,$name);
1.807     albertel 3992:             ($dom,$name,undef)=
1.811     albertel 3993: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3994:             if (! defined($dom) || $dom eq '' || 
                   3995:                 ! defined($name) || $name eq '') {
1.620     albertel 3996:                 my $cid = $env{'request.course.id'};
                   3997:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3998:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3999:             }
1.450     matthew  4000:             my $value = $accesshash{$entry};
                   4001:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4002:             my %temphash=($url => $value);
1.449     matthew  4003:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4004:             if ($result eq 'ok') {
                   4005:                 delete $accesshash{$entry};
                   4006:             }
                   4007:         } else {
1.811     albertel 4008:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4009:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4010:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4011:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4012:                 delete $accesshash{$entry};
                   4013:             }
1.185     www      4014:         }
1.191     harris41 4015:     }
1.352     www      4016: #
                   4017: # Roles
                   4018: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4019: #
1.800     albertel 4020:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4021:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4022: 	    split(/\:/,$entry);
                   4023:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4024:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4025:                 $rudom,$runame) eq 'ok') {
                   4026: 	    delete $userrolehash{$entry};
                   4027:         }
                   4028:     }
1.662     raeburn  4029: #
                   4030: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   4031: #
                   4032:     my %domrolebuffer = ();
1.1000    raeburn  4033:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4034:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4035:         if ($domrolebuffer{$rudom}) {
                   4036:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4037:                       '='.&escape($domainrolehash{$entry});
                   4038:         } else {
                   4039:             $domrolebuffer{$rudom}.=&escape($entry).
                   4040:                       '='.&escape($domainrolehash{$entry});
                   4041:         }
                   4042:         delete $domainrolehash{$entry};
                   4043:     }
                   4044:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 4045: 	my %servers = &get_servers($dom,'library');
                   4046: 	foreach my $tryserver (keys(%servers)) {
                   4047: 	    unless (&reply('domroleput:'.$dom.':'.
                   4048: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4049: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4050: 	    }
1.662     raeburn  4051:         }
                   4052:     }
1.186     www      4053:     $dumpcount++;
1.157     www      4054: }
                   4055: 
                   4056: sub courselog {
                   4057:     my $what=shift;
1.158     www      4058:     $what=time.':'.$what;
1.620     albertel 4059:     unless ($env{'request.course.id'}) { return ''; }
                   4060:     $coursedombuf{$env{'request.course.id'}}=
                   4061:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4062:     $coursenumbuf{$env{'request.course.id'}}=
                   4063:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4064:     $coursehombuf{$env{'request.course.id'}}=
                   4065:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4066:     $coursedescrbuf{$env{'request.course.id'}}=
                   4067:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4068:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4069:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4070:     $courseownerbuf{$env{'request.course.id'}}=
                   4071:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4072:     $coursetypebuf{$env{'request.course.id'}}=
                   4073:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4074:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4075: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4076:     } else {
1.620     albertel 4077: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4078:     }
1.620     albertel 4079:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4080: 	&flushcourselogs();
                   4081:     }
1.158     www      4082: }
                   4083: 
                   4084: sub courseacclog {
                   4085:     my $fnsymb=shift;
1.620     albertel 4086:     unless ($env{'request.course.id'}) { return ''; }
                   4087:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4088:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4089:         $what.=':POST';
1.583     matthew  4090:         # FIXME: Probably ought to escape things....
1.800     albertel 4091: 	foreach my $key (keys(%env)) {
                   4092:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4093:                 my $formitem = $1;
                   4094:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4095:                     $what.=':'.$formitem.'='.$env{$key};
                   4096:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4097:                     $what.=':'.$formitem.'='.$env{$key};
                   4098:                 }
1.158     www      4099:             }
1.191     harris41 4100:         }
1.583     matthew  4101:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4102:         # FIXME: We should not be depending on a form parameter that someone
                   4103:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4104:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4105:             $what.= ':POST';
                   4106:             # FIXME: Probably ought to escape things....
                   4107:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4108:                                  'crsdiscuss') {
1.620     albertel 4109:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4110:             }
                   4111:         }
1.158     www      4112:     }
                   4113:     &courselog($what);
1.149     www      4114: }
                   4115: 
1.185     www      4116: sub countacc {
                   4117:     my $url=&declutter(shift);
1.458     matthew  4118:     return if (! defined($url) || $url eq '');
1.620     albertel 4119:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4120: #
                   4121: # Mark that this url was used in this course
                   4122: #
1.620     albertel 4123:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4124: #
                   4125: # Increase the access count for this resource in this child process
                   4126: #
1.281     www      4127:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4128:     $accesshash{$key}++;
1.185     www      4129: }
1.349     www      4130: 
1.361     www      4131: sub linklog {
                   4132:     my ($from,$to)=@_;
                   4133:     $from=&declutter($from);
                   4134:     $to=&declutter($to);
                   4135:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4136:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4137: }
1.1160    www      4138: 
                   4139: sub statslog {
                   4140:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4141:     if ($users<2) { return; }
                   4142:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4143:             'course'       => $env{'request.course.id'},
                   4144:             'sections'     => '"all"',
                   4145:             'num_students' => $users,
                   4146:             'part'         => $part,
                   4147:             'symb'         => $symb,
                   4148:             'mean_tries'   => $av_attempts,
                   4149:             'deg_of_diff'  => $degdiff});
                   4150:     foreach my $key (keys(%dynstore)) {
                   4151:         $accesshash{$key}=$dynstore{$key};
                   4152:     }
                   4153: }
1.361     www      4154:   
1.349     www      4155: sub userrolelog {
                   4156:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4157:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4158:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4159:        $userrolehash
                   4160:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4161:                     =$tend.':'.$tstart;
1.662     raeburn  4162:     }
1.1169    droeschl 4163:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4164:        $userrolehash
                   4165:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4166:                     =$tend.':'.$tstart;
                   4167:     }
1.1169    droeschl 4168:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4169:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4170:        $domainrolehash
                   4171:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4172:                     = $tend.':'.$tstart;
                   4173:     }
1.351     www      4174: }
                   4175: 
1.957     raeburn  4176: sub courserolelog {
                   4177:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4178:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4179:         my $cdom = $1;
                   4180:         my $cnum = $2;
                   4181:         my $sec = $3;
                   4182:         my $namespace = 'rolelog';
                   4183:         my %storehash = (
                   4184:                            role    => $trole,
                   4185:                            start   => $tstart,
                   4186:                            end     => $tend,
                   4187:                            selfenroll => $selfenroll,
                   4188:                            context    => $context,
                   4189:                         );
                   4190:         if ($trole eq 'gr') {
                   4191:             $namespace = 'groupslog';
                   4192:             $storehash{'group'} = $sec;
                   4193:         } else {
                   4194:             $storehash{'section'} = $sec;
                   4195:         }
1.1188    raeburn  4196:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4197:                    $domain,$cnum,$cdom);
1.1184    raeburn  4198:         if (($trole ne 'st') || ($sec ne '')) {
                   4199:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4200:         }
                   4201:     }
                   4202:     return;
                   4203: }
                   4204: 
1.1184    raeburn  4205: sub domainrolelog {
                   4206:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4207:     if ($area =~ m{^/($match_domain)/$}) {
                   4208:         my $cdom = $1;
                   4209:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4210:         my $namespace = 'rolelog';
                   4211:         my %storehash = (
                   4212:                            role    => $trole,
                   4213:                            start   => $tstart,
                   4214:                            end     => $tend,
                   4215:                            context => $context,
                   4216:                         );
1.1188    raeburn  4217:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4218:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4219:     }
                   4220:     return;
                   4221: 
                   4222: }
                   4223: 
                   4224: sub coauthorrolelog {
                   4225:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4226:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4227:         my $audom = $1;
                   4228:         my $auname = $2;
                   4229:         my $namespace = 'rolelog';
                   4230:         my %storehash = (
                   4231:                            role    => $trole,
                   4232:                            start   => $tstart,
                   4233:                            end     => $tend,
                   4234:                            context => $context,
                   4235:                         );
1.1188    raeburn  4236:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4237:                    $domain,$auname,$audom);
1.1184    raeburn  4238:     }
                   4239:     return;
                   4240: }
                   4241: 
1.351     www      4242: sub get_course_adv_roles {
1.948     raeburn  4243:     my ($cid,$codes) = @_;
1.620     albertel 4244:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4245:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4246:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4247:     my %nothide=();
1.800     albertel 4248:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4249:         if ($user !~ /:/) {
                   4250: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4251:         } else {
                   4252:             $nothide{$user}=1;
                   4253:         }
1.470     www      4254:     }
1.1219    raeburn  4255:     my @possdoms = ($coursehash{'domain'});
                   4256:     if ($coursehash{'checkforpriv'}) {
                   4257:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4258:     }
1.351     www      4259:     my %returnhash=();
                   4260:     my %dumphash=
                   4261:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4262:     my $now=time;
1.997     raeburn  4263:     my %privileged;
1.1000    raeburn  4264:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4265: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4266:         if (($tstart) && ($tstart<0)) { next; }
                   4267:         if (($tend) && ($tend<$now)) { next; }
                   4268:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4269:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4270: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4271:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4272:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4273: 	if ($role eq 'cr') { next; }
1.948     raeburn  4274:         if ($codes) {
                   4275:             if ($section) { $role .= ':'.$section; }
                   4276:             if ($returnhash{$role}) {
                   4277:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4278:             } else {
                   4279:                 $returnhash{$role}=$username.':'.$domain;
                   4280:             }
1.351     www      4281:         } else {
1.988     raeburn  4282:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4283:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4284:             if ($returnhash{$key}) {
                   4285: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4286:             } else {
                   4287:                 $returnhash{$key}=$username.':'.$domain;
                   4288:             }
1.351     www      4289:         }
1.948     raeburn  4290:     }
1.400     www      4291:     return %returnhash;
                   4292: }
                   4293: 
                   4294: sub get_my_roles {
1.937     raeburn  4295:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4296:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4297:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4298:     my (%dumphash,%nothide);
1.1086    raeburn  4299:     if ($context eq 'userroles') {
1.1166    raeburn  4300:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4301:     } else {
1.1219    raeburn  4302:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4303:         if ($hidepriv) {
                   4304:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4305:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4306:                 if ($user !~ /:/) {
                   4307:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4308:                 } else {
                   4309:                     $nothide{$user} = 1;
                   4310:                 }
                   4311:             }
                   4312:         }
1.858     raeburn  4313:     }
1.400     www      4314:     my %returnhash=();
                   4315:     my $now=time;
1.999     raeburn  4316:     my %privileged;
1.800     albertel 4317:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4318:         my ($role,$tend,$tstart);
                   4319:         if ($context eq 'userroles') {
1.1149    raeburn  4320:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4321: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4322:         } else {
                   4323:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4324:         }
1.400     www      4325:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4326:         my $status = 'active';
1.939     raeburn  4327:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4328:             $status = 'previous';
                   4329:         } 
                   4330:         if (($tstart) && ($now<$tstart)) {
                   4331:             $status = 'future';
                   4332:         }
                   4333:         if (ref($types) eq 'ARRAY') {
                   4334:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4335:                 next;
                   4336:             } 
                   4337:         } else {
                   4338:             if ($status ne 'active') {
                   4339:                 next;
                   4340:             }
                   4341:         }
1.867     raeburn  4342:         my ($rolecode,$username,$domain,$section,$area);
                   4343:         if ($context eq 'userroles') {
1.1186    raeburn  4344:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4345:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4346:         } else {
                   4347:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4348:         }
1.832     raeburn  4349:         if (ref($roledoms) eq 'ARRAY') {
                   4350:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4351:                 next;
                   4352:             }
                   4353:         }
                   4354:         if (ref($roles) eq 'ARRAY') {
                   4355:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4356:                 if ($role =~ /^cr\//) {
                   4357:                     if (!grep(/^cr$/,@{$roles})) {
                   4358:                         next;
                   4359:                     }
1.1104    raeburn  4360:                 } elsif ($role =~ /^gr\//) {
                   4361:                     if (!grep(/^gr$/,@{$roles})) {
                   4362:                         next;
                   4363:                     }
1.922     raeburn  4364:                 } else {
                   4365:                     next;
                   4366:                 }
1.832     raeburn  4367:             }
1.867     raeburn  4368:         }
1.937     raeburn  4369:         if ($hidepriv) {
1.1219    raeburn  4370:             my @privroles = ('dc','su');
1.999     raeburn  4371:             if ($context eq 'userroles') {
1.1219    raeburn  4372:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4373:             } else {
1.1219    raeburn  4374:                 my $possdoms = [$domain];
                   4375:                 if (ref($roledoms) eq 'ARRAY') {
                   4376:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4377:                 }
1.1219    raeburn  4378:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4379:                     if (!$nothide{$username.':'.$domain}) {
                   4380:                         next;
                   4381:                     }
                   4382:                 }
1.937     raeburn  4383:             }
                   4384:         }
1.933     raeburn  4385:         if ($withsec) {
                   4386:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4387:                 $tstart.':'.$tend;
                   4388:         } else {
                   4389:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4390:         }
1.832     raeburn  4391:     }
1.373     www      4392:     return %returnhash;
1.399     www      4393: }
                   4394: 
                   4395: # ----------------------------------------------------- Frontpage Announcements
                   4396: #
                   4397: #
                   4398: 
                   4399: sub postannounce {
                   4400:     my ($server,$text)=@_;
1.844     albertel 4401:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4402:     unless ($text=~/\w/) { $text=''; }
                   4403:     return &reply('setannounce:'.&escape($text),$server);
                   4404: }
                   4405: 
                   4406: sub getannounce {
1.448     albertel 4407: 
                   4408:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4409: 	my $announcement='';
1.800     albertel 4410: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4411: 	close($fh);
1.399     www      4412: 	if ($announcement=~/\w/) { 
                   4413: 	    return 
                   4414:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4415:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4416: 	} else {
                   4417: 	    return '';
                   4418: 	}
                   4419:     } else {
                   4420: 	return '';
                   4421:     }
1.351     www      4422: }
1.353     www      4423: 
                   4424: # ---------------------------------------------------------- Course ID routines
                   4425: # Deal with domain's nohist_courseid.db files
                   4426: #
                   4427: 
                   4428: sub courseidput {
1.921     raeburn  4429:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4430:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4431:     my $outcome;
                   4432:     if ($caller eq 'timeonly') {
                   4433:         my $cids = '';
                   4434:         foreach my $item (keys(%$storehash)) {
                   4435:             $cids.=&escape($item).'&';
                   4436:         }
                   4437:         $cids=~s/\&$//;
                   4438:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4439:                           $coursehome);       
                   4440:     } else {
                   4441:         my $items = '';
                   4442:         foreach my $item (keys(%$storehash)) {
                   4443:             $items.= &escape($item).'='.
                   4444:                      &freeze_escape($$storehash{$item}).'&';
                   4445:         }
                   4446:         $items=~s/\&$//;
                   4447:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4448:                           $coursehome);
1.918     raeburn  4449:     }
                   4450:     if ($outcome eq 'unknown_cmd') {
                   4451:         my $what;
                   4452:         foreach my $cid (keys(%$storehash)) {
                   4453:             $what .= &escape($cid).'=';
1.921     raeburn  4454:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4455:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4456:             }
                   4457:             $what =~ s/\:$/&/;
                   4458:         }
                   4459:         $what =~ s/\&$//;  
                   4460:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4461:     } else {
                   4462:         return $outcome;
                   4463:     }
1.353     www      4464: }
                   4465: 
                   4466: sub courseiddump {
1.921     raeburn  4467:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4468:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4469:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4470:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4471:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4472:     my $as_hash = 1;
                   4473:     my %returnhash;
                   4474:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4475:     my %libserv = &all_library();
                   4476:     foreach my $tryserver (keys(%libserv)) {
                   4477:         if ( (  $hostidflag == 1 
                   4478: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4479: 	     || (!defined($hostidflag)) ) {
                   4480: 
1.918     raeburn  4481: 	    if (($domfilter eq '') ||
                   4482: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4483:                 my $rep;
                   4484:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4485:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4486:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4487:                                 &escape($descfilter), &escape($instcodefilter), 
                   4488:                                 &escape($ownerfilter), &escape($coursefilter),
                   4489:                                 &escape($typefilter), &escape($regexp_ok), 
                   4490:                                 $as_hash, &escape($selfenrollonly), 
                   4491:                                 &escape($catfilter), $showhidden, $caller, 
                   4492:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4493:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4494:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4495:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4496:                 } else {
                   4497:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4498:                              $sincefilter.':'.&escape($descfilter).':'.
                   4499:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4500:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4501:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4502:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4503:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4504:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4505:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4506:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4507:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4508:                 }
                   4509:                      
1.918     raeburn  4510:                 my @pairs=split(/\&/,$rep);
                   4511:                 foreach my $item (@pairs) {
                   4512:                     my ($key,$value)=split(/\=/,$item,2);
                   4513:                     $key = &unescape($key);
                   4514:                     next if ($key =~ /^error: 2 /);
                   4515:                     my $result = &thaw_unescape($value);
                   4516:                     if (ref($result) eq 'HASH') {
                   4517:                         $returnhash{$key}=$result;
                   4518:                     } else {
1.921     raeburn  4519:                         my @responses = split(/:/,$value);
                   4520:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4521:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4522:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4523:                         }
1.1008    raeburn  4524:                     }
1.353     www      4525:                 }
                   4526:             }
                   4527:         }
                   4528:     }
                   4529:     return %returnhash;
                   4530: }
                   4531: 
1.1055    raeburn  4532: sub courselastaccess {
                   4533:     my ($cdom,$cnum,$hostidref) = @_;
                   4534:     my %returnhash;
                   4535:     if ($cdom && $cnum) {
                   4536:         my $chome = &homeserver($cnum,$cdom);
                   4537:         if ($chome ne 'no_host') {
                   4538:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4539:             &extract_lastaccess(\%returnhash,$rep);
                   4540:         }
                   4541:     } else {
                   4542:         if (!$cdom) { $cdom=''; }
                   4543:         my %libserv = &all_library();
                   4544:         foreach my $tryserver (keys(%libserv)) {
                   4545:             if (ref($hostidref) eq 'ARRAY') {
                   4546:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4547:             } 
                   4548:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4549:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4550:                 &extract_lastaccess(\%returnhash,$rep);
                   4551:             }
                   4552:         }
                   4553:     }
                   4554:     return %returnhash;
                   4555: }
                   4556: 
                   4557: sub extract_lastaccess {
                   4558:     my ($returnhash,$rep) = @_;
                   4559:     if (ref($returnhash) eq 'HASH') {
                   4560:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4561:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4562:                  $rep eq '') {
                   4563:             my @pairs=split(/\&/,$rep);
                   4564:             foreach my $item (@pairs) {
                   4565:                 my ($key,$value)=split(/\=/,$item,2);
                   4566:                 $key = &unescape($key);
                   4567:                 next if ($key =~ /^error: 2 /);
                   4568:                 $returnhash->{$key} = &thaw_unescape($value);
                   4569:             }
                   4570:         }
                   4571:     }
                   4572:     return;
                   4573: }
                   4574: 
1.658     raeburn  4575: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4576: 
                   4577: sub dcmailput {
1.685     raeburn  4578:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4579:     my $status = &Apache::lonnet::critical(
1.740     www      4580:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4581:        &escape($message),$server);
1.662     raeburn  4582:     return $status;
                   4583: }
                   4584: 
1.658     raeburn  4585: sub dcmaildump {
                   4586:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4587:     my %returnhash=();
1.846     albertel 4588: 
                   4589:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4590:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4591:                                                          &escape($enddate).':';
                   4592: 	my @esc_senders=map { &escape($_)} @$senders;
                   4593: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4594: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4595:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4596:             if (($key) && ($value)) {
                   4597:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4598:             }
                   4599:         }
                   4600:     }
                   4601:     return %returnhash;
                   4602: }
1.662     raeburn  4603: # ---------------------------------------------------------- Domain roles
                   4604: 
                   4605: sub get_domain_roles {
                   4606:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4607:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4608:         $startdate = '.';
                   4609:     }
1.1018    raeburn  4610:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4611:         $enddate = '.';
                   4612:     }
1.922     raeburn  4613:     my $rolelist;
                   4614:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4615:         $rolelist = join('&',@{$roles});
1.922     raeburn  4616:     }
1.662     raeburn  4617:     my %personnel = ();
1.841     albertel 4618: 
                   4619:     my %servers = &get_servers($dom,'library');
                   4620:     foreach my $tryserver (keys(%servers)) {
                   4621: 	%{$personnel{$tryserver}}=();
                   4622: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4623: 					    &escape($startdate).':'.
                   4624: 					    &escape($enddate).':'.
                   4625: 					    &escape($rolelist), $tryserver))) {
                   4626: 	    my ($key,$value) = split(/\=/,$line,2);
                   4627: 	    if (($key) && ($value)) {
                   4628: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4629: 	    }
                   4630: 	}
1.662     raeburn  4631:     }
                   4632:     return %personnel;
                   4633: }
1.658     raeburn  4634: 
1.1057    www      4635: # ----------------------------------------------------------- Interval timing 
1.149     www      4636: 
1.1153    www      4637: {
                   4638: # Caches needed for speedup of navmaps
                   4639: # We don't want to cache this for very long at all (5 seconds at most)
                   4640: # 
                   4641: # The user for whom we cache
                   4642: my $cachedkey='';
                   4643: # The cached times for this user
                   4644: my %cachedtimes=();
                   4645: # When this was last done
1.1282    raeburn  4646: my $cachedtime='';
1.1153    www      4647: 
                   4648: sub load_all_first_access {
1.1154    raeburn  4649:     my ($uname,$udom)=@_;
1.1156    www      4650:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4651:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4652:         return;
                   4653:     }
                   4654:     $cachedtime=time;
                   4655:     $cachedkey=$uname.':'.$udom;
                   4656:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4657: }
                   4658: 
1.504     albertel 4659: sub get_first_access {
1.1162    raeburn  4660:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4661:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4662:     if ($argsymb) { $symb=$argsymb; }
                   4663:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4664:     if ($argmap) { $map = $argmap; }
1.926     albertel 4665:     if ($type eq 'course') {
                   4666: 	$res='course';
                   4667:     } elsif ($type eq 'map') {
1.588     albertel 4668: 	$res=&symbread($map);
                   4669:     } else {
                   4670: 	$res=$symb;
                   4671:     }
1.1153    www      4672:     &load_all_first_access($uname,$udom);
                   4673:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4674: }
                   4675: 
                   4676: sub set_first_access {
1.1162    raeburn  4677:     my ($type,$interval)=@_;
1.790     albertel 4678:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4679:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4680:     if ($type eq 'course') {
                   4681: 	$res='course';
                   4682:     } elsif ($type eq 'map') {
1.588     albertel 4683: 	$res=&symbread($map);
                   4684:     } else {
                   4685: 	$res=$symb;
                   4686:     }
1.1153    www      4687:     $cachedkey='';
1.1162    raeburn  4688:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4689:     if (!$firstaccess) {
1.1162    raeburn  4690:         my $start = time;
                   4691: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4692:                           $udom,$uname);
                   4693:         if ($putres eq 'ok') {
                   4694:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4695:                  $udom,$uname); 
                   4696:             &appenv(
                   4697:                      {
                   4698:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4699:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4700:                      }
                   4701:                   );
                   4702:         }
                   4703:         return $putres;
1.505     albertel 4704:     }
                   4705:     return 'already_set';
1.504     albertel 4706: }
1.1153    www      4707: }
1.1282    raeburn  4708: 
1.110     www      4709: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4710: 
                   4711: sub expirespread {
                   4712:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4713:     my $cid=$env{'request.course.id'}; 
1.110     www      4714:     if ($cid) {
                   4715:        my $now=time;
                   4716:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4717:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4718:                             $env{'course.'.$cid.'.num'}.
1.110     www      4719: 	        	    ':nohist_expirationdates:'.
                   4720:                             &escape($key).'='.$now,
1.620     albertel 4721:                             $env{'course.'.$cid.'.home'})
1.110     www      4722:     }
                   4723:     return 'ok';
1.14      www      4724: }
                   4725: 
1.109     www      4726: # ----------------------------------------------------- Devalidate Spreadsheets
                   4727: 
                   4728: sub devalidate {
1.325     www      4729:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4730:     my $cid=$env{'request.course.id'}; 
1.109     www      4731:     if ($cid) {
1.391     matthew  4732:         # delete the stored spreadsheets for
                   4733:         # - the student level sheet of this user in course's homespace
                   4734:         # - the assessment level sheet for this resource 
                   4735:         #   for this user in user's homespace
1.553     albertel 4736: 	# - current conditional state info
1.325     www      4737: 	my $key=$uname.':'.$udom.':';
1.109     www      4738:         my $status=
1.299     matthew  4739: 	    &del('nohist_calculatedsheets',
1.391     matthew  4740: 		 [$key.'studentcalc:'],
1.620     albertel 4741: 		 $env{'course.'.$cid.'.domain'},
                   4742: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4743: 		.' '.
                   4744: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4745: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4746:         unless ($status eq 'ok ok') {
                   4747:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4748:                     $uname.' at '.$udom.' for '.
1.109     www      4749: 		    $symb.': '.$status);
1.133     albertel 4750:         }
1.553     albertel 4751: 	&delenv('user.state.'.$cid);
1.109     www      4752:     }
                   4753: }
                   4754: 
1.265     albertel 4755: sub get_scalar {
                   4756:     my ($string,$end) = @_;
                   4757:     my $value;
                   4758:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4759: 	$value = $1;
                   4760:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4761: 	$value = $1;
                   4762:     }
                   4763:     return &unescape($value);
                   4764: }
                   4765: 
                   4766: sub array2str {
                   4767:   my (@array) = @_;
                   4768:   my $result=&arrayref2str(\@array);
                   4769:   $result=~s/^__ARRAY_REF__//;
                   4770:   $result=~s/__END_ARRAY_REF__$//;
                   4771:   return $result;
                   4772: }
                   4773: 
1.204     albertel 4774: sub arrayref2str {
                   4775:   my ($arrayref) = @_;
1.265     albertel 4776:   my $result='__ARRAY_REF__';
1.204     albertel 4777:   foreach my $elem (@$arrayref) {
1.265     albertel 4778:     if(ref($elem) eq 'ARRAY') {
                   4779:       $result.=&arrayref2str($elem).'&';
                   4780:     } elsif(ref($elem) eq 'HASH') {
                   4781:       $result.=&hashref2str($elem).'&';
                   4782:     } elsif(ref($elem)) {
                   4783:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4784:     } else {
                   4785:       $result.=&escape($elem).'&';
                   4786:     }
                   4787:   }
                   4788:   $result=~s/\&$//;
1.265     albertel 4789:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4790:   return $result;
                   4791: }
                   4792: 
1.168     albertel 4793: sub hash2str {
1.204     albertel 4794:   my (%hash) = @_;
                   4795:   my $result=&hashref2str(\%hash);
1.265     albertel 4796:   $result=~s/^__HASH_REF__//;
                   4797:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4798:   return $result;
                   4799: }
                   4800: 
                   4801: sub hashref2str {
                   4802:   my ($hashref)=@_;
1.265     albertel 4803:   my $result='__HASH_REF__';
1.800     albertel 4804:   foreach my $key (sort(keys(%$hashref))) {
                   4805:     if (ref($key) eq 'ARRAY') {
                   4806:       $result.=&arrayref2str($key).'=';
                   4807:     } elsif (ref($key) eq 'HASH') {
                   4808:       $result.=&hashref2str($key).'=';
                   4809:     } elsif (ref($key)) {
1.265     albertel 4810:       $result.='=';
1.800     albertel 4811:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4812:     } else {
1.1132    raeburn  4813: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4814:     }
                   4815: 
1.800     albertel 4816:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4817:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4818:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4819:       $result.=&hashref2str($hashref->{$key}).'&';
                   4820:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4821:        $result.='&';
1.800     albertel 4822:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4823:     } else {
1.800     albertel 4824:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4825:     }
                   4826:   }
1.168     albertel 4827:   $result=~s/\&$//;
1.265     albertel 4828:   $result .= '__END_HASH_REF__';
1.168     albertel 4829:   return $result;
                   4830: }
                   4831: 
                   4832: sub str2hash {
1.265     albertel 4833:     my ($string)=@_;
                   4834:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4835:     return %$hash;
                   4836: }
                   4837: 
                   4838: sub str2hashref {
1.168     albertel 4839:   my ($string) = @_;
1.265     albertel 4840: 
                   4841:   my %hash;
                   4842: 
                   4843:   if($string !~ /^__HASH_REF__/) {
                   4844:       if (! ($string eq '' || !defined($string))) {
                   4845: 	  $hash{'error'}='Not hash reference';
                   4846:       }
                   4847:       return (\%hash, $string);
                   4848:   }
                   4849: 
                   4850:   $string =~ s/^__HASH_REF__//;
                   4851: 
                   4852:   while($string !~ /^__END_HASH_REF__/) {
                   4853:       #key
                   4854:       my $key='';
                   4855:       if($string =~ /^__HASH_REF__/) {
                   4856:           ($key, $string)=&str2hashref($string);
                   4857:           if(defined($key->{'error'})) {
                   4858:               $hash{'error'}='Bad data';
                   4859:               return (\%hash, $string);
                   4860:           }
                   4861:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4862:           ($key, $string)=&str2arrayref($string);
                   4863:           if($key->[0] eq 'Array reference error') {
                   4864:               $hash{'error'}='Bad data';
                   4865:               return (\%hash, $string);
                   4866:           }
                   4867:       } else {
                   4868:           $string =~ s/^(.*?)=//;
1.267     albertel 4869: 	  $key=&unescape($1);
1.265     albertel 4870:       }
                   4871:       $string =~ s/^=//;
                   4872: 
                   4873:       #value
                   4874:       my $value='';
                   4875:       if($string =~ /^__HASH_REF__/) {
                   4876:           ($value, $string)=&str2hashref($string);
                   4877:           if(defined($value->{'error'})) {
                   4878:               $hash{'error'}='Bad data';
                   4879:               return (\%hash, $string);
                   4880:           }
                   4881:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4882:           ($value, $string)=&str2arrayref($string);
                   4883:           if($value->[0] eq 'Array reference error') {
                   4884:               $hash{'error'}='Bad data';
                   4885:               return (\%hash, $string);
                   4886:           }
                   4887:       } else {
                   4888: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4889:       }
                   4890:       $string =~ s/^&//;
                   4891: 
                   4892:       $hash{$key}=$value;
1.204     albertel 4893:   }
1.265     albertel 4894: 
                   4895:   $string =~ s/^__END_HASH_REF__//;
                   4896: 
                   4897:   return (\%hash, $string);
1.204     albertel 4898: }
                   4899: 
                   4900: sub str2array {
1.265     albertel 4901:     my ($string)=@_;
                   4902:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4903:     return @$array;
                   4904: }
                   4905: 
                   4906: sub str2arrayref {
1.204     albertel 4907:   my ($string) = @_;
1.265     albertel 4908:   my @array;
                   4909: 
                   4910:   if($string !~ /^__ARRAY_REF__/) {
                   4911:       if (! ($string eq '' || !defined($string))) {
                   4912: 	  $array[0]='Array reference error';
                   4913:       }
                   4914:       return (\@array, $string);
                   4915:   }
                   4916: 
                   4917:   $string =~ s/^__ARRAY_REF__//;
                   4918: 
                   4919:   while($string !~ /^__END_ARRAY_REF__/) {
                   4920:       my $value='';
                   4921:       if($string =~ /^__HASH_REF__/) {
                   4922:           ($value, $string)=&str2hashref($string);
                   4923:           if(defined($value->{'error'})) {
                   4924:               $array[0] ='Array reference error';
                   4925:               return (\@array, $string);
                   4926:           }
                   4927:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4928:           ($value, $string)=&str2arrayref($string);
                   4929:           if($value->[0] eq 'Array reference error') {
                   4930:               $array[0] ='Array reference error';
                   4931:               return (\@array, $string);
                   4932:           }
                   4933:       } else {
                   4934: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4935:       }
                   4936:       $string =~ s/^&//;
                   4937: 
                   4938:       push(@array, $value);
1.191     harris41 4939:   }
1.265     albertel 4940: 
                   4941:   $string =~ s/^__END_ARRAY_REF__//;
                   4942: 
                   4943:   return (\@array, $string);
1.168     albertel 4944: }
                   4945: 
1.167     albertel 4946: # -------------------------------------------------------------------Temp Store
                   4947: 
1.168     albertel 4948: sub tmpreset {
                   4949:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4950:   if (!$symb) {
                   4951:     $symb=&symbread();
1.620     albertel 4952:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4953:   }
                   4954:   $symb=escape($symb);
                   4955: 
1.620     albertel 4956:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4957:   $namespace=~s/\//\_/g;
                   4958:   $namespace=~s/\W//g;
                   4959: 
1.620     albertel 4960:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4961:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4962:   if ($domain eq 'public' && $stuname eq 'public') {
                   4963:       $stuname=$ENV{'REMOTE_ADDR'};
                   4964:   }
1.1117    foxr     4965:   my $path=LONCAPA::tempdir();
1.168     albertel 4966:   my %hash;
                   4967:   if (tie(%hash,'GDBM_File',
                   4968: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4969: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4970:     foreach my $key (keys(%hash)) {
1.180     albertel 4971:       if ($key=~ /:$symb/) {
1.168     albertel 4972: 	delete($hash{$key});
                   4973:       }
                   4974:     }
                   4975:   }
                   4976: }
                   4977: 
1.167     albertel 4978: sub tmpstore {
1.168     albertel 4979:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4980: 
                   4981:   if (!$symb) {
                   4982:     $symb=&symbread();
1.620     albertel 4983:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4984:   }
                   4985:   $symb=escape($symb);
                   4986: 
                   4987:   if (!$namespace) {
                   4988:     # I don't think we would ever want to store this for a course.
                   4989:     # it seems this will only be used if we don't have a course.
1.620     albertel 4990:     #$namespace=$env{'request.course.id'};
1.168     albertel 4991:     #if (!$namespace) {
1.620     albertel 4992:       $namespace=$env{'request.state'};
1.168     albertel 4993:     #}
                   4994:   }
                   4995:   $namespace=~s/\//\_/g;
                   4996:   $namespace=~s/\W//g;
1.620     albertel 4997:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4998:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4999:   if ($domain eq 'public' && $stuname eq 'public') {
                   5000:       $stuname=$ENV{'REMOTE_ADDR'};
                   5001:   }
1.168     albertel 5002:   my $now=time;
                   5003:   my %hash;
1.1117    foxr     5004:   my $path=LONCAPA::tempdir();
1.168     albertel 5005:   if (tie(%hash,'GDBM_File',
                   5006: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5007: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5008:     $hash{"version:$symb"}++;
                   5009:     my $version=$hash{"version:$symb"};
                   5010:     my $allkeys=''; 
                   5011:     foreach my $key (keys(%$storehash)) {
                   5012:       $allkeys.=$key.':';
1.591     albertel 5013:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5014:     }
                   5015:     $hash{"$version:$symb:timestamp"}=$now;
                   5016:     $allkeys.='timestamp';
                   5017:     $hash{"$version:keys:$symb"}=$allkeys;
                   5018:     if (untie(%hash)) {
                   5019:       return 'ok';
                   5020:     } else {
                   5021:       return "error:$!";
                   5022:     }
                   5023:   } else {
                   5024:     return "error:$!";
                   5025:   }
                   5026: }
1.167     albertel 5027: 
1.168     albertel 5028: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5029: 
1.168     albertel 5030: sub tmprestore {
                   5031:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5032: 
1.168     albertel 5033:   if (!$symb) {
                   5034:     $symb=&symbread();
1.620     albertel 5035:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5036:   }
                   5037:   $symb=escape($symb);
                   5038: 
1.620     albertel 5039:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5040: 
1.620     albertel 5041:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5042:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5043:   if ($domain eq 'public' && $stuname eq 'public') {
                   5044:       $stuname=$ENV{'REMOTE_ADDR'};
                   5045:   }
1.168     albertel 5046:   my %returnhash;
                   5047:   $namespace=~s/\//\_/g;
                   5048:   $namespace=~s/\W//g;
                   5049:   my %hash;
1.1117    foxr     5050:   my $path=LONCAPA::tempdir();
1.168     albertel 5051:   if (tie(%hash,'GDBM_File',
                   5052: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5053: 	  &GDBM_READER(),0640)) {
1.168     albertel 5054:     my $version=$hash{"version:$symb"};
                   5055:     $returnhash{'version'}=$version;
                   5056:     my $scope;
                   5057:     for ($scope=1;$scope<=$version;$scope++) {
                   5058:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5059:       my @keys=split(/:/,$vkeys);
                   5060:       my $key;
                   5061:       $returnhash{"$scope:keys"}=$vkeys;
                   5062:       foreach $key (@keys) {
1.591     albertel 5063: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5064: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5065:       }
                   5066:     }
1.168     albertel 5067:     if (!(untie(%hash))) {
                   5068:       return "error:$!";
                   5069:     }
                   5070:   } else {
                   5071:     return "error:$!";
                   5072:   }
                   5073:   return %returnhash;
1.167     albertel 5074: }
                   5075: 
1.9       www      5076: # ----------------------------------------------------------------------- Store
                   5077: 
                   5078: sub store {
1.1269    raeburn  5079:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5080:     my $home='';
                   5081: 
1.168     albertel 5082:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5083: 
1.213     www      5084:     $symb=&symbclean($symb);
1.122     albertel 5085:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5086: 
1.620     albertel 5087:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5088:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5089: 
                   5090:     &devalidate($symb,$stuname,$domain);
1.109     www      5091: 
                   5092:     $symb=escape($symb);
1.187     www      5093:     if (!$namespace) { 
1.620     albertel 5094:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5095:           return ''; 
                   5096:        } 
                   5097:     }
1.620     albertel 5098:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5099: 
                   5100:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5101:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5102: 
1.12      www      5103:     my $namevalue='';
1.800     albertel 5104:     foreach my $key (keys(%$storehash)) {
                   5105:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5106:     }
1.12      www      5107:     $namevalue=~s/\&$//;
1.187     www      5108:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5109:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5110: }
                   5111: 
1.47      www      5112: # -------------------------------------------------------------- Critical Store
                   5113: 
                   5114: sub cstore {
1.1269    raeburn  5115:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5116:     my $home='';
                   5117: 
1.168     albertel 5118:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5119: 
1.213     www      5120:     $symb=&symbclean($symb);
1.122     albertel 5121:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5122: 
1.620     albertel 5123:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5124:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5125: 
                   5126:     &devalidate($symb,$stuname,$domain);
1.109     www      5127: 
                   5128:     $symb=escape($symb);
1.187     www      5129:     if (!$namespace) { 
1.620     albertel 5130:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5131:           return ''; 
                   5132:        } 
                   5133:     }
1.620     albertel 5134:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5135: 
                   5136:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5137:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5138: 
1.47      www      5139:     my $namevalue='';
1.800     albertel 5140:     foreach my $key (keys(%$storehash)) {
                   5141:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5142:     }
1.47      www      5143:     $namevalue=~s/\&$//;
1.187     www      5144:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5145:     return critical
1.1269    raeburn  5146:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5147: }
                   5148: 
1.9       www      5149: # --------------------------------------------------------------------- Restore
                   5150: 
                   5151: sub restore {
1.124     www      5152:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5153:     my $home='';
                   5154: 
1.168     albertel 5155:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5156: 
1.122     albertel 5157:     if (!$symb) {
1.1224    raeburn  5158:         return if ($namespace eq 'courserequests');
                   5159:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5160:     } else {
1.1224    raeburn  5161:         unless ($namespace eq 'courserequests') {
                   5162:             $symb=&escape(&symbclean($symb));
                   5163:         }
1.122     albertel 5164:     }
1.188     www      5165:     if (!$namespace) { 
1.620     albertel 5166:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5167:           return ''; 
                   5168:        } 
                   5169:     }
1.620     albertel 5170:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5171:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5172:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5173:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5174: 
1.12      www      5175:     my %returnhash=();
1.800     albertel 5176:     foreach my $line (split(/\&/,$answer)) {
                   5177: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5178:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5179:     }
1.75      www      5180:     my $version;
                   5181:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5182:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5183:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5184:        }
1.75      www      5185:     }
1.13      www      5186:     return %returnhash;
1.34      www      5187: }
                   5188: 
                   5189: # ---------------------------------------------------------- Course Description
1.1118    foxr     5190: #
                   5191: #  
1.34      www      5192: 
                   5193: sub coursedescription {
1.731     albertel 5194:     my ($courseid,$args)=@_;
1.34      www      5195:     $courseid=~s/^\///;
1.49      www      5196:     $courseid=~s/\_/\//g;
1.34      www      5197:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5198:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5199:     my $normalid=$cdomain.'_'.$cnum;
                   5200:     # need to always cache even if we get errors otherwise we keep 
                   5201:     # trying and trying and trying to get the course description.
                   5202:     my %envhash=();
                   5203:     my %returnhash=();
1.731     albertel 5204:     
                   5205:     my $expiretime=600;
                   5206:     if ($env{'request.course.id'} eq $normalid) {
                   5207: 	$expiretime=120;
                   5208:     }
                   5209: 
                   5210:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5211:     if (!$args->{'freshen_cache'}
                   5212: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5213: 	foreach my $key (keys(%env)) {
                   5214: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5215: 	    my ($setting) = $1;
                   5216: 	    $returnhash{$setting} = $env{$key};
                   5217: 	}
                   5218: 	return %returnhash;
                   5219:     }
                   5220: 
1.1118    foxr     5221:     # get the data again
                   5222: 
1.731     albertel 5223:     if (!$args->{'one_time'}) {
                   5224: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5225:     }
1.811     albertel 5226: 
1.34      www      5227:     if ($chome ne 'no_host') {
1.302     albertel 5228:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5229:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5230: 	   my $username = $env{'user.name'}; # Defult username
                   5231: 	   if(defined $args->{'user'}) {
                   5232: 	       $username = $args->{'user'};
                   5233: 	   }
1.129     albertel 5234:            $returnhash{'home'}= $chome;
                   5235: 	   $returnhash{'domain'} = $cdomain;
                   5236: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5237:            if (!defined($returnhash{'type'})) {
                   5238:                $returnhash{'type'} = 'Course';
                   5239:            }
1.130     albertel 5240:            while (my ($name,$value) = each %returnhash) {
1.53      www      5241:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5242:            }
1.270     www      5243:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5244:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5245: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5246:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5247:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5248:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5249:        }
                   5250:     }
1.731     albertel 5251:     if (!$args->{'one_time'}) {
1.949     raeburn  5252: 	&appenv(\%envhash);
1.731     albertel 5253:     }
1.302     albertel 5254:     return %returnhash;
1.461     www      5255: }
                   5256: 
1.1080    raeburn  5257: sub update_released_required {
                   5258:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5259:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5260:         $cid = $env{'request.course.id'};
                   5261:         $cdom = $env{'course.'.$cid.'.domain'};
                   5262:         $cnum = $env{'course.'.$cid.'.num'};
                   5263:         $chome = $env{'course.'.$cid.'.home'};
                   5264:     }
                   5265:     if ($needsrelease) {
                   5266:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5267:         my $needsupdate;
                   5268:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5269:             $needsupdate = 1;
                   5270:         } else {
                   5271:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5272:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5273:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5274:                 $needsupdate = 1;
                   5275:             }
                   5276:         }
                   5277:         if ($needsupdate) {
                   5278:             my %needshash = (
                   5279:                              'internal.releaserequired' => $needsrelease,
                   5280:                             );
                   5281:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5282:             if ($putresult eq 'ok') {
                   5283:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5284:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5285:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5286:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5287:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5288:                 }
                   5289:             }
                   5290:         }
                   5291:     }
                   5292:     return;
                   5293: }
                   5294: 
1.461     www      5295: # -------------------------------------------------See if a user is privileged
                   5296: 
                   5297: sub privileged {
1.1219    raeburn  5298:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5299:     my $now = time;
1.1219    raeburn  5300:     my $roles;
                   5301:     if (ref($possroles) eq 'ARRAY') {
                   5302:         $roles = $possroles; 
                   5303:     } else {
                   5304:         $roles = ['dc','su'];
                   5305:     }
                   5306:     if (ref($possdomains) eq 'ARRAY') {
                   5307:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5308:         foreach my $dom (@{$possdomains}) {
                   5309:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5310:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5311:                 foreach my $role (@{$roles}) {
                   5312:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5313:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5314:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5315:                             return 1 unless (($end && $end < $now) ||
                   5316:                                              ($start && $start > $now));
                   5317:                         }
                   5318:                     }
                   5319:                 }
                   5320:             }
                   5321:         }
                   5322:     } else {
                   5323:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5324:         my $now = time;
1.1170    droeschl 5325: 
1.1275    musolffc 5326:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5327:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5328:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5329:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5330:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5331:             }
1.1219    raeburn  5332:         }
                   5333:     }
                   5334:     return 0;
                   5335: }
1.1170    droeschl 5336: 
1.1219    raeburn  5337: sub privileged_by_domain {
                   5338:     my ($domains,$roles) = @_;
                   5339:     my %privileged = ();
                   5340:     my $cachetime = 60*60*24;
                   5341:     my $now = time;
                   5342:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5343:         return %privileged;
                   5344:     }
                   5345:     foreach my $dom (@{$domains}) {
                   5346:         next if (ref($privileged{$dom}) eq 'HASH');
                   5347:         my $needroles;
                   5348:         foreach my $role (@{$roles}) {
                   5349:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5350:             if (defined($cached)) {
                   5351:                 if (ref($result) eq 'HASH') {
                   5352:                     $privileged{$dom}{$role} = $result;
                   5353:                 }
                   5354:             } else {
                   5355:                 $needroles = 1;
                   5356:             }
                   5357:         }
                   5358:         if ($needroles) {
                   5359:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5360:             $privileged{$dom} = {};
                   5361:             foreach my $server (keys(%dompersonnel)) {
                   5362:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5363:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5364:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5365:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5366:                         next if ($end && $end < $now);
                   5367:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5368:                             $dompersonnel{$server}{$item};
                   5369:                     }
                   5370:                 }
                   5371:             }
                   5372:             if (ref($privileged{$dom}) eq 'HASH') {
                   5373:                 foreach my $role (@{$roles}) {
                   5374:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5375:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5376:                     } else {
                   5377:                         my %hash = ();
                   5378:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5379:                     }
                   5380:                 }
                   5381:             }
                   5382:         }
                   5383:     }
                   5384:     return %privileged;
1.9       www      5385: }
1.1       albertel 5386: 
1.103     harris41 5387: # -------------------------------------------------------- Get user privileges
1.11      www      5388: 
                   5389: sub rolesinit {
1.1169    droeschl 5390:     my ($domain, $username) = @_;
                   5391:     my %userroles = ('user.login.time' => time);
                   5392:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5393: 
                   5394:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5395:     # also, blocking can be triggered by an activating timer
                   5396:     # it's saved in the user's %env.
                   5397:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5398:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5399:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5400:         %timerintchk, %timerintenv);
                   5401: 
1.1162    raeburn  5402:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5403:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5404:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5405:     }
1.1169    droeschl 5406: 
1.1162    raeburn  5407:     foreach my $key (keys(%timerinterval)) {
                   5408:         my ($cid,$rest) = split(/\0/,$key);
                   5409:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5410:     }
1.1169    droeschl 5411: 
1.11      www      5412:     my %allroles=();
1.1162    raeburn  5413:     my %allgroups=();
1.11      www      5414: 
1.1274    raeburn  5415:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5416:         my $role = $rolesdump{$area};
                   5417:         $area =~ s/\_\w\w$//;
                   5418: 
                   5419:         my ($trole, $tend, $tstart, $group_privs);
                   5420: 
                   5421:         if ($role =~ /^cr/) {
                   5422:         # Custom role, defined by a user 
                   5423:         # e.g., user.role.cr/msu/smith/mynewrole
                   5424:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5425:                 $trole = $1;
                   5426:                 ($tend, $tstart) = split('_', $2);
                   5427:             } else {
                   5428:                 $trole = $role;
                   5429:             }
                   5430:         } elsif ($role =~ m|^gr/|) {
                   5431:         # Role of member in a group, defined within a course/community
                   5432:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5433:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5434:             next if $tstart eq '-1';
                   5435:             ($trole, $group_privs) = split(/\//, $trole);
                   5436:             $group_privs = &unescape($group_privs);
                   5437:         } else {
                   5438:         # Just a normal role, defined in roles.tab
                   5439:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5440:         }
                   5441: 
                   5442:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5443:                  $username);
                   5444:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5445: 
                   5446:         # role expired or not available yet?
                   5447:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5448:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5449: 
                   5450:         next if $area eq '' or $trole eq '';
                   5451: 
                   5452:         my $spec = "$trole.$area";
                   5453:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5454: 
                   5455:         if ($trole =~ /^cr\//) {
                   5456:         # Custom role, defined by a user
                   5457:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5458:         } elsif ($trole eq 'gr') {
                   5459:         # Role of a member in a group, defined within a course/community
                   5460:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5461:             next;
                   5462:         } else {
                   5463:         # Normal role, defined in roles.tab
                   5464:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5465:         }
                   5466: 
                   5467:         my $cid = $tdomain.'_'.$trest;
                   5468:         unless ($firstaccchk{$cid}) {
                   5469:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5470:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5471:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5472:                         $coursetimerstarts{$cid}{$item}; 
                   5473:                 }
                   5474:             }
                   5475:             $firstaccchk{$cid} = 1;
                   5476:         }
                   5477:         unless ($timerintchk{$cid}) {
                   5478:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5479:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5480:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5481:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5482:                 }
1.12      www      5483:             }
1.1169    droeschl 5484:             $timerintchk{$cid} = 1;
1.191     harris41 5485:         }
1.11      www      5486:     }
1.1169    droeschl 5487: 
                   5488:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5489:         \%allroles, \%allgroups);
                   5490:     $env{'user.adv'} = $userroles{'user.adv'};
                   5491: 
1.1162    raeburn  5492:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5493: }
                   5494: 
1.567     raeburn  5495: sub set_arearole {
1.1215    raeburn  5496:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5497:     unless ($nolog) {
1.567     raeburn  5498: # log the associated role with the area
1.1215    raeburn  5499:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5500:     }
1.743     albertel 5501:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5502: }
                   5503: 
                   5504: sub custom_roleprivs {
                   5505:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5506:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5507:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5508:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5509:         my ($rdummy,$roledef)=
                   5510:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5511:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5512:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5513:             if (defined($syspriv)) {
1.1043    raeburn  5514:                 if ($trest =~ /^$match_community$/) {
                   5515:                     $syspriv =~ s/bre\&S//; 
                   5516:                 }
1.567     raeburn  5517:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5518:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5519:             }
                   5520:             if ($tdomain ne '') {
                   5521:                 if (defined($dompriv)) {
                   5522:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5523:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5524:                 }
                   5525:                 if (($trest ne '') && (defined($coursepriv))) {
                   5526:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5527:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5528:                 }
                   5529:             }
                   5530:         }
                   5531:     }
                   5532: }
                   5533: 
1.678     raeburn  5534: sub group_roleprivs {
                   5535:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5536:     my $access = 1;
                   5537:     my $now = time;
                   5538:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5539:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5540:     if ($access) {
1.811     albertel 5541:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5542:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5543:     }
                   5544: }
1.567     raeburn  5545: 
                   5546: sub standard_roleprivs {
                   5547:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5548:     if (defined($pr{$trole.':s'})) {
                   5549:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5550:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5551:     }
                   5552:     if ($tdomain ne '') {
                   5553:         if (defined($pr{$trole.':d'})) {
                   5554:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5555:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5556:         }
                   5557:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5558:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5559:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5560:         }
                   5561:     }
                   5562: }
                   5563: 
                   5564: sub set_userprivs {
1.1064    raeburn  5565:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5566:     my $author=0;
                   5567:     my $adv=0;
1.678     raeburn  5568:     my %grouproles = ();
                   5569:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5570:         my @groupkeys; 
1.1000    raeburn  5571:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5572:             push(@groupkeys,$role);
                   5573:         }
                   5574:         if (ref($groups_roles) eq 'HASH') {
                   5575:             foreach my $key (keys(%{$groups_roles})) {
                   5576:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5577:                     push(@groupkeys,$key);
                   5578:                 }
                   5579:             }
                   5580:         }
                   5581:         if (@groupkeys > 0) {
                   5582:             foreach my $role (@groupkeys) {
                   5583:                 my ($trole,$area,$sec,$extendedarea);
                   5584:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5585:                     $trole = $1;
                   5586:                     $area = $2;
                   5587:                     $sec = $3;
                   5588:                     $extendedarea = $area.$sec;
                   5589:                     if (exists($$allgroups{$area})) {
                   5590:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5591:                             my $spec = $trole.'.'.$extendedarea;
                   5592:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5593:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5594:                         }
1.678     raeburn  5595:                     }
                   5596:                 }
                   5597:             }
                   5598:         }
                   5599:     }
1.800     albertel 5600:     foreach my $group (keys(%grouproles)) {
                   5601:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5602:     }
1.800     albertel 5603:     foreach my $role (keys(%{$allroles})) {
                   5604:         my %thesepriv;
1.941     raeburn  5605:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5606:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5607:             if ($item ne '') {
                   5608:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5609:                 if ($restrictions eq '') {
                   5610:                     $thesepriv{$privilege}='F';
                   5611:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5612:                     $thesepriv{$privilege}.=$restrictions;
                   5613:                 }
                   5614:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5615:             }
                   5616:         }
                   5617:         my $thesestr='';
1.1104    raeburn  5618:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5619: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5620: 	}
                   5621:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5622:     }
                   5623:     return ($author,$adv);
                   5624: }
                   5625: 
1.994     raeburn  5626: sub role_status {
1.1104    raeburn  5627:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5628:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5629:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5630:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5631:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5632:             $$where = '/'.$two;
1.994     raeburn  5633:             $$trolecode=$$role.'.'.$$where;
                   5634:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5635:             $$tstatus='is';
1.1104    raeburn  5636:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5637:                 $$tstatus='future';
1.1034    raeburn  5638:                 if ($$tstart<$now) {
                   5639:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5640:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5641:                             my (%allroles,%allgroups,$group_privs,
                   5642:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5643:                             my %userroles = (
                   5644:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5645:                             );
1.1064    raeburn  5646:                             @rolecodes = ('cm'); 
1.1002    raeburn  5647:                             my $spec=$$role.'.'.$$where;
                   5648:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5649:                             if ($$role =~ /^cr\//) {
                   5650:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5651:                                 push(@rolecodes,'cr');
1.1002    raeburn  5652:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5653:                                 push(@rolecodes,$$role);
1.1002    raeburn  5654:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5655:                                                     $env{'user.name'});
1.1064    raeburn  5656:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5657:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5658:                                 $group_privs = &unescape($group_privs);
                   5659:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5660:                                 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  5661:                                 &get_groups_roles($tdomain,$trest,
                   5662:                                                   \%course_roles,\@rolecodes,
                   5663:                                                   \%groups_roles);
1.1002    raeburn  5664:                             } else {
1.1064    raeburn  5665:                                 push(@rolecodes,$$role);
1.1002    raeburn  5666:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5667:                             }
1.1064    raeburn  5668:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5669:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5670:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5671:                         }
                   5672:                     }
1.1034    raeburn  5673:                     $$tstatus = 'is';
1.1002    raeburn  5674:                 }
1.994     raeburn  5675:             }
                   5676:             if ($$tend) {
1.1104    raeburn  5677:                 if ($$tend<$update) {
1.994     raeburn  5678:                     $$tstatus='expired';
                   5679:                 } elsif ($$tend<$now) {
                   5680:                     $$tstatus='will_not';
                   5681:                 }
                   5682:             }
                   5683:         }
                   5684:     }
                   5685: }
                   5686: 
1.1104    raeburn  5687: sub get_groups_roles {
                   5688:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5689:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5690:                   (ref($rolecodes) eq 'ARRAY') && 
                   5691:                   (ref($groups_roles) eq 'HASH')); 
                   5692:     if (keys(%{$cdom_courseroles}) > 0) {
                   5693:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5694:         if ($cdom ne '' && $cnum ne '') {
                   5695:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5696:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5697:                     my $crsrole = $1;
                   5698:                     my $crssec = $2;
                   5699:                     if ($crsrole =~ /^cr/) {
                   5700:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5701:                             push(@{$rolecodes},'cr');
                   5702:                         }
                   5703:                     } else {
                   5704:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5705:                             push(@{$rolecodes},$crsrole);
                   5706:                         }
                   5707:                     }
                   5708:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5709:                     if ($crssec ne '') {
                   5710:                         $rolekey .= "/$crssec";
                   5711:                     }
                   5712:                     $rolekey .= './';
                   5713:                     $groups_roles->{$rolekey} = $rolecodes;
                   5714:                 }
                   5715:             }
                   5716:         }
                   5717:     }
                   5718:     return;
                   5719: }
                   5720: 
                   5721: sub delete_env_groupprivs {
                   5722:     my ($where,$courseroles,$possroles) = @_;
                   5723:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5724:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5725:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5726:         %{$courseroles->{$udom}} =
                   5727:             &get_my_roles('','','userroles',['active'],
                   5728:                           $possroles,[$udom],1);
                   5729:     }
                   5730:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5731:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5732:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5733:             my $area = '/'.$cdom.'/'.$cnum;
                   5734:             my $privkey = "user.priv.$crsrole.$area";
                   5735:             if ($crssec ne '') {
                   5736:                 $privkey .= '/'.$crssec;
                   5737:             }
                   5738:             $privkey .= ".$area/$group";
                   5739:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5740:         }
                   5741:     }
                   5742:     return;
                   5743: }
                   5744: 
1.994     raeburn  5745: sub check_adhoc_privs {
1.1104    raeburn  5746:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5747:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5748:     my $setprivs;
1.994     raeburn  5749:     if ($env{$cckey}) {
                   5750:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5751:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5752:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5753:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5754:             $setprivs = 1;
1.994     raeburn  5755:         }
                   5756:     } else {
1.1088    raeburn  5757:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5758:         $setprivs = 1;
1.994     raeburn  5759:     }
1.1185    raeburn  5760:     return $setprivs;
1.994     raeburn  5761: }
                   5762: 
                   5763: sub set_adhoc_privileges {
                   5764: # role can be cc or ca
1.1088    raeburn  5765:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5766:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5767:     my $spec = $role.'.'.$area;
                   5768:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5769:                                   $env{'user.name'},1);
1.994     raeburn  5770:     my %ccrole = ();
                   5771:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5772:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5773:     &appenv(\%userroles,[$role,'cm']);
                   5774:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5775:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5776:         &appenv( {'request.role'        => $spec,
                   5777:                   'request.role.domain' => $dcdom,
                   5778:                   'request.course.sec'  => ''
                   5779:                  }
                   5780:                );
                   5781:         my $tadv=0;
                   5782:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5783:         &appenv({'request.role.adv'    => $tadv});
                   5784:     }
1.994     raeburn  5785: }
                   5786: 
1.12      www      5787: # --------------------------------------------------------------- get interface
                   5788: 
                   5789: sub get {
1.131     albertel 5790:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5791:    my $items='';
1.800     albertel 5792:    foreach my $item (@$storearr) {
                   5793:        $items.=&escape($item).'&';
1.191     harris41 5794:    }
1.12      www      5795:    $items=~s/\&$//;
1.620     albertel 5796:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5797:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5798:    my $uhome=&homeserver($uname,$udomain);
                   5799: 
1.133     albertel 5800:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5801:    my @pairs=split(/\&/,$rep);
1.273     albertel 5802:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5803:      return @pairs;
                   5804:    }
1.15      www      5805:    my %returnhash=();
1.42      www      5806:    my $i=0;
1.800     albertel 5807:    foreach my $item (@$storearr) {
                   5808:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5809:       $i++;
1.191     harris41 5810:    }
1.15      www      5811:    return %returnhash;
1.27      www      5812: }
                   5813: 
                   5814: # --------------------------------------------------------------- del interface
                   5815: 
                   5816: sub del {
1.133     albertel 5817:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5818:    my $items='';
1.800     albertel 5819:    foreach my $item (@$storearr) {
                   5820:        $items.=&escape($item).'&';
1.191     harris41 5821:    }
1.984     neumanie 5822: 
1.27      www      5823:    $items=~s/\&$//;
1.620     albertel 5824:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5825:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5826:    my $uhome=&homeserver($uname,$udomain);
                   5827:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5828: }
                   5829: 
                   5830: # -------------------------------------------------------------- dump interface
                   5831: 
1.1180    droeschl 5832: sub unserialize {
                   5833:     my ($rep, $escapedkeys) = @_;
                   5834: 
                   5835:     return {} if $rep =~ /^error/;
                   5836: 
                   5837:     my %returnhash=();
1.1252    raeburn  5838: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5839: 	    my ($key, $value) = split(/=/, $item, 2);
                   5840: 	    $key = unescape($key) unless $escapedkeys;
                   5841: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5842: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5843: 	}
                   5844:     #return %returnhash;
                   5845:     return \%returnhash;
                   5846: }        
                   5847: 
                   5848: # see Lond::dump_with_regexp
                   5849: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5850: sub dump {
1.1180    droeschl 5851:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5852:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5853:     if (!$uname) { $uname=$env{'user.name'}; }
                   5854:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5855: 
1.1266    raeburn  5856:     if ($regexp) {
                   5857:         $regexp=&escape($regexp);
                   5858:     } else {
                   5859:         $regexp='.';
                   5860:     }
1.1180    droeschl 5861:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5862:         # user is hosted on this machine
1.1266    raeburn  5863:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5864:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5865:         return %{unserialize($reply, $escapedkeys)};
                   5866:     }
1.1166    raeburn  5867:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5868:     my @pairs=split(/\&/,$rep);
                   5869:     my %returnhash=();
1.1098    foxr     5870:     if (!($rep =~ /^error/ )) {
                   5871: 	foreach my $item (@pairs) {
                   5872: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5873:         $key = unescape($key) unless $escapedkeys;
                   5874:         #$key = &unescape($key);
1.1098    foxr     5875: 	    next if ($key =~ /^error: 2 /);
                   5876: 	    $returnhash{$key}=&thaw_unescape($value);
                   5877: 	}
1.755     albertel 5878:     }
                   5879:     return %returnhash;
1.407     www      5880: }
                   5881: 
1.1098    foxr     5882: 
1.717     albertel 5883: # --------------------------------------------------------- dumpstore interface
                   5884: 
                   5885: sub dumpstore {
                   5886:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5887:    # same as dump but keys must be escaped. They may contain colon separated
                   5888:    # lists of values that may themself contain colons (e.g. symbs).
                   5889:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5890: }
                   5891: 
1.407     www      5892: # -------------------------------------------------------------- keys interface
                   5893: 
                   5894: sub getkeys {
                   5895:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5896:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5897:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5898:    my $uhome=&homeserver($uname,$udomain);
                   5899:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5900:    my @keyarray=();
1.800     albertel 5901:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5902:       next if ($key =~ /^error: 2 /);
1.800     albertel 5903:       push(@keyarray,&unescape($key));
1.407     www      5904:    }
                   5905:    return @keyarray;
1.318     matthew  5906: }
                   5907: 
1.319     matthew  5908: # --------------------------------------------------------------- currentdump
                   5909: sub currentdump {
1.328     matthew  5910:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5911:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5912:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5913:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5914:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5915:    my $rep;
                   5916: 
                   5917:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5918:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5919:                    $courseid)));
                   5920:    } else {
                   5921:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5922:    }
                   5923: 
1.318     matthew  5924:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5925:    #
1.318     matthew  5926:    my %returnhash=();
1.319     matthew  5927:    #
                   5928:    if ($rep eq "unknown_cmd") { 
                   5929:        # an old lond will not know currentdump
                   5930:        # Do a dump and make it look like a currentdump
1.822     albertel 5931:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5932:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5933:        my %hash = @tmp;
                   5934:        @tmp=();
1.424     matthew  5935:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5936:    } else {
                   5937:        my @pairs=split(/\&/,$rep);
1.800     albertel 5938:        foreach my $pair (@pairs) {
                   5939:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5940:            my ($symb,$param) = split(/:/,$key);
                   5941:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5942:                                                         &thaw_unescape($value);
1.319     matthew  5943:        }
1.191     harris41 5944:    }
1.12      www      5945:    return %returnhash;
1.424     matthew  5946: }
                   5947: 
                   5948: sub convert_dump_to_currentdump{
                   5949:     my %hash = %{shift()};
                   5950:     my %returnhash;
                   5951:     # Code ripped from lond, essentially.  The only difference
                   5952:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5953:     # we might run in to problems with parameter names =~ /^v\./
                   5954:     while (my ($key,$value) = each(%hash)) {
                   5955:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5956: 	$symb  = &unescape($symb);
                   5957: 	$param = &unescape($param);
1.424     matthew  5958:         next if ($v eq 'version' || $symb eq 'keys');
                   5959:         next if (exists($returnhash{$symb}) &&
                   5960:                  exists($returnhash{$symb}->{$param}) &&
                   5961:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5962:         $returnhash{$symb}->{$param}=$value;
                   5963:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5964:     }
                   5965:     #
                   5966:     # Remove all of the keys in the hashes which keep track of
                   5967:     # the version of the parameter.
                   5968:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5969:         # use a foreach because we are going to delete from the hash.
                   5970:         foreach my $key (keys(%$param_hash)) {
                   5971:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5972:         }
                   5973:     }
                   5974:     return \%returnhash;
1.12      www      5975: }
                   5976: 
1.627     albertel 5977: # ------------------------------------------------------ critical inc interface
                   5978: 
                   5979: sub cinc {
                   5980:     return &inc(@_,'critical');
                   5981: }
                   5982: 
1.449     matthew  5983: # --------------------------------------------------------------- inc interface
                   5984: 
                   5985: sub inc {
1.627     albertel 5986:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5987:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5988:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5989:     my $uhome=&homeserver($uname,$udomain);
                   5990:     my $items='';
                   5991:     if (! ref($store)) {
                   5992:         # got a single value, so use that instead
                   5993:         $items = &escape($store).'=&';
                   5994:     } elsif (ref($store) eq 'SCALAR') {
                   5995:         $items = &escape($$store).'=&';        
                   5996:     } elsif (ref($store) eq 'ARRAY') {
                   5997:         $items = join('=&',map {&escape($_);} @{$store});
                   5998:     } elsif (ref($store) eq 'HASH') {
                   5999:         while (my($key,$value) = each(%{$store})) {
                   6000:             $items.= &escape($key).'='.&escape($value).'&';
                   6001:         }
                   6002:     }
                   6003:     $items=~s/\&$//;
1.627     albertel 6004:     if ($critical) {
                   6005: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6006:     } else {
                   6007: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6008:     }
1.449     matthew  6009: }
                   6010: 
1.12      www      6011: # --------------------------------------------------------------- put interface
                   6012: 
                   6013: sub put {
1.134     albertel 6014:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6015:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6016:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6017:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6018:    my $items='';
1.800     albertel 6019:    foreach my $item (keys(%$storehash)) {
                   6020:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6021:    }
1.12      www      6022:    $items=~s/\&$//;
1.134     albertel 6023:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6024: }
                   6025: 
1.631     albertel 6026: # ------------------------------------------------------------ newput interface
                   6027: 
                   6028: sub newput {
                   6029:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6030:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6031:    if (!$uname) { $uname=$env{'user.name'}; }
                   6032:    my $uhome=&homeserver($uname,$udomain);
                   6033:    my $items='';
                   6034:    foreach my $key (keys(%$storehash)) {
                   6035:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6036:    }
                   6037:    $items=~s/\&$//;
                   6038:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6039: }
                   6040: 
                   6041: # ---------------------------------------------------------  putstore interface
                   6042: 
1.524     raeburn  6043: sub putstore {
1.1269    raeburn  6044:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6045:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6046:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6047:    my $uhome=&homeserver($uname,$udomain);
                   6048:    my $items='';
1.715     albertel 6049:    foreach my $key (keys(%$storehash)) {
                   6050:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6051:    }
1.715     albertel 6052:    $items=~s/\&$//;
1.716     albertel 6053:    my $esc_symb=&escape($symb);
                   6054:    my $esc_v=&escape($version);
1.715     albertel 6055:    my $reply =
1.716     albertel 6056:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6057: 	      $uhome);
1.1269    raeburn  6058:    if (($tolog) && ($reply eq 'ok')) {
                   6059:        my $namevalue='';
                   6060:        foreach my $key (keys(%{$storehash})) {
                   6061:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6062:        }
                   6063:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6064:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6065:                      '&version='.$esc_v.
                   6066:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6067:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6068:    }
1.715     albertel 6069:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6070:        # gfall back to way things use to be done
1.715     albertel 6071:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6072: 			    $uname);
1.524     raeburn  6073:    }
1.715     albertel 6074:    return $reply;
                   6075: }
                   6076: 
                   6077: sub old_putstore {
1.716     albertel 6078:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6079:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6080:     if (!$uname) { $uname=$env{'user.name'}; }
                   6081:     my $uhome=&homeserver($uname,$udomain);
                   6082:     my %newstorehash;
1.800     albertel 6083:     foreach my $item (keys(%$storehash)) {
                   6084: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6085: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6086:     }
                   6087:     my $items='';
                   6088:     my %allitems = ();
1.800     albertel 6089:     foreach my $item (keys(%newstorehash)) {
                   6090: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6091: 	    my $key = $1.':keys:'.$2;
                   6092: 	    $allitems{$key} .= $3.':';
                   6093: 	}
1.800     albertel 6094: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6095:     }
1.800     albertel 6096:     foreach my $item (keys(%allitems)) {
                   6097: 	$allitems{$item} =~ s/\:$//;
                   6098: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6099:     }
                   6100:     $items=~s/\&$//;
                   6101:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6102: }
                   6103: 
1.47      www      6104: # ------------------------------------------------------ critical put interface
                   6105: 
                   6106: sub cput {
1.134     albertel 6107:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6108:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6109:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6110:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6111:    my $items='';
1.800     albertel 6112:    foreach my $item (keys(%$storehash)) {
                   6113:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6114:    }
1.47      www      6115:    $items=~s/\&$//;
1.134     albertel 6116:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6117: }
                   6118: 
                   6119: # -------------------------------------------------------------- eget interface
                   6120: 
                   6121: sub eget {
1.133     albertel 6122:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6123:    my $items='';
1.800     albertel 6124:    foreach my $item (@$storearr) {
                   6125:        $items.=&escape($item).'&';
1.191     harris41 6126:    }
1.12      www      6127:    $items=~s/\&$//;
1.620     albertel 6128:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6129:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6130:    my $uhome=&homeserver($uname,$udomain);
                   6131:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6132:    my @pairs=split(/\&/,$rep);
                   6133:    my %returnhash=();
1.42      www      6134:    my $i=0;
1.800     albertel 6135:    foreach my $item (@$storearr) {
                   6136:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6137:       $i++;
1.191     harris41 6138:    }
1.12      www      6139:    return %returnhash;
                   6140: }
                   6141: 
1.667     albertel 6142: # ------------------------------------------------------------ tmpput interface
                   6143: sub tmpput {
1.802     raeburn  6144:     my ($storehash,$server,$context)=@_;
1.667     albertel 6145:     my $items='';
1.800     albertel 6146:     foreach my $item (keys(%$storehash)) {
                   6147: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6148:     }
                   6149:     $items=~s/\&$//;
1.802     raeburn  6150:     if (defined($context)) {
                   6151:         $items .= ':'.&escape($context);
                   6152:     }
1.667     albertel 6153:     return &reply("tmpput:$items",$server);
                   6154: }
                   6155: 
                   6156: # ------------------------------------------------------------ tmpget interface
                   6157: sub tmpget {
1.688     albertel 6158:     my ($token,$server)=@_;
                   6159:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6160:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6161:     my %returnhash;
                   6162:     foreach my $item (split(/\&/,$rep)) {
                   6163: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6164:         next if ($key =~ /^error: 2 /);
1.667     albertel 6165: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6166:     }
                   6167:     return %returnhash;
                   6168: }
                   6169: 
1.1113    raeburn  6170: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6171: sub tmpdel {
                   6172:     my ($token,$server)=@_;
                   6173:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6174:     return &reply("tmpdel:$token",$server);
                   6175: }
                   6176: 
1.1198    raeburn  6177: # ------------------------------------------------------------ get_timebased_id 
                   6178: 
                   6179: sub get_timebased_id {
                   6180:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6181:         $maxtries) = @_;
                   6182:     my ($newid,$error,$dellock);
                   6183:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6184:         return ('','ok','invalid call to get suffix');
                   6185:     }
                   6186: 
                   6187: # set defaults for any optional args for which values were not supplied
                   6188:     if ($who eq '') {
                   6189:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6190:     }
                   6191:     if (!$locktries) {
                   6192:         $locktries = 3;
                   6193:     }
                   6194:     if (!$maxtries) {
                   6195:         $maxtries = 10;
                   6196:     }
                   6197:     
                   6198:     if (($cdom eq '') || ($cnum eq '')) {
                   6199:         if ($env{'request.course.id'}) {
                   6200:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6201:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6202:         }
                   6203:         if (($cdom eq '') || ($cnum eq '')) {
                   6204:             return ('','ok','call to get suffix not in course context');
                   6205:         }
                   6206:     }
                   6207: 
                   6208: # construct locking item
                   6209:     my $lockhash = {
                   6210:                       $prefix."\0".'locked_'.$keyid => $who,
                   6211:                    };
                   6212:     my $tries = 0;
                   6213: 
                   6214: # attempt to get lock on nohist_$namespace file
                   6215:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6216:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6217:         $tries ++;
                   6218:         sleep 1;
                   6219:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6220:     }
                   6221: 
                   6222: # attempt to get unique identifier, based on current timestamp
                   6223:     if ($gotlock eq 'ok') {
                   6224:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6225:         my $id = time;
                   6226:         $newid = $id;
1.1268    raeburn  6227:         if ($idtype eq 'addcode') {
                   6228:             $newid .= &sixnum_code();
                   6229:         }
1.1198    raeburn  6230:         my $idtries = 0;
                   6231:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6232:             if ($idtype eq 'concat') {
                   6233:                 $newid = $id.$idtries;
1.1268    raeburn  6234:             } elsif ($idtype eq 'addcode') {
                   6235:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6236:             } else {
                   6237:                 $newid ++;
                   6238:             }
                   6239:             $idtries ++;
                   6240:         }
                   6241:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6242:             my %new_item =  (
                   6243:                               $prefix."\0".$newid => $who,
                   6244:                             );
                   6245:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6246:                                                  $cdom,$cnum);
                   6247:             if ($putresult ne 'ok') {
                   6248:                 undef($newid);
                   6249:                 $error = 'error saving new item: '.$putresult;
                   6250:             }
                   6251:         } else {
1.1268    raeburn  6252:              undef($newid);
1.1198    raeburn  6253:              $error = ('error: no unique suffix available for the new item ');
                   6254:         }
                   6255: #  remove lock
                   6256:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6257:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6258:     } else {
                   6259:         $error = "error: could not obtain lockfile\n";
                   6260:         $dellock = 'ok';
1.1276    raeburn  6261:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6262:             $dellock = 'nolock';
                   6263:         }
1.1198    raeburn  6264:     }
                   6265:     return ($newid,$dellock,$error);
                   6266: }
                   6267: 
1.1268    raeburn  6268: sub sixnum_code {
                   6269:     my $code;
                   6270:     for (0..6) {
                   6271:         $code .= int( rand(9) );
                   6272:     }
                   6273:     return $code;
                   6274: }
                   6275: 
1.765     albertel 6276: # -------------------------------------------------- portfolio access checking
                   6277: 
                   6278: sub portfolio_access {
1.1270    raeburn  6279:     my ($requrl,$clientip) = @_;
1.765     albertel 6280:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6281:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6282:     if ($result) {
                   6283:         my %setters;
                   6284:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6285:             my ($startblock,$endblock) =
                   6286:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6287:             if ($startblock && $endblock) {
                   6288:                 return 'B';
                   6289:             }
                   6290:         } else {
                   6291:             my ($startblock,$endblock) =
                   6292:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6293:             if ($startblock && $endblock) {
                   6294:                 return 'B';
                   6295:             }
                   6296:         }
                   6297:     }
1.765     albertel 6298:     if ($result eq 'ok') {
1.766     albertel 6299:        return 'F';
1.765     albertel 6300:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6301:        return 'A';
1.765     albertel 6302:     }
1.766     albertel 6303:     return '';
1.765     albertel 6304: }
                   6305: 
                   6306: sub get_portfolio_access {
1.1270    raeburn  6307:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6308: 
                   6309:     if (!ref($access_hash)) {
                   6310: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6311: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6312: 						   $file_name);
                   6313: 	$access_hash = $access_controls{$file_name};
                   6314:     }
                   6315: 
1.1270    raeburn  6316:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6317:     my $now = time;
                   6318:     if (ref($access_hash) eq 'HASH') {
                   6319:         foreach my $key (keys(%{$access_hash})) {
                   6320:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6321:             if ($start > $now) {
                   6322:                 next;
                   6323:             }
                   6324:             if ($end && $end<$now) {
                   6325:                 next;
                   6326:             }
                   6327:             if ($scope eq 'public') {
                   6328:                 $public = $key;
                   6329:                 last;
                   6330:             } elsif ($scope eq 'guest') {
                   6331:                 $guest = $key;
                   6332:             } elsif ($scope eq 'domains') {
                   6333:                 push(@domains,$key);
                   6334:             } elsif ($scope eq 'users') {
                   6335:                 push(@users,$key);
                   6336:             } elsif ($scope eq 'course') {
                   6337:                 push(@courses,$key);
                   6338:             } elsif ($scope eq 'group') {
                   6339:                 push(@groups,$key);
1.1270    raeburn  6340:             } elsif ($scope eq 'ip') {
                   6341:                 push(@ips,$key);
1.765     albertel 6342:             }
                   6343:         }
                   6344:         if ($public) {
                   6345:             return 'ok';
1.1270    raeburn  6346:         } elsif (@ips > 0) {
                   6347:             my $allowed;
                   6348:             foreach my $ipkey (@ips) {
                   6349:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6350:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6351:                         $allowed = 1;
                   6352:                         last; 
                   6353:                     }
                   6354:                 }
                   6355:             }
                   6356:             if ($allowed) {
                   6357:                 return 'ok';
                   6358:             }
1.765     albertel 6359:         }
                   6360:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6361:             if ($guest) {
                   6362:                 return $guest;
                   6363:             }
                   6364:         } else {
                   6365:             if (@domains > 0) {
                   6366:                 foreach my $domkey (@domains) {
                   6367:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6368:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6369:                             return 'ok';
                   6370:                         }
                   6371:                     }
                   6372:                 }
                   6373:             }
                   6374:             if (@users > 0) {
                   6375:                 foreach my $userkey (@users) {
1.865     raeburn  6376:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6377:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6378:                             if (ref($item) eq 'HASH') {
                   6379:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6380:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6381:                                     return 'ok';
                   6382:                                 }
                   6383:                             }
                   6384:                         }
                   6385:                     } 
1.765     albertel 6386:                 }
                   6387:             }
                   6388:             my %roleshash;
                   6389:             my @courses_and_groups = @courses;
                   6390:             push(@courses_and_groups,@groups); 
                   6391:             if (@courses_and_groups > 0) {
                   6392:                 my (%allgroups,%allroles); 
                   6393:                 my ($start,$end,$role,$sec,$group);
                   6394:                 foreach my $envkey (%env) {
1.1060    raeburn  6395:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6396:                         my $cid = $2.'_'.$3; 
                   6397:                         if ($1 eq 'gr') {
                   6398:                             $group = $4;
                   6399:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6400:                         } else {
                   6401:                             if ($4 eq '') {
                   6402:                                 $sec = 'none';
                   6403:                             } else {
                   6404:                                 $sec = $4;
                   6405:                             }
                   6406:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6407:                         }
1.811     albertel 6408:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6409:                         my $cid = $2.'_'.$3;
                   6410:                         if ($4 eq '') {
                   6411:                             $sec = 'none';
                   6412:                         } else {
                   6413:                             $sec = $4;
                   6414:                         }
                   6415:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6416:                     }
                   6417:                 }
                   6418:                 if (keys(%allroles) == 0) {
                   6419:                     return;
                   6420:                 }
                   6421:                 foreach my $key (@courses_and_groups) {
                   6422:                     my %content = %{$$access_hash{$key}};
                   6423:                     my $cnum = $content{'number'};
                   6424:                     my $cdom = $content{'domain'};
                   6425:                     my $cid = $cdom.'_'.$cnum;
                   6426:                     if (!exists($allroles{$cid})) {
                   6427:                         next;
                   6428:                     }    
                   6429:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6430:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6431:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6432:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6433:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6434:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6435:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6436:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6437:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6438:                                         if (grep/^all$/,@sections) {
                   6439:                                             return 'ok';
                   6440:                                         } else {
                   6441:                                             if (grep/^$sec$/,@sections) {
                   6442:                                                 return 'ok';
                   6443:                                             }
                   6444:                                         }
                   6445:                                     }
                   6446:                                 }
                   6447:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6448:                                     if (grep/^none$/,@groups) {
                   6449:                                         return 'ok';
                   6450:                                     }
                   6451:                                 } else {
                   6452:                                     if (grep/^all$/,@groups) {
                   6453:                                         return 'ok';
                   6454:                                     } 
                   6455:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6456:                                         if (grep/^$group$/,@groups) {
                   6457:                                             return 'ok';
                   6458:                                         }
                   6459:                                     }
                   6460:                                 } 
                   6461:                             }
                   6462:                         }
                   6463:                     }
                   6464:                 }
                   6465:             }
                   6466:             if ($guest) {
                   6467:                 return $guest;
                   6468:             }
                   6469:         }
                   6470:     }
                   6471:     return;
                   6472: }
                   6473: 
                   6474: sub course_group_datechecker {
                   6475:     my ($dates,$now,$status) = @_;
                   6476:     my ($start,$end) = split(/\./,$dates);
                   6477:     if (!$start && !$end) {
                   6478:         return 'ok';
                   6479:     }
                   6480:     if (grep/^active$/,@{$status}) {
                   6481:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6482:             return 'ok';
                   6483:         }
                   6484:     }
                   6485:     if (grep/^previous$/,@{$status}) {
                   6486:         if ($end > $now ) {
                   6487:             return 'ok';
                   6488:         }
                   6489:     }
                   6490:     if (grep/^future$/,@{$status}) {
                   6491:         if ($start > $now) {
                   6492:             return 'ok';
                   6493:         }
                   6494:     }
                   6495:     return; 
                   6496: }
                   6497: 
                   6498: sub parse_portfolio_url {
                   6499:     my ($url) = @_;
                   6500: 
                   6501:     my ($type,$udom,$unum,$group,$file_name);
                   6502:     
1.823     albertel 6503:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6504: 	$type = 1;
                   6505:         $udom = $1;
                   6506:         $unum = $2;
                   6507:         $file_name = $3;
1.823     albertel 6508:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6509: 	$type = 2;
                   6510:         $udom = $1;
                   6511:         $unum = $2;
                   6512:         $group = $3;
                   6513:         $file_name = $3.'/'.$4;
                   6514:     }
                   6515:     if (wantarray) {
                   6516: 	return ($type,$udom,$unum,$file_name,$group);
                   6517:     }
                   6518:     return $type;
                   6519: }
                   6520: 
                   6521: sub is_portfolio_url {
                   6522:     my ($url) = @_;
                   6523:     return scalar(&parse_portfolio_url($url));
                   6524: }
                   6525: 
1.798     raeburn  6526: sub is_portfolio_file {
                   6527:     my ($file) = @_;
1.820     raeburn  6528:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6529:         return 1;
                   6530:     }
                   6531:     return;
                   6532: }
                   6533: 
1.976     raeburn  6534: sub usertools_access {
1.1084    raeburn  6535:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6536:     my ($access,%tools);
                   6537:     if ($context eq '') {
                   6538:         $context = 'tools';
                   6539:     }
                   6540:     if ($context eq 'requestcourses') {
                   6541:         %tools = (
                   6542:                       official   => 1,
                   6543:                       unofficial => 1,
1.1006    raeburn  6544:                       community  => 1,
1.1246    raeburn  6545:                       textbook   => 1,
1.1305    raeburn  6546:                       placement  => 1,
1.985     raeburn  6547:                  );
1.1183    raeburn  6548:     } elsif ($context eq 'requestauthor') {
                   6549:         %tools = (
                   6550:                       requestauthor => 1,
                   6551:                  );
1.985     raeburn  6552:     } else {
                   6553:         %tools = (
                   6554:                       aboutme   => 1,
                   6555:                       blog      => 1,
1.1177    raeburn  6556:                       webdav    => 1,
1.985     raeburn  6557:                       portfolio => 1,
                   6558:                  );
                   6559:     }
1.976     raeburn  6560:     return if (!defined($tools{$tool}));
                   6561: 
1.1242    raeburn  6562:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6563:         $udom = $env{'user.domain'};
                   6564:         $uname = $env{'user.name'};
                   6565:     }
                   6566: 
1.978     raeburn  6567:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6568:         if ($action ne 'reload') {
1.985     raeburn  6569:             if ($context eq 'requestcourses') {
                   6570:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6571:             } elsif ($context eq 'requestauthor') {
                   6572:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6573:             } else {
                   6574:                 return $env{'environment.availabletools.'.$tool};
                   6575:             }
                   6576:         }
1.976     raeburn  6577:     }
                   6578: 
1.1183    raeburn  6579:     my ($toolstatus,$inststatus,$envkey);
                   6580:     if ($context eq 'requestauthor') {
                   6581:         $envkey = $context; 
                   6582:     } else {
                   6583:         $envkey = $context.'.'.$tool;
                   6584:     }
1.976     raeburn  6585: 
1.985     raeburn  6586:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6587:          ($action ne 'reload')) {
1.1183    raeburn  6588:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6589:         $inststatus = $env{'environment.inststatus'};
                   6590:     } else {
1.1084    raeburn  6591:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6592:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6593:             $inststatus = $userenvref->{'inststatus'};
                   6594:         } else {
1.1183    raeburn  6595:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6596:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6597:             $inststatus = $userenv{'inststatus'};
                   6598:         }
1.976     raeburn  6599:     }
                   6600: 
                   6601:     if ($toolstatus ne '') {
                   6602:         if ($toolstatus) {
                   6603:             $access = 1;
                   6604:         } else {
                   6605:             $access = 0;
                   6606:         }
                   6607:         return $access;
                   6608:     }
                   6609: 
1.1084    raeburn  6610:     my ($is_adv,%domdef);
                   6611:     if (ref($is_advref) eq 'HASH') {
                   6612:         $is_adv = $is_advref->{'is_adv'};
                   6613:     } else {
                   6614:         $is_adv = &is_advanced_user($udom,$uname);
                   6615:     }
                   6616:     if (ref($domdefref) eq 'HASH') {
                   6617:         %domdef = %{$domdefref};
                   6618:     } else {
                   6619:         %domdef = &get_domain_defaults($udom);
                   6620:     }
1.976     raeburn  6621:     if (ref($domdef{$tool}) eq 'HASH') {
                   6622:         if ($is_adv) {
                   6623:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6624:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6625:                     $access = 1;
                   6626:                 } else {
                   6627:                     $access = 0;
                   6628:                 }
                   6629:                 return $access;
                   6630:             }
                   6631:         }
                   6632:         if ($inststatus ne '') {
                   6633:             my ($hasaccess,$hasnoaccess);
                   6634:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6635:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6636:                     if ($domdef{$tool}{$affiliation}) {
                   6637:                         $hasaccess = 1;
                   6638:                     } else {
                   6639:                         $hasnoaccess = 1;
                   6640:                     }
                   6641:                 }
                   6642:             }
                   6643:             if ($hasaccess || $hasnoaccess) {
                   6644:                 if ($hasaccess) {
                   6645:                     $access = 1;
                   6646:                 } elsif ($hasnoaccess) {
                   6647:                     $access = 0; 
                   6648:                 }
                   6649:                 return $access;
                   6650:             }
                   6651:         } else {
                   6652:             if ($domdef{$tool}{'default'} ne '') {
                   6653:                 if ($domdef{$tool}{'default'}) {
                   6654:                     $access = 1;
                   6655:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6656:                     $access = 0;
                   6657:                 }
                   6658:                 return $access;
                   6659:             }
                   6660:         }
                   6661:     } else {
1.1177    raeburn  6662:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6663:             $access = 1;
                   6664:         } else {
                   6665:             $access = 0;
                   6666:         }
1.976     raeburn  6667:         return $access;
                   6668:     }
                   6669: }
                   6670: 
1.1050    raeburn  6671: sub is_course_owner {
                   6672:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6673:     if (($udom eq '') || ($uname eq '')) {
                   6674:         $udom = $env{'user.domain'};
                   6675:         $uname = $env{'user.name'};
                   6676:     }
                   6677:     unless (($udom eq '') || ($uname eq '')) {
                   6678:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6679:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6680:                 return 1;
                   6681:             } else {
                   6682:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6683:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6684:                     return 1;
                   6685:                 }
                   6686:             }
                   6687:         }
                   6688:     }
                   6689:     return;
                   6690: }
                   6691: 
1.976     raeburn  6692: sub is_advanced_user {
                   6693:     my ($udom,$uname) = @_;
1.1085    raeburn  6694:     if ($udom ne '' && $uname ne '') {
                   6695:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6696:             if (wantarray) {
                   6697:                 return ($env{'user.adv'},$env{'user.author'});
                   6698:             } else {
                   6699:                 return $env{'user.adv'};
                   6700:             }
1.1085    raeburn  6701:         }
                   6702:     }
1.976     raeburn  6703:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6704:     my %allroles;
1.1128    raeburn  6705:     my ($is_adv,$is_author);
1.976     raeburn  6706:     foreach my $role (keys(%roleshash)) {
                   6707:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6708:         my $area = '/'.$tdomain.'/'.$trest;
                   6709:         if ($sec ne '') {
                   6710:             $area .= '/'.$sec;
                   6711:         }
                   6712:         if (($area ne '') && ($trole ne '')) {
                   6713:             my $spec=$trole.'.'.$area;
                   6714:             if ($trole =~ /^cr\//) {
                   6715:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6716:             } elsif ($trole ne 'gr') {
                   6717:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6718:             }
1.1128    raeburn  6719:             if ($trole eq 'au') {
                   6720:                 $is_author = 1;
                   6721:             }
1.976     raeburn  6722:         }
                   6723:     }
                   6724:     foreach my $role (keys(%allroles)) {
                   6725:         last if ($is_adv);
                   6726:         foreach my $item (split(/:/,$allroles{$role})) {
                   6727:             if ($item ne '') {
                   6728:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6729:                 if ($privilege eq 'adv') {
                   6730:                     $is_adv = 1;
                   6731:                     last;
                   6732:                 }
                   6733:             }
                   6734:         }
                   6735:     }
1.1128    raeburn  6736:     if (wantarray) {
                   6737:         return ($is_adv,$is_author);
                   6738:     }
1.976     raeburn  6739:     return $is_adv;
                   6740: }
1.798     raeburn  6741: 
1.1035    raeburn  6742: sub check_can_request {
1.1036    raeburn  6743:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6744:     my $canreq = 0;
                   6745:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6746:     my @options = ('approval','validate','autolimit');
                   6747:     my $optregex = join('|',@options);
                   6748:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6749:         foreach my $type (@{$types}) {
                   6750:             if (&usertools_access($env{'user.name'},
                   6751:                                   $env{'user.domain'},
                   6752:                                   $type,undef,'requestcourses')) {
                   6753:                 $canreq ++;
1.1036    raeburn  6754:                 if (ref($request_domains) eq 'HASH') {
                   6755:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6756:                 }
1.1035    raeburn  6757:                 if ($dom eq $env{'user.domain'}) {
                   6758:                     $can_request->{$type} = 1;
                   6759:                 }
                   6760:             }
                   6761:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6762:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6763:                 if (@curr > 0) {
1.1036    raeburn  6764:                     foreach my $item (@curr) {
                   6765:                         if (ref($request_domains) eq 'HASH') {
                   6766:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6767:                             if ($otherdom ne '') {
                   6768:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6769:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6770:                                         push(@{$request_domains->{$type}},$otherdom);
                   6771:                                     }
                   6772:                                 } else {
                   6773:                                     push(@{$request_domains->{$type}},$otherdom);
                   6774:                                 }
                   6775:                             }
                   6776:                         }
                   6777:                     }
                   6778:                     unless($dom eq $env{'user.domain'}) {
                   6779:                         $canreq ++;
1.1035    raeburn  6780:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6781:                             $can_request->{$type} = 1;
                   6782:                         }
                   6783:                     }
                   6784:                 }
                   6785:             }
                   6786:         }
                   6787:     }
                   6788:     return $canreq;
                   6789: }
                   6790: 
1.341     www      6791: # ---------------------------------------------- Custom access rule evaluation
                   6792: 
                   6793: sub customaccess {
                   6794:     my ($priv,$uri)=@_;
1.807     albertel 6795:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6796:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6797:     $udom = &LONCAPA::clean_domain($udom);
                   6798:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6799:     my $access=0;
1.800     albertel 6800:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6801: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6802: 	if ($type eq 'user') {
                   6803: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6804: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6805: 		if ($tdom) {
                   6806: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6807: 		}
1.896     albertel 6808: 		if ($tuname) {
                   6809: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6810: 		}
                   6811: 		$access=($effect eq 'allow');
                   6812: 		last;
                   6813: 	    }
                   6814: 	} else {
                   6815: 	    if ($role) {
                   6816: 		if ($role ne $urole) { next; }
                   6817: 	    }
                   6818: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6819: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6820: 		if ($tdom) {
                   6821: 		    if ($tdom ne $udom) { next; }
                   6822: 		}
                   6823: 		if ($tcrs) {
                   6824: 		    if ($tcrs ne $ucrs) { next; }
                   6825: 		}
                   6826: 		if ($tsec) {
                   6827: 		    if ($tsec ne $usec) { next; }
                   6828: 		}
                   6829: 		$access=($effect eq 'allow');
                   6830: 		last;
                   6831: 	    }
                   6832: 	    if ($realm eq '' && $role eq '') {
                   6833: 		$access=($effect eq 'allow');
                   6834: 	    }
1.402     bowersj2 6835: 	}
1.341     www      6836:     }
                   6837:     return $access;
                   6838: }
                   6839: 
1.103     harris41 6840: # ------------------------------------------------- Check for a user privilege
1.12      www      6841: 
                   6842: sub allowed {
1.1281    raeburn  6843:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6844:     my $ver_orguri=$uri;
1.439     www      6845:     $uri=&deversion($uri);
1.152     www      6846:     my $orguri=$uri;
1.52      www      6847:     $uri=&declutter($uri);
1.809     raeburn  6848: 
1.810     raeburn  6849:     if ($priv eq 'evb') {
                   6850: # Evade communication block restrictions for specified role in a course
                   6851:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6852:             return $1;
                   6853:         } else {
                   6854:             return;
                   6855:         }
                   6856:     }
                   6857: 
1.620     albertel 6858:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6859: # Free bre access to adm and meta resources
1.775     albertel 6860:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6861: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6862: 	&& ($priv eq 'bre')) {
1.14      www      6863: 	return 'F';
1.159     www      6864:     }
                   6865: 
1.545     banghart 6866: # Free bre access to user's own portfolio contents
1.714     raeburn  6867:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6868:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6869: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6870:         my %setters;
                   6871:         my ($startblock,$endblock) = 
                   6872:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6873:         if ($startblock && $endblock) {
                   6874:             return 'B';
                   6875:         } else {
                   6876:             return 'F';
                   6877:         }
1.545     banghart 6878:     }
                   6879: 
1.762     raeburn  6880: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6881:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6882:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6883:         if (exists($env{'request.course.id'})) {
                   6884:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6885:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6886:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6887:                 my $courseprivid=$env{'request.course.id'};
                   6888:                 $courseprivid=~s/\_/\//;
                   6889:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6890:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6891:                     return $1; 
1.762     raeburn  6892:                 } else {
                   6893:                     if ($env{'request.course.sec'}) {
                   6894:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6895:                     }
                   6896:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6897:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6898:                         return $2;
                   6899:                     }
1.714     raeburn  6900:                 }
                   6901:             }
                   6902:         }
                   6903:     }
                   6904: 
1.159     www      6905: # Free bre to public access
                   6906: 
                   6907:     if ($priv eq 'bre') {
1.238     www      6908:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6909: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6910:            return 'F'; 
                   6911:         }
1.238     www      6912:         if ($copyright eq 'priv') {
                   6913:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6914: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6915: 		return '';
                   6916:             }
                   6917:         }
                   6918:         if ($copyright eq 'domain') {
                   6919:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6920: 	    unless (($env{'user.domain'} eq $1) ||
                   6921:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6922: 		return '';
                   6923:             }
1.262     matthew  6924:         }
1.620     albertel 6925:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6926:             # Library role, so allow browsing of resources in this domain.
                   6927:             return 'F';
1.238     www      6928:         }
1.341     www      6929:         if ($copyright eq 'custom') {
                   6930: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6931:         }
1.14      www      6932:     }
1.264     matthew  6933:     # Domain coordinator is trying to create a course
1.620     albertel 6934:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6935:         # uri is the requested domain in this case.
                   6936:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6937:         # a role of dc for the domain in question.
1.620     albertel 6938:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6939:     }
1.29      www      6940: 
1.52      www      6941:     my $thisallowed='';
                   6942:     my $statecond=0;
                   6943:     my $courseprivid='';
                   6944: 
1.1039    raeburn  6945:     my $ownaccess;
1.1043    raeburn  6946:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6947:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6948:         if ($uri eq '') {
                   6949:             $ownaccess = 1;
                   6950:         } else {
                   6951:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6952:                 my $udom = $env{'user.domain'};
                   6953:                 my $uname = $env{'user.name'};
                   6954:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6955:                     $ownaccess = 1;
1.1040    raeburn  6956:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6957:                     unless ($uri =~ m{\.\./}) {
                   6958:                         $ownaccess = 1;
                   6959:                     }
                   6960:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6961:                     my $now = time;
                   6962:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6963:                         my $adom = $1;
                   6964:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6965:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6966:                                 my ($start,$end) = split('.',$env{$key});
                   6967:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6968:                                     $ownaccess = 1;
                   6969:                                     last;
                   6970:                                 }
                   6971:                             }
                   6972:                         }
                   6973:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6974:                         my $adom = $1;
                   6975:                         my $aname = $2;
1.1042    raeburn  6976:                         foreach my $role ('ca','aa') { 
                   6977:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6978:                                 my ($start,$end) =
                   6979:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6980:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6981:                                     $ownaccess = 1;
                   6982:                                     last;
                   6983:                                 }
1.1039    raeburn  6984:                             }
                   6985:                         }
                   6986:                     }
                   6987:                 }
                   6988:             }
                   6989:         }
                   6990:     }
                   6991: 
1.52      www      6992: # Course
                   6993: 
1.620     albertel 6994:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6995:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6996:             $thisallowed.=$1;
                   6997:         }
1.52      www      6998:     }
1.29      www      6999: 
1.52      www      7000: # Domain
                   7001: 
1.620     albertel 7002:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7003:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7004:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7005:             $thisallowed.=$1;
                   7006:         }
1.12      www      7007:     }
1.52      www      7008: 
1.1141    raeburn  7009: # User who is not author or co-author might still be able to edit
                   7010: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7011:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7012:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7013:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7014:             $thisallowed.=$1;
                   7015:         }
                   7016:     }
                   7017: 
1.52      www      7018: # Course: uri itself is a course
1.66      www      7019:     my $courseuri=$uri;
                   7020:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7021:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7022: 
1.620     albertel 7023:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7024:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7025:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7026:             $thisallowed.=$1;
                   7027:         }
1.12      www      7028:     }
1.29      www      7029: 
1.665     albertel 7030: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7031: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7032:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7033: 	$thisallowed='';
1.671     raeburn  7034:         my ($match)=&is_on_map($uri);
                   7035:         if ($match) {
                   7036:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7037:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7038:                 my $value = $1;
                   7039:                 if ($noblockcheck) {
                   7040:                     $thisallowed.=$value;
1.1162    raeburn  7041:                 } else {
1.1281    raeburn  7042:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7043:                     if (@blockers > 0) {
                   7044:                         $thisallowed = 'B';
                   7045:                     } else {
                   7046:                         $thisallowed.=$value;
                   7047:                     }
1.1162    raeburn  7048:                 }
1.671     raeburn  7049:             }
                   7050:         } else {
1.705     albertel 7051:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7052:             if ($refuri) {
                   7053:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7054:                     $thisallowed='F';
1.671     raeburn  7055:                 } else {
                   7056:                     $refuri=&declutter($refuri);
                   7057:                     my ($match) = &is_on_map($refuri);
                   7058:                     if ($match) {
1.1281    raeburn  7059:                         if ($noblockcheck) {
                   7060:                             $thisallowed='F';
1.1162    raeburn  7061:                         } else {
1.1281    raeburn  7062:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7063:                             if (@blockers > 0) {
                   7064:                                 $thisallowed = 'B';
                   7065:                             } else {
                   7066:                                 $thisallowed='F';
                   7067:                             }
1.1162    raeburn  7068:                         }
1.671     raeburn  7069:                     }
1.669     raeburn  7070:                 }
1.671     raeburn  7071:             }
                   7072:         }
1.314     www      7073:     }
1.492     albertel 7074: 
1.766     albertel 7075:     if ($priv eq 'bre'
                   7076: 	&& $thisallowed ne 'F' 
                   7077: 	&& $thisallowed ne '2'
                   7078: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7079: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7080:     }
1.1250    raeburn  7081: 
1.52      www      7082: # Full access at system, domain or course-wide level? Exit.
1.29      www      7083:     if ($thisallowed=~/F/) {
                   7084: 	return 'F';
                   7085:     }
                   7086: 
1.52      www      7087: # If this is generating or modifying users, exit with special codes
1.29      www      7088: 
1.643     www      7089:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7090: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7091: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7092: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7093: 	    unless ($auname) { return $thisallowed; }
                   7094: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7095: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7096: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7097: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7098: 	}
1.52      www      7099: 	return $thisallowed;
                   7100:     }
                   7101: #
1.103     harris41 7102: # Gathered so far: system, domain and course wide privileges
1.52      www      7103: #
                   7104: # Course: See if uri or referer is an individual resource that is part of 
                   7105: # the course
                   7106: 
1.620     albertel 7107:     if ($env{'request.course.id'}) {
1.232     www      7108: 
1.620     albertel 7109:        $courseprivid=$env{'request.course.id'};
                   7110:        if ($env{'request.course.sec'}) {
                   7111:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7112:        }
                   7113:        $courseprivid=~s/\_/\//;
                   7114:        my $checkreferer=1;
1.232     www      7115:        my ($match,$cond)=&is_on_map($uri);
                   7116:        if ($match) {
                   7117:            $statecond=$cond;
1.620     albertel 7118:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7119:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7120:                my $value = $1;
                   7121:                if ($priv eq 'bre') {
1.1281    raeburn  7122:                    if ($noblockcheck) {
                   7123:                        $thisallowed.=$value;
1.1162    raeburn  7124:                    } else {
1.1281    raeburn  7125:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7126:                        if (@blockers > 0) {
                   7127:                            $thisallowed = 'B';
                   7128:                        } else {
                   7129:                            $thisallowed.=$value;
                   7130:                        }
1.1162    raeburn  7131:                    }
                   7132:                } else {
                   7133:                    $thisallowed.=$value;
                   7134:                }
1.52      www      7135:                $checkreferer=0;
                   7136:            }
1.29      www      7137:        }
1.83      www      7138:        
1.148     www      7139:        if ($checkreferer) {
1.620     albertel 7140: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7141:             unless ($refuri) {
1.800     albertel 7142:                 foreach my $key (keys(%env)) {
                   7143: 		    if ($key=~/^httpref\..*\*/) {
                   7144: 			my $pattern=$key;
1.156     www      7145:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7146:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7147:                         $pattern=~s/\//\\\//g;
1.152     www      7148:                         if ($orguri=~/$pattern/) {
1.800     albertel 7149: 			    $refuri=$env{$key};
1.148     www      7150:                         }
                   7151:                     }
1.191     harris41 7152:                 }
1.148     www      7153:             }
1.232     www      7154: 
1.148     www      7155:          if ($refuri) { 
1.152     www      7156: 	  $refuri=&declutter($refuri);
1.232     www      7157:           my ($match,$cond)=&is_on_map($refuri);
                   7158:             if ($match) {
                   7159:               my $refstatecond=$cond;
1.620     albertel 7160:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7161:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7162:                   my $value = $1;
                   7163:                   if ($priv eq 'bre') {
1.1281    raeburn  7164:                       if ($noblockcheck) {
                   7165:                           $thisallowed.=$value;
1.1162    raeburn  7166:                       } else {
1.1281    raeburn  7167:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7168:                           if (@blockers > 0) {
                   7169:                               $thisallowed = 'B';
                   7170:                           } else {
                   7171:                               $thisallowed.=$value;
                   7172:                           }
1.1162    raeburn  7173:                       }
                   7174:                   } else {
                   7175:                       $thisallowed.=$value;
                   7176:                   }
1.53      www      7177:                   $uri=$refuri;
                   7178:                   $statecond=$refstatecond;
1.52      www      7179:               }
                   7180:           }
1.148     www      7181:         }
1.29      www      7182:        }
1.52      www      7183:    }
1.29      www      7184: 
1.52      www      7185: #
1.103     harris41 7186: # Gathered now: all privileges that could apply, and condition number
1.52      www      7187: # 
                   7188: #
                   7189: # Full or no access?
                   7190: #
1.29      www      7191: 
1.52      www      7192:     if ($thisallowed=~/F/) {
                   7193: 	return 'F';
                   7194:     }
1.29      www      7195: 
1.52      www      7196:     unless ($thisallowed) {
                   7197:         return '';
                   7198:     }
1.29      www      7199: 
1.52      www      7200: # Restrictions exist, deal with them
                   7201: #
                   7202: #   C:according to course preferences
                   7203: #   R:according to resource settings
                   7204: #   L:unless locked
                   7205: #   X:according to user session state
                   7206: #
                   7207: 
                   7208: # Possibly locked functionality, check all courses
1.54      www      7209: # Locks might take effect only after 10 minutes cache expiration for other
                   7210: # courses, and 2 minutes for current course
1.52      www      7211: 
                   7212:     my $envkey;
                   7213:     if ($thisallowed=~/L/) {
1.1000    raeburn  7214:         foreach $envkey (keys(%env)) {
1.54      www      7215:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7216:                my $courseid=$2;
                   7217:                my $roleid=$1.'.'.$2;
1.92      www      7218:                $courseid=~s/^\///;
1.54      www      7219:                my $expiretime=600;
1.620     albertel 7220:                if ($env{'request.role'} eq $roleid) {
1.54      www      7221: 		  $expiretime=120;
                   7222:                }
                   7223: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7224:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7225:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7226: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7227:                }
1.620     albertel 7228:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7229:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7230: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7231:                        &log($env{'user.domain'},$env{'user.name'},
                   7232:                             $env{'user.home'},
1.57      www      7233:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7234:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7235:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7236: 		       return '';
                   7237:                    }
                   7238:                }
1.620     albertel 7239:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7240:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7241: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7242:                        &log($env{'user.domain'},$env{'user.name'},
                   7243:                             $env{'user.home'},
1.57      www      7244:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7245:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7246:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7247: 		       return '';
                   7248:                    }
                   7249:                }
                   7250: 	   }
1.29      www      7251:        }
1.52      www      7252:     }
                   7253:    
                   7254: #
                   7255: # Rest of the restrictions depend on selected course
                   7256: #
                   7257: 
1.620     albertel 7258:     unless ($env{'request.course.id'}) {
1.766     albertel 7259: 	if ($thisallowed eq 'A') {
                   7260: 	    return 'A';
1.814     raeburn  7261:         } elsif ($thisallowed eq 'B') {
                   7262:             return 'B';
1.766     albertel 7263: 	} else {
                   7264: 	    return '1';
                   7265: 	}
1.52      www      7266:     }
1.29      www      7267: 
1.52      www      7268: #
                   7269: # Now user is definitely in a course
                   7270: #
1.53      www      7271: 
                   7272: 
                   7273: # Course preferences
                   7274: 
                   7275:    if ($thisallowed=~/C/) {
1.620     albertel 7276:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7277:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7278:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7279: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7280: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7281: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7282: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7283: 			$env{'request.course.id'});
                   7284: 	   }
1.237     www      7285:            return '';
                   7286:        }
                   7287: 
1.620     albertel 7288:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7289: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7290: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7291: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7292: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7293: 			$env{'request.course.id'});
                   7294: 	   }
1.54      www      7295:            return '';
                   7296:        }
1.53      www      7297:    }
                   7298: 
                   7299: # Resource preferences
                   7300: 
                   7301:    if ($thisallowed=~/R/) {
1.620     albertel 7302:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7303:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7304: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7305: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7306: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7307: 	   }
                   7308: 	   return '';
1.54      www      7309:        }
1.53      www      7310:    }
1.30      www      7311: 
1.246     www      7312: # Restricted by state or randomout?
1.30      www      7313: 
1.52      www      7314:    if ($thisallowed=~/X/) {
1.620     albertel 7315:       if ($env{'acc.randomout'}) {
1.579     albertel 7316: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7317:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7318:             return ''; 
                   7319:          }
1.247     www      7320:       }
                   7321:       if (&condval($statecond)) {
1.52      www      7322: 	 return '2';
                   7323:       } else {
                   7324:          return '';
                   7325:       }
                   7326:    }
1.30      www      7327: 
1.766     albertel 7328:     if ($thisallowed eq 'A') {
                   7329: 	return 'A';
1.814     raeburn  7330:     } elsif ($thisallowed eq 'B') {
                   7331:         return 'B';
1.766     albertel 7332:     }
1.52      www      7333:    return 'F';
1.232     www      7334: }
1.1162    raeburn  7335: 
1.1192    raeburn  7336: # ------------------------------------------- Check construction space access
                   7337: 
                   7338: sub constructaccess {
                   7339:     my ($url,$setpriv)=@_;
                   7340: 
                   7341: # We do not allow editing of previous versions of files
                   7342:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7343: 
                   7344: # Get username and domain from URL
                   7345:     my ($ownername,$ownerdomain,$ownerhome);
                   7346: 
                   7347:     ($ownerdomain,$ownername) =
1.1297    damieng  7348:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7349: 
                   7350: # The URL does not really point to any authorspace, forget it
                   7351:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7352: 
                   7353: # Now we need to see if the user has access to the authorspace of
                   7354: # $ownername at $ownerdomain
                   7355: 
                   7356:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7357: # Real author for this?
                   7358:        $ownerhome = $env{'user.home'};
                   7359:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7360:           return ($ownername,$ownerdomain,$ownerhome);
                   7361:        }
                   7362:     } else {
                   7363: # Co-author for this?
                   7364:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7365:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7366:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7367:             return ($ownername,$ownerdomain,$ownerhome);
                   7368:         }
                   7369:     }
                   7370: 
                   7371: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7372: # we might as well leave
                   7373:    unless ($setpriv) { return ''; }
                   7374: 
                   7375: # Backdoor access?
                   7376:     my $allowed=&allowed('eco',$ownerdomain);
                   7377: # Nope
                   7378:     unless ($allowed) { return ''; }
                   7379: # Looks like we may have access, but could be locked by the owner of the construction space
                   7380:     if ($allowed eq 'U') {
                   7381:         my %blocked=&get('environment',['domcoord.author'],
                   7382:                          $ownerdomain,$ownername);
                   7383: # Is blocked by owner
                   7384:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7385:     }
                   7386:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7387: # Grant temporary access
                   7388:         my $then=$env{'user.login.time'};
1.1209    raeburn  7389:         my $update=$env{'user.update.time'};
1.1192    raeburn  7390:         if (!$update) { $update = $then; }
                   7391:         my $refresh=$env{'user.refresh.time'};
                   7392:         if (!$refresh) { $refresh = $update; }
                   7393:         my $now = time;
                   7394:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7395:                            $now,'ca','constructaccess');
                   7396:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7397:         return($ownername,$ownerdomain,$ownerhome);
                   7398:     }
                   7399: # No business here
                   7400:     return '';
                   7401: }
                   7402: 
1.1282    raeburn  7403: # ----------------------------------------------------------- Content Blocking
                   7404: 
                   7405: {
                   7406: # Caches for faster Course Contents display where content blocking
                   7407: # is in operation (i.e., interval param set) for timed quiz.
                   7408: #
                   7409: # User for whom data are being temporarily cached.
                   7410: my $cacheduser='';
                   7411: # Cached blockers for this user (a hash of blocking items). 
                   7412: my %cachedblockers=();
                   7413: # When the data were last cached.
                   7414: my $cachedlast='';
                   7415: 
                   7416: sub load_all_blockers {
                   7417:     my ($uname,$udom,$blocks)=@_;
                   7418:     if (($uname ne '') && ($udom ne '')) { 
                   7419:         if (($cacheduser eq $uname.':'.$udom) &&
                   7420:             (abs($cachedlast-time)<5)) {
                   7421:             return;
                   7422:         }
                   7423:     }
                   7424:     $cachedlast=time;
                   7425:     $cacheduser=$uname.':'.$udom;
                   7426:     %cachedblockers = &get_commblock_resources($blocks);
                   7427: }
                   7428: 
1.1162    raeburn  7429: sub get_comm_blocks {
                   7430:     my ($cdom,$cnum) = @_;
                   7431:     if ($cdom eq '' || $cnum eq '') {
                   7432:         return unless ($env{'request.course.id'});
                   7433:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7434:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7435:     }
                   7436:     my %commblocks;
                   7437:     my $hashid=$cdom.'_'.$cnum;
                   7438:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7439:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7440:         %commblocks = %{$blocksref};
                   7441:     } else {
                   7442:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7443:         my $cachetime = 600;
                   7444:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7445:     }
                   7446:     return %commblocks;
                   7447: }
                   7448: 
1.1282    raeburn  7449: sub get_commblock_resources {
                   7450:     my ($blocks) = @_;
                   7451:     my %blockers = ();
                   7452:     return %blockers unless ($env{'request.course.id'});
                   7453:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7454:     my %commblocks;
                   7455:     if (ref($blocks) eq 'HASH') {
                   7456:         %commblocks = %{$blocks};
                   7457:     } else {
                   7458:         %commblocks = &get_comm_blocks();
                   7459:     }
1.1282    raeburn  7460:     return %blockers unless (keys(%commblocks) > 0); 
                   7461:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7462:     return %blockers unless (ref($navmap));
1.1162    raeburn  7463:     my $now = time;
                   7464:     foreach my $block (keys(%commblocks)) {
                   7465:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7466:             my ($start,$end) = ($1,$2);
                   7467:             if ($start <= $now && $end >= $now) {
                   7468:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7469:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7470:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7471:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7472:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7473:                             }
                   7474:                         }
                   7475:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7476:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7477:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7478:                             }
                   7479:                         }
                   7480:                     }
                   7481:                 }
                   7482:             }
                   7483:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7484:             my $item = $1;
1.1163    raeburn  7485:             my @to_test;
1.1162    raeburn  7486:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7487:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7488:                     my @interval;
                   7489:                     my $type = 'map';
                   7490:                     if ($item eq 'course') {
                   7491:                         $type = 'course';
                   7492:                         @interval=&EXT("resource.0.interval");
                   7493:                     } else {
                   7494:                         if ($item =~ /___\d+___/) {
                   7495:                             $type = 'resource';
                   7496:                             @interval=&EXT("resource.0.interval",$item);
                   7497:                             if (ref($navmap)) {                        
                   7498:                                 my $res = $navmap->getBySymb($item); 
                   7499:                                 push(@to_test,$res);
                   7500:                             }
1.1162    raeburn  7501:                         } else {
1.1282    raeburn  7502:                             my $mapsymb = &symbread($item,1);
                   7503:                             if ($mapsymb) {
                   7504:                                 if (ref($navmap)) {
                   7505:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7506:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7507:                                     foreach my $res (@to_test) {
                   7508:                                         my $symb = $res->symb();
                   7509:                                         next if ($symb eq $mapsymb);
                   7510:                                         if ($symb ne '') {
                   7511:                                             @interval=&EXT("resource.0.interval",$symb);
                   7512:                                             if ($interval[1] eq 'map') {
                   7513:                                                 last;
1.1162    raeburn  7514:                                             }
                   7515:                                         }
                   7516:                                     }
                   7517:                                 }
                   7518:                             }
                   7519:                         }
1.1282    raeburn  7520:                     }
1.1292    raeburn  7521:                     if ($interval[0] =~ /^\d+/) {
                   7522:                         my ($timelimit) = split(/_/,$interval[0]);
1.1282    raeburn  7523:                         my $first_access;
                   7524:                         if ($type eq 'resource') {
                   7525:                             $first_access=&get_first_access($interval[1],$item);
                   7526:                         } elsif ($type eq 'map') {
                   7527:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7528:                         } else {
                   7529:                             $first_access=&get_first_access($interval[1]);
                   7530:                         }
                   7531:                         if ($first_access) {
1.1292    raeburn  7532:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7533:                             if ($timesup > $now) {
                   7534:                                 my $activeblock;
                   7535:                                 foreach my $res (@to_test) {
1.1283    raeburn  7536:                                     if ($res->answerable()) {
1.1282    raeburn  7537:                                         $activeblock = 1;
                   7538:                                         last;
                   7539:                                     }
                   7540:                                 }
                   7541:                                 if ($activeblock) {
                   7542:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7543:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7544:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7545:                                          }
                   7546:                                     }
                   7547:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7548:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7549:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7550:                                         }
1.1162    raeburn  7551:                                     }
                   7552:                                 }
                   7553:                             }
                   7554:                         }
                   7555:                     }
                   7556:                 }
                   7557:             }
                   7558:         }
                   7559:     }
1.1282    raeburn  7560:     return %blockers;
1.1162    raeburn  7561: }
                   7562: 
1.1282    raeburn  7563: sub has_comm_blocking {
                   7564:     my ($priv,$symb,$uri,$blocks) = @_;
                   7565:     my @blockers;
                   7566:     return unless ($env{'request.course.id'});
                   7567:     return unless ($priv eq 'bre');
                   7568:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7569:     return if ($env{'request.state'} eq 'construct');
                   7570:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7571:     return unless (keys(%cachedblockers) > 0);
                   7572:     my (%possibles,@symbs);
                   7573:     if (!$symb) {
                   7574:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7575:     }
1.1282    raeburn  7576:     if ($symb) {
                   7577:         @symbs = ($symb);
                   7578:     } elsif (keys(%possibles)) { 
                   7579:         @symbs = keys(%possibles);
                   7580:     }
                   7581:     my $noblock;
                   7582:     foreach my $symb (@symbs) {
                   7583:         last if ($noblock);
                   7584:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7585:         foreach my $block (keys(%cachedblockers)) {
                   7586:             if ($block =~ /^firstaccess____(.+)$/) {
                   7587:                 my $item = $1;
                   7588:                 if (($item eq $map) || ($item eq $symb)) {
                   7589:                     $noblock = 1;
                   7590:                     last;
                   7591:                 }
                   7592:             }
                   7593:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7594:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7595:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7596:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7597:                             push(@blockers,$block);
                   7598:                         }
                   7599:                     }
                   7600:                 }
1.1162    raeburn  7601:             }
1.1282    raeburn  7602:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7603:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7604:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7605:                         push(@blockers,$block);
                   7606:                     }
                   7607:                 }
1.1162    raeburn  7608:             }
                   7609:         }
                   7610:     }
1.1282    raeburn  7611:     return if ($noblock);
                   7612:     return @blockers;
                   7613: }
1.1162    raeburn  7614: }
                   7615: 
1.1282    raeburn  7616: # -------------------------------- Deversion and split uri into path an filename   
                   7617: 
1.1133    foxr     7618: #
1.1282    raeburn  7619: #   Removes the version from a URI and
1.1133    foxr     7620: #   splits it in to its filename and path to the filename.
                   7621: #   Seems like File::Basename could have done this more clearly.
                   7622: #   Parameters:
                   7623: #      $uri   - input URI
                   7624: #   Returns:
                   7625: #     Two element list consisting of 
                   7626: #     $pathname  - the URI up to and excluding the trailing /
                   7627: #     $filename  - The part of the URI following the last /
                   7628: #  NOTE:
                   7629: #    Another realization of this is simply:
                   7630: #    use File::Basename;
                   7631: #    ...
                   7632: #    $uri = shift;
                   7633: #    $filename = basename($uri);
                   7634: #    $path     = dirname($uri);
                   7635: #    return ($filename, $path);
                   7636: #
                   7637: #     The implementation below is probably faster however.
                   7638: #
1.710     albertel 7639: sub split_uri_for_cond {
                   7640:     my $uri=&deversion(&declutter(shift));
                   7641:     my @uriparts=split(/\//,$uri);
                   7642:     my $filename=pop(@uriparts);
                   7643:     my $pathname=join('/',@uriparts);
                   7644:     return ($pathname,$filename);
                   7645: }
1.232     www      7646: # --------------------------------------------------- Is a resource on the map?
                   7647: 
                   7648: sub is_on_map {
1.710     albertel 7649:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7650:     #Trying to find the conditional for the file
1.620     albertel 7651:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7652: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7653:     if ($match) {
1.289     bowersj2 7654: 	return (1,$1);
                   7655:     } else {
1.434     www      7656: 	return (0,0);
1.289     bowersj2 7657:     }
1.12      www      7658: }
                   7659: 
1.427     www      7660: # --------------------------------------------------------- Get symb from alias
                   7661: 
                   7662: sub get_symb_from_alias {
                   7663:     my $symb=shift;
                   7664:     my ($map,$resid,$url)=&decode_symb($symb);
                   7665: # Already is a symb
                   7666:     if ($url) { return $symb; }
                   7667: # Must be an alias
                   7668:     my $aliassymb='';
                   7669:     my %bighash;
1.620     albertel 7670:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7671:                             &GDBM_READER(),0640)) {
                   7672:         my $rid=$bighash{'mapalias_'.$symb};
                   7673: 	if ($rid) {
                   7674: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7675: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7676: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7677: 	}
                   7678:         untie %bighash;
                   7679:     }
                   7680:     return $aliassymb;
                   7681: }
                   7682: 
1.12      www      7683: # ----------------------------------------------------------------- Define Role
                   7684: 
                   7685: sub definerole {
                   7686:   if (allowed('mcr','/')) {
                   7687:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7688:     foreach my $role (split(':',$sysrole)) {
                   7689: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7690:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7691:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7692: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7693:                return "refused:s:$crole&$cqual"; 
                   7694:             }
                   7695:         }
1.191     harris41 7696:     }
1.800     albertel 7697:     foreach my $role (split(':',$domrole)) {
                   7698: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7699:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7700:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7701: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7702:                return "refused:d:$crole&$cqual"; 
                   7703:             }
                   7704:         }
1.191     harris41 7705:     }
1.800     albertel 7706:     foreach my $role (split(':',$courole)) {
                   7707: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7708:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7709:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7710: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7711:                return "refused:c:$crole&$cqual"; 
                   7712:             }
                   7713:         }
1.191     harris41 7714:     }
1.620     albertel 7715:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7716:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7717: 	        "rolesdef_$rolename=".
                   7718:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7719:     return reply($command,$env{'user.home'});
1.12      www      7720:   } else {
                   7721:     return 'refused';
                   7722:   }
1.105     harris41 7723: }
                   7724: 
                   7725: # ---------------- Make a metadata query against the network of library servers
                   7726: 
                   7727: sub metadata_query {
1.1237    raeburn  7728:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7729:     my %rhash;
1.845     albertel 7730:     my %libserv = &all_library();
1.244     matthew  7731:     my @server_list = (defined($server_array) ? @$server_array
                   7732:                                               : keys(%libserv) );
                   7733:     for my $server (@server_list) {
1.1237    raeburn  7734:         my $domains = ''; 
                   7735:         if (ref($domains_hash) eq 'HASH') {
                   7736:             $domains = $domains_hash->{$server}; 
                   7737:         }
1.118     harris41 7738: 	unless ($custom or $customshow) {
1.1237    raeburn  7739: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7740: 	    $rhash{$server}=$reply;
                   7741: 	}
                   7742: 	else {
                   7743: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7744: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7745: 			     $server);
                   7746: 	    $rhash{$server}=$reply;
                   7747: 	}
1.112     harris41 7748:     }
1.118     harris41 7749:     return \%rhash;
1.240     www      7750: }
                   7751: 
                   7752: # ----------------------------------------- Send log queries and wait for reply
                   7753: 
                   7754: sub log_query {
                   7755:     my ($uname,$udom,$query,%filters)=@_;
                   7756:     my $uhome=&homeserver($uname,$udom);
                   7757:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7758:     my $uhost=&hostname($uhome);
1.800     albertel 7759:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7760:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7761:                        $uhome);
1.479     albertel 7762:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7763:     return get_query_reply($queryid);
                   7764: }
                   7765: 
1.818     raeburn  7766: # -------------------------- Update MySQL table for portfolio file
                   7767: 
                   7768: sub update_portfolio_table {
1.821     raeburn  7769:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7770:     if ($group ne '') {
                   7771:         $file_name =~s /^\Q$group\E//;
                   7772:     }
1.818     raeburn  7773:     my $homeserver = &homeserver($uname,$udom);
                   7774:     my $queryid=
1.821     raeburn  7775:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7776:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7777:     my $reply = &get_query_reply($queryid);
                   7778:     return $reply;
                   7779: }
                   7780: 
1.899     raeburn  7781: # -------------------------- Update MySQL allusers table
                   7782: 
                   7783: sub update_allusers_table {
                   7784:     my ($uname,$udom,$names) = @_;
                   7785:     my $homeserver = &homeserver($uname,$udom);
                   7786:     my $queryid=
                   7787:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7788:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7789:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7790:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7791:                'generation='.&escape($names->{'generation'}).'%%'.
                   7792:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7793:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7794:     return;
1.899     raeburn  7795: }
                   7796: 
1.508     raeburn  7797: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7798: 
                   7799: sub fetch_enrollment_query {
1.511     raeburn  7800:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7801:     my $homeserver;
1.547     raeburn  7802:     my $maxtries = 1;
1.508     raeburn  7803:     if ($context eq 'automated') {
                   7804:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7805:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7806:     } else {
                   7807:         $homeserver = &homeserver($cnum,$dom);
                   7808:     }
1.838     albertel 7809:     my $host=&hostname($homeserver);
1.506     raeburn  7810:     my $cmd = '';
1.1000    raeburn  7811:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7812:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7813:     }
                   7814:     $cmd =~ s/%%$//;
                   7815:     $cmd = &escape($cmd);
                   7816:     my $query = 'fetchenrollment';
1.620     albertel 7817:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7818:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7819:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7820:         return 'error: '.$queryid;
                   7821:     }
1.506     raeburn  7822:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7823:     my $tries = 1;
                   7824:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7825:         $reply = &get_query_reply($queryid);
                   7826:         $tries ++;
                   7827:     }
1.526     raeburn  7828:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7829:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7830:     } else {
1.901     albertel 7831:         my @responses = split(/:/,$reply);
1.515     raeburn  7832:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7833:             foreach my $line (@responses) {
                   7834:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7835:                 $$replyref{$key} = $value;
                   7836:             }
                   7837:         } else {
1.1117    foxr     7838:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7839:             foreach my $line (@responses) {
                   7840:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7841:                 $$replyref{$key} = $value;
                   7842:                 if ($value > 0) {
1.800     albertel 7843:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7844:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7845:                         my $destname = $pathname.'/'.$filename;
                   7846:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7847:                         if ($xml_classlist =~ /^error/) {
                   7848:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7849:                         } else {
1.506     raeburn  7850:                             if ( open(FILE,">$destname") ) {
                   7851:                                 print FILE &unescape($xml_classlist);
                   7852:                                 close(FILE);
1.526     raeburn  7853:                             } else {
                   7854:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7855:                             }
                   7856:                         }
                   7857:                     }
                   7858:                 }
                   7859:             }
                   7860:         }
                   7861:         return 'ok';
                   7862:     }
                   7863:     return 'error';
                   7864: }
                   7865: 
1.242     www      7866: sub get_query_reply {
                   7867:     my $queryid=shift;
1.1117    foxr     7868:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7869:     my $reply='';
                   7870:     for (1..100) {
1.1289    damieng  7871: 	sleep(0.2);
1.240     www      7872:         if (-e $replyfile.'.end') {
1.448     albertel 7873: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7874: 		$reply = join('',<$fh>);
                   7875: 		close($fh);
1.240     www      7876: 	   } else { return 'error: reply_file_error'; }
1.242     www      7877:            return &unescape($reply);
                   7878: 	}
1.240     www      7879:     }
1.242     www      7880:     return 'timeout:'.$queryid;
1.240     www      7881: }
                   7882: 
                   7883: sub courselog_query {
1.241     www      7884: #
                   7885: # possible filters:
                   7886: # url: url or symb
                   7887: # username
                   7888: # domain
                   7889: # action: view, submit, grade
                   7890: # start: timestamp
                   7891: # end: timestamp
                   7892: #
1.240     www      7893:     my (%filters)=@_;
1.620     albertel 7894:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7895:     if ($filters{'url'}) {
                   7896: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7897:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7898:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7899:     }
1.620     albertel 7900:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7901:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7902:     return &log_query($cname,$cdom,'courselog',%filters);
                   7903: }
                   7904: 
                   7905: sub userlog_query {
1.858     raeburn  7906: #
                   7907: # possible filters:
                   7908: # action: log check role
                   7909: # start: timestamp
                   7910: # end: timestamp
                   7911: #
1.240     www      7912:     my ($uname,$udom,%filters)=@_;
                   7913:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7914: }
                   7915: 
1.506     raeburn  7916: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7917: 
                   7918: sub auto_run {
1.508     raeburn  7919:     my ($cnum,$cdom) = @_;
1.876     raeburn  7920:     my $response = 0;
                   7921:     my $settings;
                   7922:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7923:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7924:         $settings = $domconfig{'autoenroll'};
                   7925:         if ($settings->{'run'} eq '1') {
                   7926:             $response = 1;
                   7927:         }
                   7928:     } else {
1.934     raeburn  7929:         my $homeserver;
                   7930:         if (&is_course($cdom,$cnum)) {
                   7931:             $homeserver = &homeserver($cnum,$cdom);
                   7932:         } else {
                   7933:             $homeserver = &domain($cdom,'primary');
                   7934:         }
                   7935:         if ($homeserver ne 'no_host') {
                   7936:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7937:         }
1.876     raeburn  7938:     }
1.506     raeburn  7939:     return $response;
                   7940: }
1.776     albertel 7941: 
1.506     raeburn  7942: sub auto_get_sections {
1.508     raeburn  7943:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7944:     my $homeserver;
                   7945:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7946:         $homeserver = &homeserver($cnum,$cdom);
                   7947:     }
                   7948:     if (!defined($homeserver)) { 
                   7949:         if ($cdom =~ /^$match_domain$/) {
                   7950:             $homeserver = &domain($cdom,'primary');
                   7951:         }
                   7952:     }
                   7953:     my @secs;
                   7954:     if (defined($homeserver)) {
                   7955:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7956:         unless ($response eq 'refused') {
                   7957:             @secs = split(/:/,$response);
                   7958:         }
1.506     raeburn  7959:     }
                   7960:     return @secs;
                   7961: }
1.776     albertel 7962: 
1.506     raeburn  7963: sub auto_new_course {
1.1099    raeburn  7964:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7965:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7966:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7967:     return $response;
                   7968: }
1.776     albertel 7969: 
1.506     raeburn  7970: sub auto_validate_courseID {
1.508     raeburn  7971:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7972:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7973:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7974:     return $response;
                   7975: }
1.776     albertel 7976: 
1.1007    raeburn  7977: sub auto_validate_instcode {
1.1020    raeburn  7978:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7979:     my ($homeserver,$response);
                   7980:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7981:         $homeserver = &homeserver($cnum,$cdom);
                   7982:     }
                   7983:     if (!defined($homeserver)) {
                   7984:         if ($cdom =~ /^$match_domain$/) {
                   7985:             $homeserver = &domain($cdom,'primary');
                   7986:         }
                   7987:     }
1.1065    raeburn  7988:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7989:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7990:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7991:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7992: }
                   7993: 
1.506     raeburn  7994: sub auto_create_password {
1.873     raeburn  7995:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7996:     my ($homeserver,$response);
1.506     raeburn  7997:     my $create_passwd = 0;
                   7998:     my $authchk = '';
1.873     raeburn  7999:     if ($udom =~ /^$match_domain$/) {
                   8000:         $homeserver = &domain($udom,'primary');
                   8001:     }
                   8002:     if ($homeserver eq '') {
                   8003:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8004:             $homeserver = &homeserver($cnum,$cdom);
                   8005:         }
                   8006:     }
                   8007:     if ($homeserver eq '') {
                   8008:         $authchk = 'nodomain';
1.506     raeburn  8009:     } else {
1.873     raeburn  8010:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8011:         if ($response eq 'refused') {
                   8012:             $authchk = 'refused';
                   8013:         } else {
1.901     albertel 8014:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8015:         }
1.506     raeburn  8016:     }
                   8017:     return ($authparam,$create_passwd,$authchk);
                   8018: }
                   8019: 
1.706     raeburn  8020: sub auto_photo_permission {
                   8021:     my ($cnum,$cdom,$students) = @_;
                   8022:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8023:     my ($outcome,$perm_reqd,$conditions) = 
                   8024: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8025:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8026: 	return (undef,undef);
                   8027:     }
1.706     raeburn  8028:     return ($outcome,$perm_reqd,$conditions);
                   8029: }
                   8030: 
                   8031: sub auto_checkphotos {
                   8032:     my ($uname,$udom,$pid) = @_;
                   8033:     my $homeserver = &homeserver($uname,$udom);
                   8034:     my ($result,$resulttype);
                   8035:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8036: 				   &escape($uname).':'.&escape($pid),
                   8037: 				   $homeserver));
1.709     albertel 8038:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8039: 	return (undef,undef);
                   8040:     }
1.706     raeburn  8041:     if ($outcome) {
                   8042:         ($result,$resulttype) = split(/:/,$outcome);
                   8043:     } 
                   8044:     return ($result,$resulttype);
                   8045: }
                   8046: 
                   8047: sub auto_photochoice {
                   8048:     my ($cnum,$cdom) = @_;
                   8049:     my $homeserver = &homeserver($cnum,$cdom);
                   8050:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8051: 						       &escape($cdom),
                   8052: 						       $homeserver)));
1.709     albertel 8053:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8054: 	return (undef,undef);
                   8055:     }
1.706     raeburn  8056:     return ($update,$comment);
                   8057: }
                   8058: 
                   8059: sub auto_photoupdate {
                   8060:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8061:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8062:     my $host=&hostname($homeserver);
1.706     raeburn  8063:     my $cmd = '';
                   8064:     my $maxtries = 1;
1.800     albertel 8065:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8066:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8067:     }
                   8068:     $cmd =~ s/%%$//;
                   8069:     $cmd = &escape($cmd);
                   8070:     my $query = 'institutionalphotos';
                   8071:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8072:     unless ($queryid=~/^\Q$host\E\_/) {
                   8073:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8074:         return 'error: '.$queryid;
                   8075:     }
                   8076:     my $reply = &get_query_reply($queryid);
                   8077:     my $tries = 1;
                   8078:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8079:         $reply = &get_query_reply($queryid);
                   8080:         $tries ++;
                   8081:     }
                   8082:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8083:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8084:     } else {
                   8085:         my @responses = split(/:/,$reply);
                   8086:         my $outcome = shift(@responses); 
                   8087:         foreach my $item (@responses) {
                   8088:             my ($key,$value) = split(/=/,$item);
                   8089:             $$photo{$key} = $value;
                   8090:         }
                   8091:         return $outcome;
                   8092:     }
                   8093:     return 'error';
                   8094: }
                   8095: 
1.521     raeburn  8096: sub auto_instcode_format {
1.793     albertel 8097:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8098: 	$cat_order) = @_;
1.521     raeburn  8099:     my $courses = '';
1.772     raeburn  8100:     my @homeservers;
1.521     raeburn  8101:     if ($caller eq 'global') {
1.841     albertel 8102: 	my %servers = &get_servers($codedom,'library');
                   8103: 	foreach my $tryserver (keys(%servers)) {
                   8104: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8105: 		push(@homeservers,$tryserver);
                   8106: 	    }
1.584     raeburn  8107:         }
1.1022    raeburn  8108:     } elsif ($caller eq 'requests') {
                   8109:         if ($codedom =~ /^$match_domain$/) {
                   8110:             my $chome = &domain($codedom,'primary');
                   8111:             unless ($chome eq 'no_host') {
                   8112:                 push(@homeservers,$chome);
                   8113:             }
                   8114:         }
1.521     raeburn  8115:     } else {
1.772     raeburn  8116:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8117:     }
1.793     albertel 8118:     foreach my $code (keys(%{$instcodes})) {
                   8119:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8120:     }
                   8121:     chop($courses);
1.772     raeburn  8122:     my $ok_response = 0;
                   8123:     my $response;
                   8124:     while (@homeservers > 0 && $ok_response == 0) {
                   8125:         my $server = shift(@homeservers); 
                   8126:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8127:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8128:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8129: 		split(/:/,$response);
1.772     raeburn  8130:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8131:             push(@{$codetitles},&str2array($codetitles_str));
                   8132:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8133:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8134:             $ok_response = 1;
                   8135:         }
                   8136:     }
                   8137:     if ($ok_response) {
1.521     raeburn  8138:         return 'ok';
1.772     raeburn  8139:     } else {
                   8140:         return $response;
1.521     raeburn  8141:     }
                   8142: }
                   8143: 
1.792     raeburn  8144: sub auto_instcode_defaults {
                   8145:     my ($domain,$returnhash,$code_order) = @_;
                   8146:     my @homeservers;
1.841     albertel 8147: 
                   8148:     my %servers = &get_servers($domain,'library');
                   8149:     foreach my $tryserver (keys(%servers)) {
                   8150: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8151: 	    push(@homeservers,$tryserver);
                   8152: 	}
1.792     raeburn  8153:     }
1.841     albertel 8154: 
1.792     raeburn  8155:     my $response;
1.841     albertel 8156:     foreach my $server (@homeservers) {
1.792     raeburn  8157:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8158:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8159: 	
                   8160: 	foreach my $pair (split(/\&/,$response)) {
                   8161: 	    my ($name,$value)=split(/\=/,$pair);
                   8162: 	    if ($name eq 'code_order') {
                   8163: 		@{$code_order} = split(/\&/,&unescape($value));
                   8164: 	    } else {
                   8165: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8166: 	    }
                   8167: 	}
                   8168: 	return 'ok';
1.792     raeburn  8169:     }
1.841     albertel 8170: 
                   8171:     return $response;
1.1003    raeburn  8172: }
                   8173: 
                   8174: sub auto_possible_instcodes {
1.1007    raeburn  8175:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8176:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8177:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8178:         return;
                   8179:     }
1.1003    raeburn  8180:     my (@homeservers,$uhome);
                   8181:     if (defined(&domain($domain,'primary'))) {
                   8182:         $uhome=&domain($domain,'primary');
                   8183:         push(@homeservers,&domain($domain,'primary'));
                   8184:     } else {
                   8185:         my %servers = &get_servers($domain,'library');
                   8186:         foreach my $tryserver (keys(%servers)) {
                   8187:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8188:                 push(@homeservers,$tryserver);
                   8189:             }
                   8190:         }
                   8191:     }
                   8192:     my $response;
                   8193:     foreach my $server (@homeservers) {
                   8194:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8195:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8196:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8197:             split(':',$response);
                   8198:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8199:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8200:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8201:             my ($name,$value)=split('=',$item);
                   8202:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8203:         }
                   8204:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8205:             my ($name,$value)=split('=',$item);
                   8206:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8207:         }
                   8208:         return 'ok';
                   8209:     }
                   8210:     return $response;
                   8211: }
1.792     raeburn  8212: 
1.1010    raeburn  8213: sub auto_courserequest_checks {
                   8214:     my ($dom) = @_;
1.1020    raeburn  8215:     my ($homeserver,%validations);
                   8216:     if ($dom =~ /^$match_domain$/) {
                   8217:         $homeserver = &domain($dom,'primary');
                   8218:     }
                   8219:     unless ($homeserver eq 'no_host') {
                   8220:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8221:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8222:             my @items = split(/&/,$response);
                   8223:             foreach my $item (@items) {
                   8224:                 my ($key,$value) = split('=',$item);
                   8225:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8226:             }
                   8227:         }
                   8228:     }
1.1010    raeburn  8229:     return %validations; 
                   8230: }
                   8231: 
1.1020    raeburn  8232: sub auto_courserequest_validation {
1.1255    raeburn  8233:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8234:     my ($homeserver,$response);
                   8235:     if ($dom =~ /^$match_domain$/) {
                   8236:         $homeserver = &domain($dom,'primary');
                   8237:     }
1.1255    raeburn  8238:     unless ($homeserver eq 'no_host') {
                   8239:         my $customdata;
                   8240:         if (ref($custominfo) eq 'HASH') {
                   8241:             $customdata = &freeze_escape($custominfo);
                   8242:         }
1.1020    raeburn  8243:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8244:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8245:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8246:                                     $customdata,$homeserver));
1.1020    raeburn  8247:     }
                   8248:     return $response;
                   8249: }
                   8250: 
1.777     albertel 8251: sub auto_validate_class_sec {
1.918     raeburn  8252:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8253:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8254:     my $ownerlist;
                   8255:     if (ref($owners) eq 'ARRAY') {
                   8256:         $ownerlist = join(',',@{$owners});
                   8257:     } else {
                   8258:         $ownerlist = $owners;
                   8259:     }
1.773     raeburn  8260:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8261:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8262:     return $response;
                   8263: }
                   8264: 
1.1248    raeburn  8265: sub auto_crsreq_update {
                   8266:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8267:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8268:     my ($homeserver,%crsreqresponse);
                   8269:     if ($cdom =~ /^$match_domain$/) {
                   8270:         $homeserver = &domain($cdom,'primary');
                   8271:     }
                   8272:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8273:         my $info;
                   8274:         if (ref($inbound) eq 'HASH') {
                   8275:             $info = &freeze_escape($inbound);
                   8276:         }
                   8277:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8278:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8279:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8280:                             &escape($title).':'.&escape($code).':'.
                   8281:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8282:                             $homeserver);
1.1248    raeburn  8283:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8284:             my @items = split(/&/,$response);
                   8285:             foreach my $item (@items) {
                   8286:                 my ($key,$value) = split('=',$item);
                   8287:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8288:             }
                   8289:         }
                   8290:     }
                   8291:     return \%crsreqresponse;
                   8292: }
                   8293: 
1.1305    raeburn  8294: sub auto_export_grades {
                   8295:     my ($cnum,$cdom,$gradesref) = @_;
                   8296:     return;
                   8297: }
                   8298: 
1.1287    raeburn  8299: sub check_instcode_cloning {
                   8300:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8301:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8302:         return;
                   8303:     }
                   8304:     my $canclone;
                   8305:     if (@{$code_order} > 0) {
                   8306:         my $instcoderegexp ='^';
                   8307:         my @clonecodes = split(/\&/,$cloner);
                   8308:         foreach my $item (@{$code_order}) {
                   8309:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8310:                 foreach my $pair (@clonecodes) {
                   8311:                     my ($key,$val) = split(/\=/,$pair,2);
                   8312:                     $val = &unescape($val);
                   8313:                     if ($key eq $item) {
                   8314:                         $instcoderegexp .= '('.$val.')';
                   8315:                         last;
                   8316:                     }
                   8317:                 }
                   8318:             } else {
                   8319:                 $instcoderegexp .= $codedefaults->{$item};
                   8320:             }
                   8321:         }
                   8322:         $instcoderegexp .= '$';
                   8323:         my (@from,@to);
                   8324:         eval {
                   8325:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8326:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8327:         };
                   8328:         if ((@from > 0) && (@to > 0)) {
                   8329:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8330:             if (!@diffs) {
                   8331:                 $canclone = 1;
                   8332:             }
                   8333:         }
                   8334:     }
                   8335:     return $canclone;
                   8336: }
                   8337: 
                   8338: sub default_instcode_cloning {
                   8339:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8340:     my (%codedefaults,@code_order,$canclone);
                   8341:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8342:         %codedefaults = %{$codedefaultsref};
                   8343:         @code_order = @{$codeorderref};
                   8344:     } elsif ($clonedom) {
                   8345:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8346:     }
                   8347:     if (($domdefclone) && (@code_order)) {
                   8348:         my @clonecodes = split(/\+/,$domdefclone);
                   8349:         my $instcoderegexp ='^';
                   8350:         foreach my $item (@code_order) {
                   8351:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8352:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8353:             } else {
                   8354:                 $instcoderegexp .= $codedefaults{$item};
                   8355:             }
                   8356:         }
                   8357:         $instcoderegexp .= '$';
                   8358:         my (@from,@to);
                   8359:         eval {
                   8360:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8361:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8362:         };
                   8363:         if ((@from > 0) && (@to > 0)) {
                   8364:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8365:             if (!@diffs) {
                   8366:                 $canclone = 1;
                   8367:             }
                   8368:         }
                   8369:     }
                   8370:     return $canclone;
                   8371: }
                   8372: 
1.679     raeburn  8373: # ------------------------------------------------------- Course Group routines
                   8374: 
                   8375: sub get_coursegroups {
1.809     raeburn  8376:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8377:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8378: }
                   8379: 
1.679     raeburn  8380: sub modify_coursegroup {
                   8381:     my ($cdom,$cnum,$groupsettings) = @_;
                   8382:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8383: }
                   8384: 
1.809     raeburn  8385: sub toggle_coursegroup_status {
                   8386:     my ($cdom,$cnum,$group,$action) = @_;
                   8387:     my ($from_namespace,$to_namespace);
                   8388:     if ($action eq 'delete') {
                   8389:         $from_namespace = 'coursegroups';
                   8390:         $to_namespace = 'deleted_groups';
                   8391:     } else {
                   8392:         $from_namespace = 'deleted_groups';
                   8393:         $to_namespace = 'coursegroups';
                   8394:     }
                   8395:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8396:     if (my $tmp = &error(%curr_group)) {
                   8397:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8398:         return ('read error',$tmp);
                   8399:     } else {
                   8400:         my %savedsettings = %curr_group; 
1.809     raeburn  8401:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8402:         my $deloutcome;
                   8403:         if ($result eq 'ok') {
1.809     raeburn  8404:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8405:         } else {
                   8406:             return ('write error',$result);
                   8407:         }
                   8408:         if ($deloutcome eq 'ok') {
                   8409:             return 'ok';
                   8410:         } else {
                   8411:             return ('delete error',$deloutcome);
                   8412:         }
                   8413:     }
                   8414: }
                   8415: 
1.679     raeburn  8416: sub modify_group_roles {
1.957     raeburn  8417:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8418:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8419:     my $role = 'gr/'.&escape($userprivs);
                   8420:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8421:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8422:     if ($result eq 'ok') {
                   8423:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8424:     }
1.679     raeburn  8425:     return $result;
                   8426: }
                   8427: 
                   8428: sub modify_coursegroup_membership {
                   8429:     my ($cdom,$cnum,$membership) = @_;
                   8430:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8431:     return $result;
                   8432: }
                   8433: 
1.682     raeburn  8434: sub get_active_groups {
                   8435:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8436:     my $now = time;
                   8437:     my %groups = ();
                   8438:     foreach my $key (keys(%env)) {
1.811     albertel 8439:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8440:             my ($start,$end) = split(/\./,$env{$key});
                   8441:             if (($end!=0) && ($end<$now)) { next; }
                   8442:             if (($start!=0) && ($start>$now)) { next; }
                   8443:             if ($1 eq $cdom && $2 eq $cnum) {
                   8444:                 $groups{$3} = $env{$key} ;
                   8445:             }
                   8446:         }
                   8447:     }
                   8448:     return %groups;
                   8449: }
                   8450: 
1.683     raeburn  8451: sub get_group_membership {
                   8452:     my ($cdom,$cnum,$group) = @_;
                   8453:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8454: }
                   8455: 
                   8456: sub get_users_groups {
                   8457:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8458:     my @usersgroups;
1.683     raeburn  8459:     my $cachetime=1800;
                   8460: 
                   8461:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8462:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8463:     if (defined($cached)) {
1.734     albertel 8464:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8465:     } else {  
                   8466:         $grouplist = '';
1.816     raeburn  8467:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8468:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8469:         my $access_end = $env{'course.'.$courseid.
                   8470:                               '.default_enrollment_end_date'};
                   8471:         my $now = time;
                   8472:         foreach my $key (keys(%roleshash)) {
                   8473:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8474:                 my $group = $1;
                   8475:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8476:                     my $start = $2;
                   8477:                     my $end = $1;
                   8478:                     if ($start == -1) { next; } # deleted from group
                   8479:                     if (($start!=0) && ($start>$now)) { next; }
                   8480:                     if (($end!=0) && ($end<$now)) {
                   8481:                         if ($access_end && $access_end < $now) {
                   8482:                             if ($access_end - $end < 86400) {
                   8483:                                 push(@usersgroups,$group);
1.733     raeburn  8484:                             }
                   8485:                         }
1.817     raeburn  8486:                         next;
1.733     raeburn  8487:                     }
1.817     raeburn  8488:                     push(@usersgroups,$group);
1.683     raeburn  8489:                 }
                   8490:             }
                   8491:         }
1.817     raeburn  8492:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8493:         $grouplist = join(':',@usersgroups);
                   8494:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8495:     }
1.733     raeburn  8496:     return @usersgroups;
1.683     raeburn  8497: }
                   8498: 
                   8499: sub devalidate_getgroups_cache {
                   8500:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8501:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8502: 
1.683     raeburn  8503:     my $hashid="$udom:$uname:$courseid";
                   8504:     &devalidate_cache_new('getgroups',$hashid);
                   8505: }
                   8506: 
1.12      www      8507: # ------------------------------------------------------------------ Plain Text
                   8508: 
                   8509: sub plaintext {
1.988     raeburn  8510:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8511:     if ($short =~ m{^cr/}) {
1.758     albertel 8512: 	return (split('/',$short))[-1];
                   8513:     }
1.742     raeburn  8514:     if (!defined($cid)) {
                   8515:         $cid = $env{'request.course.id'};
                   8516:     }
                   8517:     my %rolenames = (
1.1008    raeburn  8518:                       Course    => 'std',
                   8519:                       Community => 'alt1',
1.1305    raeburn  8520:                       Placement => 'std',
1.742     raeburn  8521:                     );
1.1037    raeburn  8522:     if ($cid ne '') {
                   8523:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8524:             unless ($forcedefault) {
                   8525:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8526:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8527:                 return &Apache::lonlocal::mt($roletext);
                   8528:             }
                   8529:         }
                   8530:     }
                   8531:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8532:         (defined($rolenames{$type})) && 
                   8533:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8534:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8535:     } elsif ($cid ne '') {
                   8536:         my $crstype = $env{'course.'.$cid.'.type'};
                   8537:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8538:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8539:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8540:         }
1.742     raeburn  8541:     }
1.1037    raeburn  8542:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8543: }
                   8544: 
                   8545: # ----------------------------------------------------------------- Assign Role
                   8546: 
                   8547: sub assignrole {
1.957     raeburn  8548:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8549:         $context)=@_;
1.21      www      8550:     my $mrole;
                   8551:     if ($role =~ /^cr\//) {
1.393     www      8552:         my $cwosec=$url;
1.811     albertel 8553:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8554: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8555:            my $refused = 1;
                   8556:            if ($context eq 'requestcourses') {
                   8557:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8558:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8559:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8560:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8561:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8562:                            if ($crsenv{'internal.courseowner'} eq
                   8563:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8564:                                $refused = '';
                   8565:                            }
                   8566:                        }
                   8567:                    }
                   8568:                }
                   8569:            }
                   8570:            if ($refused) {
                   8571:                &logthis('Refused custom assignrole: '.
                   8572:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8573:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8574:                return 'refused';
                   8575:            }
1.104     www      8576:         }
1.21      www      8577:         $mrole='cr';
1.678     raeburn  8578:     } elsif ($role =~ /^gr\//) {
                   8579:         my $cwogrp=$url;
1.811     albertel 8580:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8581:         unless (&allowed('mdg',$cwogrp)) {
                   8582:             &logthis('Refused group assignrole: '.
                   8583:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8584:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8585:             return 'refused';
                   8586:         }
                   8587:         $mrole='gr';
1.21      www      8588:     } else {
1.82      www      8589:         my $cwosec=$url;
1.811     albertel 8590:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8591:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8592:             my $refused;
                   8593:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8594:                 if (!(&allowed('c'.$role,$url))) {
                   8595:                     $refused = 1;
                   8596:                 }
                   8597:             } else {
                   8598:                 $refused = 1;
                   8599:             }
1.947     raeburn  8600:             if ($refused) {
1.1045    raeburn  8601:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8602:                 if (!$selfenroll && $context eq 'course') {
                   8603:                     my %crsenv;
                   8604:                     if ($role eq 'cc' || $role eq 'co') {
                   8605:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8606:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8607:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8608:                                 if ($crsenv{'internal.courseowner'} eq 
                   8609:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8610:                                     $refused = '';
                   8611:                                 }
                   8612:                             }
                   8613:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8614:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8615:                                 if ($crsenv{'internal.courseowner'} eq 
                   8616:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8617:                                     $refused = '';
                   8618:                                 }
                   8619:                             }
                   8620:                         }
                   8621:                     }
                   8622:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8623:                     $refused = '';
1.1017    raeburn  8624:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8625:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8626:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8627:                         my $wrongcc;
                   8628:                         if ($cnum =~ /^$match_community$/) {
                   8629:                             $wrongcc = 1 if ($role eq 'cc');
                   8630:                         } else {
                   8631:                             $wrongcc = 1 if ($role eq 'co');
                   8632:                         }
                   8633:                         unless ($wrongcc) {
                   8634:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8635:                             if ($crsenv{'internal.courseowner'} eq 
                   8636:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8637:                                 $refused = '';
                   8638:                             }
1.1017    raeburn  8639:                         }
                   8640:                     }
1.1183    raeburn  8641:                 } elsif ($context eq 'requestauthor') {
                   8642:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8643:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8644:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8645:                             $refused = '';
                   8646:                         } else {
                   8647:                             my %domdefaults = &get_domain_defaults($udom);
                   8648:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8649:                                 my $checkbystatus;
                   8650:                                 if ($env{'user.adv'}) { 
                   8651:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8652:                                     if ($disposition eq 'automatic') {
                   8653:                                         $refused = '';
                   8654:                                     } elsif ($disposition eq '') {
                   8655:                                         $checkbystatus = 1;
                   8656:                                     } 
                   8657:                                 } else {
                   8658:                                     $checkbystatus = 1;
                   8659:                                 }
                   8660:                                 if ($checkbystatus) {
                   8661:                                     if ($env{'environment.inststatus'}) {
                   8662:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8663:                                         foreach my $type (@inststatuses) {
                   8664:                                             if (($type ne '') &&
                   8665:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8666:                                                 $refused = '';
                   8667:                                             }
                   8668:                                         }
                   8669:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8670:                                         $refused = '';
                   8671:                                     }
                   8672:                                 }
                   8673:                             }
                   8674:                         }
                   8675:                     }
1.1017    raeburn  8676:                 }
                   8677:                 if ($refused) {
1.947     raeburn  8678:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8679:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8680: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8681:                     return 'refused';
                   8682:                 }
1.932     raeburn  8683:             }
1.1131    raeburn  8684:         } elsif ($role eq 'au') {
                   8685:             if ($url ne '/'.$udom.'/') {
                   8686:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8687:                          ' to assign author role for '.$uname.':'.$udom.
                   8688:                          ' in domain: '.$url.' refused (wrong domain).');
                   8689:                 return 'refused';
                   8690:             }
1.104     www      8691:         }
1.21      www      8692:         $mrole=$role;
                   8693:     }
1.620     albertel 8694:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8695:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8696:     if ($end) { $command.='_'.$end; }
1.21      www      8697:     if ($start) {
                   8698: 	if ($end) { 
1.81      www      8699:            $command.='_'.$start; 
1.21      www      8700:         } else {
1.81      www      8701:            $command.='_0_'.$start;
1.21      www      8702:         }
                   8703:     }
1.739     raeburn  8704:     my $origstart = $start;
                   8705:     my $origend = $end;
1.957     raeburn  8706:     my $delflag;
1.357     www      8707: # actually delete
                   8708:     if ($deleteflag) {
1.373     www      8709: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8710: # modify command to delete the role
1.620     albertel 8711:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8712:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8713: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8714: # set start and finish to negative values for userrolelog
                   8715:            $start=-1;
                   8716:            $end=-1;
1.957     raeburn  8717:            $delflag = 1;
1.357     www      8718:         }
                   8719:     }
                   8720: # send command
1.349     www      8721:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8722: # log new user role if status is ok
1.349     www      8723:     if ($answer eq 'ok') {
1.663     raeburn  8724: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8725:         if (($role eq 'cc') || ($role eq 'in') ||
                   8726:             ($role eq 'ep') || ($role eq 'ad') ||
                   8727:             ($role eq 'ta') || ($role eq 'st') ||
                   8728:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8729:             ($role eq 'co')) {
1.1200    raeburn  8730: # for course roles, perform group memberships changes triggered by role change.
                   8731:             unless ($role =~ /^gr/) {
                   8732:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8733:                                                  $origstart,$selfenroll,$context);
                   8734:             }
1.1184    raeburn  8735:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8736:                            $selfenroll,$context);
                   8737:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8738:                  ($role eq 'au') || ($role eq 'dc')) {
                   8739:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8740:                            $context);
                   8741:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8742:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8743:                              $context); 
                   8744:         }
1.1053    raeburn  8745:         if ($role eq 'cc') {
                   8746:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8747:         }
1.349     www      8748:     }
                   8749:     return $answer;
1.169     harris41 8750: }
                   8751: 
1.1053    raeburn  8752: sub autoupdate_coowners {
                   8753:     my ($url,$end,$start,$uname,$udom) = @_;
                   8754:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8755:     if (($cdom ne '') && ($cnum ne '')) {
                   8756:         my $now = time;
                   8757:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8758:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8759:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8760:             my $instcode = $coursehash{'internal.coursecode'};
                   8761:             if ($instcode ne '') {
1.1056    raeburn  8762:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8763:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8764:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8765:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8766:                         if ($result eq 'valid') {
                   8767:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8768:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8769:                                     push(@newcoowners,$coowner);
                   8770:                                 }
                   8771:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8772:                                     push(@newcoowners,$uname.':'.$udom);
                   8773:                                 }
                   8774:                                 @newcoowners = sort(@newcoowners);
                   8775:                             } else {
                   8776:                                 push(@newcoowners,$uname.':'.$udom);
                   8777:                             }
                   8778:                         } else {
                   8779:                             if ($coursehash{'internal.co-owners'}) {
                   8780:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8781:                                     unless ($coowner eq $uname.':'.$udom) {
                   8782:                                         push(@newcoowners,$coowner);
                   8783:                                     }
                   8784:                                 }
                   8785:                                 unless (@newcoowners > 0) {
                   8786:                                     $delcoowners = 1;
                   8787:                                     $coowners = '';
                   8788:                                 }
                   8789:                             }
                   8790:                         }
                   8791:                         if (@newcoowners || $delcoowners) {
                   8792:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8793:                                             $delcoowners,@newcoowners);
                   8794:                         }
                   8795:                     }
                   8796:                 }
                   8797:             }
                   8798:         }
                   8799:     }
                   8800: }
                   8801: 
                   8802: sub store_coowners {
                   8803:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8804:     my $cid = $cdom.'_'.$cnum;
                   8805:     my ($coowners,$delresult,$putresult);
                   8806:     if (@newcoowners) {
                   8807:         $coowners = join(',',@newcoowners);
                   8808:         my %coownershash = (
                   8809:                             'internal.co-owners' => $coowners,
                   8810:                            );
                   8811:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8812:         if ($putresult eq 'ok') {
                   8813:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8814:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8815:             }
                   8816:         }
                   8817:     }
                   8818:     if ($delcoowners) {
                   8819:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8820:         if ($delresult eq 'ok') {
                   8821:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8822:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8823:             }
                   8824:         }
                   8825:     }
                   8826:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8827:         my %crsinfo =
                   8828:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8829:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8830:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8831:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8832:         }
                   8833:     }
                   8834: }
                   8835: 
1.169     harris41 8836: # -------------------------------------------------- Modify user authentication
1.197     www      8837: # Overrides without validation
                   8838: 
1.169     harris41 8839: sub modifyuserauth {
                   8840:     my ($udom,$uname,$umode,$upass)=@_;
                   8841:     my $uhome=&homeserver($uname,$udom);
1.197     www      8842:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8843:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8844:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8845:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8846:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8847: 		     &escape($upass),$uhome);
1.620     albertel 8848:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8849:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8850:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8851:     &log($udom,,$uname,$uhome,
1.620     albertel 8852:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8853:                                      $env{'user.name'}.', '.$umode.
1.197     www      8854:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8855:     unless ($reply eq 'ok') {
1.197     www      8856:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8857: 	return 'error: '.$reply;
                   8858:     }   
1.170     harris41 8859:     return 'ok';
1.80      www      8860: }
                   8861: 
1.81      www      8862: # --------------------------------------------------------------- Modify a user
1.80      www      8863: 
1.81      www      8864: sub modifyuser {
1.206     matthew  8865:     my ($udom,    $uname, $uid,
                   8866:         $umode,   $upass, $first,
                   8867:         $middle,  $last,  $gene,
1.1058    raeburn  8868:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8869:     $udom= &LONCAPA::clean_domain($udom);
                   8870:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8871:     my $showcandelete = 'none';
                   8872:     if (ref($candelete) eq 'ARRAY') {
                   8873:         if (@{$candelete} > 0) {
                   8874:             $showcandelete = join(', ',@{$candelete});
                   8875:         }
                   8876:     }
1.81      www      8877:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8878:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8879: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8880:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8881:                                      ' desiredhome not specified'). 
1.620     albertel 8882:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8883:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8884:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8885:     my $newuser;
                   8886:     if ($uhome eq 'no_host') {
                   8887:         $newuser = 1;
                   8888:     }
1.80      www      8889: # ----------------------------------------------------------------- Create User
1.406     albertel 8890:     if (($uhome eq 'no_host') && 
                   8891: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8892:         my $unhome='';
1.844     albertel 8893:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8894:             $unhome = $desiredhome;
1.620     albertel 8895: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8896: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8897:         } else { # load balancing routine for determining $unhome
1.81      www      8898:             my $loadm=10000000;
1.841     albertel 8899: 	    my %servers = &get_servers($udom,'library');
                   8900: 	    foreach my $tryserver (keys(%servers)) {
                   8901: 		my $answer=reply('load',$tryserver);
                   8902: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8903: 		    $loadm=$answer;
                   8904: 		    $unhome=$tryserver;
                   8905: 		}
1.80      www      8906: 	    }
                   8907:         }
                   8908:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8909: 	    return 'error: unable to find a home server for '.$uname.
                   8910:                    ' in domain '.$udom;
1.80      www      8911:         }
                   8912:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8913:                          &escape($upass),$unhome);
                   8914: 	unless ($reply eq 'ok') {
                   8915:             return 'error: '.$reply;
                   8916:         }   
1.230     stredwic 8917:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8918:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8919: 	    return 'error: unable verify users home machine.';
1.80      www      8920:         }
1.209     matthew  8921:     }   # End of creation of new user
1.80      www      8922: # ---------------------------------------------------------------------- Add ID
                   8923:     if ($uid) {
                   8924:        $uid=~tr/A-Z/a-z/;
                   8925:        my %uidhash=&idrget($udom,$uname);
1.196     www      8926:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8927:          && (!$forceid)) {
1.80      www      8928: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8929: 	      return 'error: user id "'.$uid.'" does not match '.
                   8930:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8931:           }
                   8932:        } else {
1.1300    raeburn  8933: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      8934:        }
                   8935:     }
                   8936: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8937:     my @tmp=&get('environment',
1.899     raeburn  8938: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8939:                     'permanentemail','inststatus'],
1.134     albertel 8940: 		   $udom,$uname);
1.1075    raeburn  8941:     my (%names,%oldnames);
1.313     matthew  8942:     if ($tmp[0] =~ m/^error:.*/) { 
                   8943:         %names=(); 
                   8944:     } else {
                   8945:         %names = @tmp;
1.1075    raeburn  8946:         %oldnames = %names;
1.313     matthew  8947:     }
1.388     www      8948: #
1.1058    raeburn  8949: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8950: # of users did not contain them), do not overwrite existing values
                   8951: # unless field is in $candelete array ref.  
                   8952: #
                   8953: 
                   8954:     my @fields = ('firstname','middlename','lastname','generation',
                   8955:                   'permanentemail','id');
                   8956:     my %newvalues;
                   8957:     if (ref($candelete) eq 'ARRAY') {
                   8958:         foreach my $field (@fields) {
                   8959:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8960:                 if ($field eq 'firstname') {
                   8961:                     $names{$field} = $first;
                   8962:                 } elsif ($field eq 'middlename') {
                   8963:                     $names{$field} = $middle;
                   8964:                 } elsif ($field eq 'lastname') {
                   8965:                     $names{$field} = $last;
                   8966:                 } elsif ($field eq 'generation') { 
                   8967:                     $names{$field} = $gene;
                   8968:                 } elsif ($field eq 'permanentemail') {
                   8969:                     $names{$field} = $email;
                   8970:                 } elsif ($field eq 'id') {
                   8971:                     $names{$field}  = $uid;
                   8972:                 }
                   8973:             }
                   8974:         }
                   8975:     }
1.388     www      8976:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8977:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8978:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8979:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8980:     if ($email) {
                   8981:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8982:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8983:     }
1.899     raeburn  8984:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8985:     if (defined($inststatus)) {
                   8986:         $names{'inststatus'} = '';
                   8987:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8988:         if (ref($usertypes) eq 'HASH') {
                   8989:             my @okstatuses; 
                   8990:             foreach my $item (split(/:/,$inststatus)) {
                   8991:                 if (defined($usertypes->{$item})) {
                   8992:                     push(@okstatuses,$item);  
                   8993:                 }
                   8994:             }
                   8995:             if (@okstatuses) {
                   8996:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8997:             }
                   8998:         }
                   8999:     }
1.1075    raeburn  9000:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9001:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9002:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9003:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9004:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9005:     } else {
                   9006:         $logmsg .= ' during self creation';
                   9007:     }
1.1075    raeburn  9008:     my $changed;
                   9009:     if ($newuser) {
                   9010:         $changed = 1;
                   9011:     } else {
                   9012:         foreach my $field (@fields) {
                   9013:             if ($names{$field} ne $oldnames{$field}) {
                   9014:                 $changed = 1;
                   9015:                 last;
                   9016:             }
                   9017:         }
                   9018:     }
                   9019:     unless ($changed) {
                   9020:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9021:         &logthis($logmsg);
                   9022:         return 'ok';
                   9023:     }
                   9024:     my $reply = &put('environment', \%names, $udom,$uname);
                   9025:     if ($reply ne 'ok') { 
                   9026:         return 'error: '.$reply;
                   9027:     }
1.1087    raeburn  9028:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9029:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9030:     }
1.1075    raeburn  9031:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9032:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9033:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9034:     &logthis($logmsg);
1.134     albertel 9035:     return 'ok';
1.80      www      9036: }
                   9037: 
1.81      www      9038: # -------------------------------------------------------------- Modify student
1.80      www      9039: 
1.81      www      9040: sub modifystudent {
                   9041:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9042:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  9043:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 9044:     if (!$cid) {
1.620     albertel 9045: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9046: 	    return 'not_in_class';
                   9047: 	}
1.80      www      9048:     }
                   9049: # --------------------------------------------------------------- Make the user
1.81      www      9050:     my $reply=&modifyuser
1.209     matthew  9051: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9052:          $desiredhome,$email,$inststatus);
1.80      www      9053:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9054:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9055:     # student's environment
1.297     matthew  9056:     $uid = undef if (!$forceid);
1.455     albertel 9057:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9058:                                         $gene,$usec,$end,$start,$type,$locktype,
                   9059:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  9060:     return $reply;
                   9061: }
                   9062: 
                   9063: sub modify_student_enrollment {
1.1216    raeburn  9064:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   9065:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 9066:     my ($cdom,$cnum,$chome);
                   9067:     if (!$cid) {
1.620     albertel 9068: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9069: 	    return 'not_in_class';
                   9070: 	}
1.620     albertel 9071: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9072: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9073:     } else {
                   9074: 	($cdom,$cnum)=split(/_/,$cid);
                   9075:     }
1.620     albertel 9076:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9077:     if (!$chome) {
1.457     raeburn  9078: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9079:     }
1.455     albertel 9080:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9081:     # Make sure the user exists
1.81      www      9082:     my $uhome=&homeserver($uname,$udom);
                   9083:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9084: 	return 'error: no such user';
                   9085:     }
1.297     matthew  9086:     # Get student data if we were not given enough information
                   9087:     if (!defined($first)  || $first  eq '' || 
                   9088:         !defined($last)   || $last   eq '' || 
                   9089:         !defined($uid)    || $uid    eq '' || 
                   9090:         !defined($middle) || $middle eq '' || 
                   9091:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9092:         # They did not supply us with enough data to enroll the student, so
                   9093:         # we need to pick up more information.
1.297     matthew  9094:         my %tmp = &get('environment',
1.294     matthew  9095:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9096:                        ,$udom,$uname);
                   9097: 
1.800     albertel 9098:         #foreach my $key (keys(%tmp)) {
                   9099:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9100:         #}
1.294     matthew  9101:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9102:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9103:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9104:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9105:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9106:     }
1.556     albertel 9107:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9108:     my $user = "$uname:$udom";
                   9109:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9110:     my $reply=cput('classlist',
1.1148    raeburn  9111: 		   {$user => 
1.1216    raeburn  9112: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 9113: 		   $cdom,$cnum);
1.1148    raeburn  9114:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9115:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9116:     } else { 
1.81      www      9117: 	return 'error: '.$reply;
                   9118:     }
1.297     matthew  9119:     # Add student role to user
1.83      www      9120:     my $uurl='/'.$cid;
1.81      www      9121:     $uurl=~s/\_/\//g;
                   9122:     if ($usec) {
                   9123: 	$uurl.='/'.$usec;
                   9124:     }
1.1148    raeburn  9125:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9126:                              $selfenroll,$context);
                   9127:     if ($result ne 'ok') {
                   9128:         if ($old_entry{$user} ne '') {
                   9129:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9130:         } else {
                   9131:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9132:         }
                   9133:     }
                   9134:     return $result; 
1.21      www      9135: }
                   9136: 
1.556     albertel 9137: sub format_name {
                   9138:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9139:     my $name;
                   9140:     if ($first ne 'lastname') {
                   9141: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9142:     } else {
                   9143: 	if ($lastname=~/\S/) {
                   9144: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9145: 	    $name=~s/\s+,/,/;
                   9146: 	} else {
                   9147: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9148: 	}
                   9149:     }
                   9150:     $name=~s/^\s+//;
                   9151:     $name=~s/\s+$//;
                   9152:     $name=~s/\s+/ /g;
                   9153:     return $name;
                   9154: }
                   9155: 
1.84      www      9156: # ------------------------------------------------- Write to course preferences
                   9157: 
                   9158: sub writecoursepref {
                   9159:     my ($courseid,%prefs)=@_;
                   9160:     $courseid=~s/^\///;
                   9161:     $courseid=~s/\_/\//g;
                   9162:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9163:     my $chome=homeserver($cnum,$cdomain);
                   9164:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9165: 	return 'error: no such course';
                   9166:     }
                   9167:     my $cstring='';
1.800     albertel 9168:     foreach my $pref (keys(%prefs)) {
                   9169: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9170:     }
1.84      www      9171:     $cstring=~s/\&$//;
                   9172:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9173: }
                   9174: 
                   9175: # ---------------------------------------------------------- Make/modify course
                   9176: 
                   9177: sub createcourse {
1.741     raeburn  9178:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9179:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9180:     $url=&declutter($url);
                   9181:     my $cid='';
1.1028    raeburn  9182:     if ($context eq 'requestcourses') {
                   9183:         my $can_create = 0;
                   9184:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9185:         if ($udom eq $ownerdom) {
                   9186:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9187:                                   $context)) {
                   9188:                 $can_create = 1;
                   9189:             }
                   9190:         } else {
                   9191:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9192:                                            $category);
                   9193:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9194:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9195:                 if (@curr > 0) {
                   9196:                     my @options = qw(approval validate autolimit);
                   9197:                     my $optregex = join('|',@options);
                   9198:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9199:                         $can_create = 1;
                   9200:                     }
                   9201:                 }
                   9202:             }
                   9203:         }
                   9204:         if ($can_create) {
                   9205:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9206:                 unless (&allowed('ccc',$udom)) {
                   9207:                     return 'refused'; 
                   9208:                 }
1.1017    raeburn  9209:             }
                   9210:         } else {
                   9211:             return 'refused';
                   9212:         }
1.1028    raeburn  9213:     } elsif (!&allowed('ccc',$udom)) {
                   9214:         return 'refused';
1.84      www      9215:     }
1.1011    raeburn  9216: # --------------------------------------------------------------- Get Unique ID
                   9217:     my $uname;
                   9218:     if ($cnum =~ /^$match_courseid$/) {
                   9219:         my $chome=&homeserver($cnum,$udom,'true');
                   9220:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9221:             $uname = $cnum;
                   9222:         } else {
1.1038    raeburn  9223:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9224:         }
                   9225:     } else {
1.1038    raeburn  9226:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9227:     }
                   9228:     return $uname if ($uname =~ /^error/);
                   9229: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9230:     if (!defined($course_server)) {
                   9231:         if (defined(&domain($udom,'primary'))) {
                   9232:             $course_server = &domain($udom,'primary');
                   9233:         } else {
                   9234:             $course_server = $env{'user.home'}; 
                   9235:         }
                   9236:     }
                   9237:     my %host_servers =
                   9238:         &Apache::lonnet::get_servers($udom,'library');
                   9239:     unless ($host_servers{$course_server}) {
                   9240:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9241:     }
1.84      www      9242: # ------------------------------------------------------------- Make the course
                   9243:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9244:                       $course_server);
1.84      www      9245:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9246:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9247:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9248: 	return 'error: no such course';
                   9249:     }
1.271     www      9250: # ----------------------------------------------------------------- Course made
1.516     raeburn  9251: # log existence
1.1029    raeburn  9252:     my $now = time;
1.918     raeburn  9253:     my $newcourse = {
                   9254:                     $udom.'_'.$uname => {
1.921     raeburn  9255:                                      description => $description,
                   9256:                                      inst_code   => $inst_code,
                   9257:                                      owner       => $course_owner,
                   9258:                                      type        => $crstype,
1.1029    raeburn  9259:                                      creator     => $env{'user.name'}.':'.
                   9260:                                                     $env{'user.domain'},
                   9261:                                      created     => $now,
                   9262:                                      context     => $context,
1.918     raeburn  9263:                                                 },
                   9264:                     };
1.921     raeburn  9265:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9266: # set toplevel url
1.271     www      9267:     my $topurl=$url;
                   9268:     unless ($nonstandard) {
                   9269: # ------------------------------------------ For standard courses, make top url
                   9270:         my $mapurl=&clutter($url);
1.278     www      9271:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9272:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9273: <map>
                   9274: <resource id="1" type="start"></resource>
                   9275: <resource id="2" src="$mapurl"></resource>
                   9276: <resource id="3" type="finish"></resource>
                   9277: <link index="1" from="1" to="2"></link>
                   9278: <link index="2" from="2" to="3"></link>
                   9279: </map>
                   9280: ENDINITMAP
                   9281:         $topurl=&declutter(
1.638     albertel 9282:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9283:                           );
                   9284:     }
                   9285: # ----------------------------------------------------------- Write preferences
1.84      www      9286:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9287:                      ('description'              => $description,
                   9288:                       'url'                      => $topurl,
                   9289:                       'internal.creator'         => $env{'user.name'}.':'.
                   9290:                                                     $env{'user.domain'},
                   9291:                       'internal.created'         => $now,
                   9292:                       'internal.creationcontext' => $context)
                   9293:                     );
1.84      www      9294:     return '/'.$udom.'/'.$uname;
                   9295: }
                   9296: 
1.1011    raeburn  9297: # ------------------------------------------------------------------- Create ID
                   9298: sub generate_coursenum {
1.1038    raeburn  9299:     my ($udom,$crstype) = @_;
1.1011    raeburn  9300:     my $domdesc = &domain($udom);
                   9301:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9302:     my $first;
                   9303:     if ($crstype eq 'Community') {
                   9304:         $first = '0';
                   9305:     } else {
                   9306:         $first = int(1+rand(9)); 
                   9307:     } 
                   9308:     my $uname=$first.
1.1011    raeburn  9309:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9310:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9311:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9312: # ----------------------------------------------- Make sure that does not exist
                   9313:     my $uhome=&homeserver($uname,$udom,'true');
                   9314:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9315:         if ($crstype eq 'Community') {
                   9316:             $first = '0';
                   9317:         } else {
                   9318:             $first = int(1+rand(9));
                   9319:         }
                   9320:         $uname=$first.
1.1011    raeburn  9321:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9322:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9323:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9324:         $uhome=&homeserver($uname,$udom,'true');
                   9325:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9326:             return 'error: unable to generate unique course-ID';
                   9327:         }
                   9328:     }
                   9329:     return $uname;
                   9330: }
                   9331: 
1.813     albertel 9332: sub is_course {
1.1167    droeschl 9333:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9334:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9335: 
                   9336:     return unless $cdom and $cnum;
                   9337: 
                   9338:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9339:         '.');
                   9340: 
1.1219    raeburn  9341:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9342:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9343: }
                   9344: 
1.1015    raeburn  9345: sub store_userdata {
                   9346:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9347:     my $result;
1.1016    raeburn  9348:     if ($datakey ne '') {
1.1013    raeburn  9349:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9350:             if ($udom eq '' || $uname eq '') {
                   9351:                 $udom = $env{'user.domain'};
                   9352:                 $uname = $env{'user.name'};
                   9353:             }
                   9354:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9355:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9356:                 $result = 'error: no_host';
                   9357:             } else {
                   9358:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9359:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9360: 
                   9361:                 my $namevalue='';
                   9362:                 foreach my $key (keys(%{$storehash})) {
                   9363:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9364:                 }
                   9365:                 $namevalue=~s/\&$//;
1.1224    raeburn  9366:                 unless ($namespace eq 'courserequests') {
                   9367:                     $datakey = &escape($datakey);
                   9368:                 }
1.1105    raeburn  9369:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9370:                                   $namevalue,$uhome);
1.1013    raeburn  9371:             }
                   9372:         } else {
                   9373:             $result = 'error: data to store was not a hash reference'; 
                   9374:         }
                   9375:     } else {
                   9376:         $result= 'error: invalid requestkey'; 
                   9377:     }
                   9378:     return $result;
                   9379: }
                   9380: 
1.21      www      9381: # ---------------------------------------------------------- Assign Custom Role
                   9382: 
                   9383: sub assigncustomrole {
1.957     raeburn  9384:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9385:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9386:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9387: }
                   9388: 
                   9389: # ----------------------------------------------------------------- Revoke Role
                   9390: 
                   9391: sub revokerole {
1.957     raeburn  9392:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9393:     my $now=time;
1.965     raeburn  9394:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9395: }
                   9396: 
                   9397: # ---------------------------------------------------------- Revoke Custom Role
                   9398: 
                   9399: sub revokecustomrole {
1.957     raeburn  9400:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9401:     my $now=time;
1.357     www      9402:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9403:            $deleteflag,$selfenroll,$context);
1.17      www      9404: }
                   9405: 
1.533     banghart 9406: # ------------------------------------------------------------ Disk usage
1.535     albertel 9407: sub diskusage {
1.955     raeburn  9408:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9409:     $directorypath =~ s/\/$//;
                   9410:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9411:                        .&escape($getpropath).':'.&escape($uname).':'
                   9412:                        .&escape($udom),homeserver($uname,$udom));
                   9413:     if ($listing eq 'unknown_cmd') {
                   9414:         if ($getpropath) {
                   9415:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9416:         }
                   9417:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9418:     }
1.514     albertel 9419:     return $listing;
1.512     banghart 9420: }
                   9421: 
1.566     banghart 9422: sub is_locked {
1.1096    raeburn  9423:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9424:     my @check;
                   9425:     my $is_locked;
1.1093    raeburn  9426:     push (@check,$file_name);
1.613     albertel 9427:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9428: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9429:     my ($tmp)=keys(%locked);
                   9430:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9431:     
1.566     banghart 9432:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9433:         $is_locked = 'false';
                   9434:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9435:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9436:                $is_locked = 'true';
1.1096    raeburn  9437:                if (ref($which) eq 'ARRAY') {
                   9438:                    push(@{$which},$entry);
                   9439:                } else {
                   9440:                    last;
                   9441:                }
1.745     raeburn  9442:            }
                   9443:        }
1.566     banghart 9444:     } else {
                   9445:         $is_locked = 'false';
                   9446:     }
1.1093    raeburn  9447:     return $is_locked;
1.566     banghart 9448: }
                   9449: 
1.759     albertel 9450: sub declutter_portfile {
                   9451:     my ($file) = @_;
1.833     albertel 9452:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9453:     return $file;
                   9454: }
                   9455: 
1.559     banghart 9456: # ------------------------------------------------------------- Mark as Read Only
                   9457: 
                   9458: sub mark_as_readonly {
                   9459:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9460:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9461:     my ($tmp)=keys(%current_permissions);
                   9462:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9463:     foreach my $file (@{$files}) {
1.759     albertel 9464: 	$file = &declutter_portfile($file);
1.561     banghart 9465:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9466:     }
1.613     albertel 9467:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9468:     return;
                   9469: }
                   9470: 
1.572     banghart 9471: # ------------------------------------------------------------Save Selected Files
                   9472: 
                   9473: sub save_selected_files {
                   9474:     my ($user, $path, @files) = @_;
                   9475:     my $filename = $user."savedfiles";
1.573     banghart 9476:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9477:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9478:     foreach my $file (@files) {
1.620     albertel 9479:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9480:     }
                   9481:     foreach my $file (@other_files) {
1.574     banghart 9482:         print (OUT $file."\n");
1.572     banghart 9483:     }
1.574     banghart 9484:     close (OUT);
1.572     banghart 9485:     return 'ok';
                   9486: }
                   9487: 
1.574     banghart 9488: sub clear_selected_files {
                   9489:     my ($user) = @_;
                   9490:     my $filename = $user."savedfiles";
1.1117    foxr     9491:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9492:     print (OUT undef);
                   9493:     close (OUT);
                   9494:     return ("ok");    
                   9495: }
                   9496: 
1.572     banghart 9497: sub files_in_path {
                   9498:     my ($user, $path) = @_;
                   9499:     my $filename = $user."savedfiles";
                   9500:     my %return_files;
1.1117    foxr     9501:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9502:     while (my $line_in = <IN>) {
1.574     banghart 9503:         chomp ($line_in);
                   9504:         my @paths_and_file = split (m!/!, $line_in);
                   9505:         my $file_part = pop (@paths_and_file);
                   9506:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9507:         $path_part.='/';
                   9508:         my $path_and_file = $path_part.$file_part;
                   9509:         if ($path_part eq $path) {
                   9510:             $return_files{$file_part}= 'selected';
                   9511:         }
                   9512:     }
1.574     banghart 9513:     close (IN);
                   9514:     return (\%return_files);
1.572     banghart 9515: }
                   9516: 
                   9517: # called in portfolio select mode, to show files selected NOT in current directory
                   9518: sub files_not_in_path {
                   9519:     my ($user, $path) = @_;
                   9520:     my $filename = $user."savedfiles";
                   9521:     my @return_files;
                   9522:     my $path_part;
1.1117    foxr     9523:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9524:     while (my $line = <IN>) {
1.572     banghart 9525:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9526:         my @paths_and_file = split(m|/|, $line);
                   9527:         my $file_part = pop(@paths_and_file);
                   9528:         chomp($file_part);
                   9529:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9530:         $path_part .= '/';
                   9531:         my $path_and_file = $path_part.$file_part;
                   9532:         if ($path_part ne $path) {
1.800     albertel 9533:             push(@return_files, ($path_and_file));
1.572     banghart 9534:         }
                   9535:     }
1.800     albertel 9536:     close(OUT);
1.574     banghart 9537:     return (@return_files);
1.572     banghart 9538: }
                   9539: 
1.1273    raeburn  9540: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9541:  
                   9542: sub portfiles_versioning {
                   9543:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9544:     my $portfolio_root = '/userfiles/portfolio';
                   9545:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9546:     foreach my $file (@{$portfiles}) {
                   9547:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9548:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9549:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9550:         my $getpropath = 1;
                   9551:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9552:                                              $stu_name,$getpropath);
                   9553:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9554:         my $new_answer = 
                   9555:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9556:         if ($new_answer ne 'problem getting file') {
                   9557:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9558:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9559:                               [$symb,$env{'request.course.id'},'graded']);
                   9560:         }
                   9561:     }
                   9562: }
                   9563: 
                   9564: sub get_next_version {
                   9565:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9566:     my $version;
                   9567:     if (ref($dir_list) eq 'ARRAY') {
                   9568:         foreach my $row (@{$dir_list}) {
                   9569:             my ($file) = split(/\&/,$row,2);
                   9570:             my ($file_name,$file_version,$file_ext) =
                   9571:                 &file_name_version_ext($file);
                   9572:             if (($file_name eq $answer_name) &&
                   9573:                 ($file_ext eq $answer_ext)) {
                   9574:                      # gets here if filename and extension match,
                   9575:                      # regardless of version
                   9576:                 if ($file_version ne '') {
                   9577:                     # a versioned file is found  so save it for later
                   9578:                     if ($file_version > $version) {
                   9579:                         $version = $file_version;
                   9580:                     }
                   9581:                 }
                   9582:             }
                   9583:         }
                   9584:     }
                   9585:     $version ++;
                   9586:     return($version);
                   9587: }
                   9588: 
                   9589: sub version_selected_portfile {
                   9590:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9591:     my ($answer_name,$answer_ver,$answer_ext) =
                   9592:         &file_name_version_ext($file_name);
                   9593:     my $new_answer;
                   9594:     $env{'form.copy'} =
                   9595:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9596:     if($env{'form.copy'} eq '-1') {
                   9597:         $new_answer = 'problem getting file';
                   9598:     } else {
                   9599:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9600:         my $copy_result = 
                   9601:             &finishuserfileupload($stu_name,$domain,'copy',
                   9602:                                   '/portfolio'.$directory.$new_answer);
                   9603:     }
                   9604:     undef($env{'form.copy'});
                   9605:     return ($new_answer);
                   9606: }
                   9607: 
                   9608: sub file_name_version_ext {
                   9609:     my ($file)=@_;
                   9610:     my @file_parts = split(/\./, $file);
                   9611:     my ($name,$version,$ext);
                   9612:     if (@file_parts > 1) {
                   9613:         $ext=pop(@file_parts);
                   9614:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9615:             $version=pop(@file_parts);
                   9616:         }
                   9617:         $name=join('.',@file_parts);
                   9618:     } else {
                   9619:         $name=join('.',@file_parts);
                   9620:     }
                   9621:     return($name,$version,$ext);
                   9622: }
                   9623: 
1.745     raeburn  9624: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9625: 
1.745     raeburn  9626: sub get_portfile_permissions {
                   9627:     my ($domain,$user) = @_;
1.613     albertel 9628:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9629:     my ($tmp)=keys(%current_permissions);
                   9630:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9631:     return \%current_permissions;
                   9632: }
                   9633: 
                   9634: #---------------------------------------------Get portfolio file access controls
                   9635: 
1.749     raeburn  9636: sub get_access_controls {
1.745     raeburn  9637:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9638:     my %access;
                   9639:     my $real_file = $file;
                   9640:     $file =~ s/\.meta$//;
1.745     raeburn  9641:     if (defined($file)) {
1.749     raeburn  9642:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9643:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9644:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9645:             }
                   9646:         }
1.745     raeburn  9647:     } else {
1.749     raeburn  9648:         foreach my $key (keys(%{$current_permissions})) {
                   9649:             if ($key =~ /\0accesscontrol$/) {
                   9650:                 if (defined($group)) {
                   9651:                     if ($key !~ m-^\Q$group\E/-) {
                   9652:                         next;
                   9653:                     }
                   9654:                 }
                   9655:                 my ($fullpath) = split(/\0/,$key);
                   9656:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9657:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9658:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9659:                     }
                   9660:                 }
                   9661:             }
                   9662:         }
                   9663:     }
                   9664:     return %access;
                   9665: }
                   9666: 
                   9667: sub modify_access_controls {
                   9668:     my ($file_name,$changes,$domain,$user)=@_;
                   9669:     my ($outcome,$deloutcome);
                   9670:     my %store_permissions;
                   9671:     my %new_values;
                   9672:     my %new_control;
                   9673:     my %translation;
                   9674:     my @deletions = ();
                   9675:     my $now = time;
                   9676:     if (exists($$changes{'activate'})) {
                   9677:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9678:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9679:             my $numnew = scalar(@newitems);
                   9680:             for (my $i=0; $i<$numnew; $i++) {
                   9681:                 my $newkey = $newitems[$i];
                   9682:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9683:                 if ($newkey =~ /^\d+:/) { 
                   9684:                     $newkey =~ s/^(\d+)/$newid/;
                   9685:                     $translation{$1} = $newid;
                   9686:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9687:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9688:                     $translation{$1} = $newid;
                   9689:                 }
1.749     raeburn  9690:                 $new_values{$file_name."\0".$newkey} = 
                   9691:                                           $$changes{'activate'}{$newitems[$i]};
                   9692:                 $new_control{$newkey} = $now;
                   9693:             }
                   9694:         }
                   9695:     }
                   9696:     my %todelete;
                   9697:     my %changed_items;
                   9698:     foreach my $action ('delete','update') {
                   9699:         if (exists($$changes{$action})) {
                   9700:             if (ref($$changes{$action}) eq 'HASH') {
                   9701:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9702:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9703:                     if ($action eq 'delete') { 
                   9704:                         $todelete{$itemnum} = 1;
                   9705:                     } else {
                   9706:                         $changed_items{$itemnum} = $key;
                   9707:                     }
                   9708:                 }
1.745     raeburn  9709:             }
                   9710:         }
1.749     raeburn  9711:     }
                   9712:     # get lock on access controls for file.
                   9713:     my $lockhash = {
                   9714:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9715:                                                        ':'.$env{'user.domain'},
                   9716:                    }; 
                   9717:     my $tries = 0;
                   9718:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9719:    
1.1288    damieng  9720:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9721:         $tries ++;
1.1289    damieng  9722:         sleep(0.1);
1.749     raeburn  9723:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9724:     }
                   9725:     if ($gotlock eq 'ok') {
                   9726:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9727:         my ($tmp)=keys(%curr_permissions);
                   9728:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9729:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9730:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9731:             if (ref($curr_controls) eq 'HASH') {
                   9732:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9733:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9734:                     if (defined($todelete{$itemnum})) {
                   9735:                         push(@deletions,$file_name."\0".$control_item);
                   9736:                     } else {
                   9737:                         if (defined($changed_items{$itemnum})) {
                   9738:                             $new_control{$changed_items{$itemnum}} = $now;
                   9739:                             push(@deletions,$file_name."\0".$control_item);
                   9740:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9741:                         } else {
                   9742:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9743:                         }
                   9744:                     }
1.745     raeburn  9745:                 }
                   9746:             }
                   9747:         }
1.970     raeburn  9748:         my ($group);
                   9749:         if (&is_course($domain,$user)) {
                   9750:             ($group,my $file) = split(/\//,$file_name,2);
                   9751:         }
1.749     raeburn  9752:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9753:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9754:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9755:         #  remove lock
                   9756:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9757:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9758:         my $sqlresult =
1.970     raeburn  9759:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9760:                                     $group);
1.749     raeburn  9761:     } else {
                   9762:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9763:     }
1.749     raeburn  9764:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9765: }
                   9766: 
1.827     raeburn  9767: sub make_public_indefinitely {
1.1271    raeburn  9768:     my (@requrl) = @_;
                   9769:     return &automated_portfile_access('public',\@requrl);
                   9770: }
                   9771: 
                   9772: sub automated_portfile_access {
                   9773:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9774:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9775:         return 'invalid';
                   9776:     }
1.1271    raeburn  9777:     my %urls;
                   9778:     if (ref($addsref) eq 'ARRAY') {
                   9779:         foreach my $requrl (@{$addsref}) {
                   9780:             if (&is_portfolio_url($requrl)) {
                   9781:                 unless (exists($urls{$requrl})) {
                   9782:                     $urls{$requrl} = 'add';
                   9783:                 }
                   9784:             }
                   9785:         }
                   9786:     }
                   9787:     if (ref($delsref) eq 'ARRAY') {
                   9788:         foreach my $requrl (@{$delsref}) { 
                   9789:             if (&is_portfolio_url($requrl)) {
                   9790:                 unless (exists($urls{$requrl})) {
                   9791:                     $urls{$requrl} = 'delete'; 
                   9792:                 }
                   9793:             }
                   9794:         }
                   9795:     }
                   9796:     unless (keys(%urls)) {
                   9797:         return 'invalid';
                   9798:     }
                   9799:     my $ip;
                   9800:     if ($accesstype eq 'ip') {
                   9801:         if (ref($info) eq 'HASH') {
                   9802:             if ($info->{'ip'} ne '') {
                   9803:                 $ip = $info->{'ip'};
                   9804:             }
                   9805:         }
                   9806:         if ($ip eq '') {
                   9807:             return 'invalid';
                   9808:         }
                   9809:     }
                   9810:     my $errors;
1.827     raeburn  9811:     my $now = time;
1.1271    raeburn  9812:     my %current_perms;
                   9813:     foreach my $requrl (sort(keys(%urls))) {
                   9814:         my $action;
                   9815:         if ($urls{$requrl} eq 'add') {
                   9816:             $action = 'activate';
                   9817:         } else {
                   9818:             $action = 'none';
                   9819:         }
                   9820:         my $aclnum = 0;
1.827     raeburn  9821:         my (undef,$udom,$unum,$file_name,$group) =
                   9822:             &parse_portfolio_url($requrl);
1.1271    raeburn  9823:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9824:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9825:         }
                   9826:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9827:                                                    $group,$file_name);
                   9828:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9829:             my ($num,$scope,$end,$start) = 
                   9830:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9831:             if ($scope eq $accesstype) {
                   9832:                 if (($start <= $now) && ($end == 0)) {
                   9833:                     if ($accesstype eq 'ip') {
                   9834:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9835:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9836:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9837:                                     if ($urls{$requrl} eq 'add') {
                   9838:                                         $action = 'none';
                   9839:                                         last;
                   9840:                                     } else {
                   9841:                                         $action = 'delete';
                   9842:                                         $aclnum = $num;
                   9843:                                         last;
                   9844:                                     }
                   9845:                                 }
                   9846:                             }
                   9847:                         }
                   9848:                     } elsif ($accesstype eq 'public') {
                   9849:                         if ($urls{$requrl} eq 'add') {
                   9850:                             $action = 'none';
                   9851:                             last;
                   9852:                         } else {
                   9853:                             $action = 'delete';
                   9854:                             $aclnum = $num;
                   9855:                             last;
                   9856:                         }
                   9857:                     }
                   9858:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9859:                     $action = 'update';
                   9860:                     $aclnum = $num;
1.1271    raeburn  9861:                     last;
1.827     raeburn  9862:                 }
                   9863:             }
                   9864:         }
                   9865:         if ($action eq 'none') {
1.1271    raeburn  9866:             next;
1.827     raeburn  9867:         } else {
                   9868:             my %changes;
                   9869:             my $newend = 0;
                   9870:             my $newstart = $now;
1.1271    raeburn  9871:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9872:             $changes{$action}{$newkey} = {
1.1271    raeburn  9873:                 type => $accesstype,
1.827     raeburn  9874:                 time => {
                   9875:                     start => $newstart,
                   9876:                     end   => $newend,
                   9877:                 },
                   9878:             };
1.1271    raeburn  9879:             if ($accesstype eq 'ip') {
                   9880:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9881:             }
1.827     raeburn  9882:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9883:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9884:             unless ($outcome eq 'ok') {
                   9885:                 $errors .= $outcome.' ';
                   9886:             }
1.827     raeburn  9887:         }
1.1271    raeburn  9888:     }
                   9889:     if ($errors) {
                   9890:         $errors =~ s/\s$//;
                   9891:         return $errors;
1.827     raeburn  9892:     } else {
1.1271    raeburn  9893:         return 'ok';
1.827     raeburn  9894:     }
                   9895: }
                   9896: 
1.745     raeburn  9897: #------------------------------------------------------Get Marked as Read Only
                   9898: 
                   9899: sub get_marked_as_readonly {
                   9900:     my ($domain,$user,$what,$group) = @_;
                   9901:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9902:     my @readonly_files;
1.629     banghart 9903:     my $cmp1=$what;
                   9904:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9905:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9906:         if (defined($group)) {
                   9907:             if ($file_name !~ m-^\Q$group\E/-) {
                   9908:                 next;
                   9909:             }
                   9910:         }
1.561     banghart 9911:         if (ref($value) eq "ARRAY"){
                   9912:             foreach my $stored_what (@{$value}) {
1.629     banghart 9913:                 my $cmp2=$stored_what;
1.759     albertel 9914:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9915:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9916:                 }
1.629     banghart 9917:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9918:                     push(@readonly_files, $file_name);
1.745     raeburn  9919:                     last;
1.563     banghart 9920:                 } elsif (!defined($what)) {
                   9921:                     push(@readonly_files, $file_name);
1.745     raeburn  9922:                     last;
1.561     banghart 9923:                 }
                   9924:             }
1.745     raeburn  9925:         }
1.561     banghart 9926:     }
                   9927:     return @readonly_files;
                   9928: }
1.577     banghart 9929: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9930: 
1.577     banghart 9931: sub get_marked_as_readonly_hash {
1.745     raeburn  9932:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9933:     my %readonly_files;
1.745     raeburn  9934:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9935:         if (defined($group)) {
                   9936:             if ($file_name !~ m-^\Q$group\E/-) {
                   9937:                 next;
                   9938:             }
                   9939:         }
1.577     banghart 9940:         if (ref($value) eq "ARRAY"){
                   9941:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9942:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9943:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9944:                         if ($lock_descriptor eq 'graded') {
                   9945:                             $readonly_files{$file_name} = 'graded';
                   9946:                         } elsif ($lock_descriptor eq 'handback') {
                   9947:                             $readonly_files{$file_name} = 'handback';
                   9948:                         } else {
                   9949:                             if (!exists($readonly_files{$file_name})) {
                   9950:                                 $readonly_files{$file_name} = 'locked';
                   9951:                             }
                   9952:                         }
1.745     raeburn  9953:                     }
1.750     banghart 9954:                 } 
1.577     banghart 9955:             }
                   9956:         } 
                   9957:     }
                   9958:     return %readonly_files;
                   9959: }
1.559     banghart 9960: # ------------------------------------------------------------ Unmark as Read Only
                   9961: 
                   9962: sub unmark_as_readonly {
1.629     banghart 9963:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9964:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9965:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9966:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9967:     my $symb_crs = $what;
                   9968:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9969:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9970:     my ($tmp)=keys(%current_permissions);
                   9971:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9972:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9973:     foreach my $file (@readonly_files) {
1.759     albertel 9974: 	my $clean_file = &declutter_portfile($file);
                   9975: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9976: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9977:         my @new_locks;
                   9978:         my @del_keys;
                   9979:         if (ref($current_locks) eq "ARRAY"){
                   9980:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9981:                 my $compare=$locker;
1.749     raeburn  9982:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9983:                     $compare=join('',@{$locker});
1.746     raeburn  9984:                     if ($compare ne $symb_crs) {
                   9985:                         push(@new_locks, $locker);
                   9986:                     }
1.563     banghart 9987:                 }
                   9988:             }
1.650     albertel 9989:             if (scalar(@new_locks) > 0) {
1.563     banghart 9990:                 $current_permissions{$file} = \@new_locks;
                   9991:             } else {
                   9992:                 push(@del_keys, $file);
1.613     albertel 9993:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9994:                 delete($current_permissions{$file});
1.563     banghart 9995:             }
                   9996:         }
1.561     banghart 9997:     }
1.613     albertel 9998:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9999:     return;
                   10000: }
1.512     banghart 10001: 
1.17      www      10002: # ------------------------------------------------------------ Directory lister
                   10003: 
                   10004: sub dirlist {
1.955     raeburn  10005:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10006:     $uri=~s/^\///;
                   10007:     $uri=~s/\/$//;
1.253     stredwic 10008:     my ($udom, $uname);
1.955     raeburn  10009:     if ($getuserdir) {
1.253     stredwic 10010:         $udom = $userdomain;
                   10011:         $uname = $username;
1.955     raeburn  10012:     } else {
                   10013:         (undef,$udom,$uname)=split(/\//,$uri);
                   10014:         if(defined($userdomain)) {
                   10015:             $udom = $userdomain;
                   10016:         }
                   10017:         if(defined($username)) {
                   10018:             $uname = $username;
                   10019:         }
1.253     stredwic 10020:     }
1.955     raeburn  10021:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10022: 
1.955     raeburn  10023:     $dirRoot = $perlvar{'lonDocRoot'};
                   10024:     if (defined($getpropath)) {
                   10025:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10026:         $dirRoot =~ s/\/$//;
1.955     raeburn  10027:     } elsif (defined($getuserdir)) {
                   10028:         my $subdir=$uname.'__';
                   10029:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10030:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10031:                    ."/$udom/$subdir/$uname";
                   10032:     } elsif (defined($alternateRoot)) {
                   10033:         $dirRoot = $alternateRoot;
1.751     banghart 10034:     }
1.253     stredwic 10035: 
                   10036:     if($udom) {
                   10037:         if($uname) {
1.1135    raeburn  10038:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10039:             if ($uhome eq 'no_host') {
                   10040:                 return ([],'no_host');
                   10041:             }
1.955     raeburn  10042:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10043:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10044:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10045:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10046:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10047:             } else {
                   10048:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10049:             }
1.605     matthew  10050:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10051:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10052:                 @listing_results = split(/:/,$listing);
                   10053:             } else {
                   10054:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10055:             }
1.1135    raeburn  10056:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10057:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10058:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10059:                 return ([],$listing);
                   10060:             } else {
                   10061:                 return (\@listing_results);
1.1135    raeburn  10062:             }
1.955     raeburn  10063:         } elsif(!$alternateRoot) {
1.1136    raeburn  10064:             my (%allusers,%listerror);
1.841     albertel 10065: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10066:  	    foreach my $tryserver (keys(%servers)) {
                   10067:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10068:                                   &escape($udom),$tryserver);
                   10069:                 if ($listing eq 'unknown_cmd') {
                   10070: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10071: 				      $udom, $tryserver);
                   10072:                 } else {
                   10073:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10074:                 }
1.841     albertel 10075: 		if ($listing eq 'unknown_cmd') {
                   10076: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10077: 				      $udom, $tryserver);
                   10078: 		    @listing_results = split(/:/,$listing);
                   10079: 		} else {
                   10080: 		    @listing_results =
                   10081: 			map { &unescape($_); } split(/:/,$listing);
                   10082: 		}
1.1136    raeburn  10083:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10084:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10085:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10086:                     $listerror{$tryserver} = $listing;
                   10087:                 } else {
1.841     albertel 10088: 		    foreach my $line (@listing_results) {
                   10089: 			my ($entry) = split(/&/,$line,2);
                   10090: 			$allusers{$entry} = 1;
                   10091: 		    }
                   10092: 		}
1.253     stredwic 10093:             }
1.1136    raeburn  10094:             my @alluserslist=();
1.800     albertel 10095:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10096:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10097:             }
1.1136    raeburn  10098:             return (\@alluserslist);
1.253     stredwic 10099:         } else {
1.1136    raeburn  10100:             return ([],'missing username');
1.253     stredwic 10101:         }
1.955     raeburn  10102:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10103:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10104:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10105:         return (\@all_domains);
1.955     raeburn  10106:     } else {
1.1136    raeburn  10107:         return ([],'missing domain');
1.275     stredwic 10108:     }
                   10109: }
                   10110: 
                   10111: # --------------------------------------------- GetFileTimestamp
                   10112: # This function utilizes dirlist and returns the date stamp for
                   10113: # when it was last modified.  It will also return an error of -1
                   10114: # if an error occurs
                   10115: 
                   10116: sub GetFileTimestamp {
1.955     raeburn  10117:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10118:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10119:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10120:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10121:                                     undef,$getuserdir);
                   10122:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10123:         return -1;
                   10124:     }
                   10125:     if (ref($fileref) eq 'ARRAY') {
                   10126:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10127:         # @stats contains first the filename, then the stat output
                   10128:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10129:     } else {
                   10130:         return -1;
1.253     stredwic 10131:     }
1.26      www      10132: }
                   10133: 
1.712     albertel 10134: sub stat_file {
                   10135:     my ($uri) = @_;
1.787     albertel 10136:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10137: 
1.955     raeburn  10138:     my ($udom,$uname,$file);
1.712     albertel 10139:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10140: 	($udom,$uname,$file) =
1.811     albertel 10141: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10142: 	$file = 'userfiles/'.$file;
                   10143:     }
                   10144:     if ($uri =~ m-^/res/-) {
                   10145: 	($udom,$uname) = 
1.807     albertel 10146: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10147: 	$file = $uri;
                   10148:     }
                   10149: 
                   10150:     if (!$udom || !$uname || !$file) {
                   10151: 	# unable to handle the uri
                   10152: 	return ();
                   10153:     }
1.956     raeburn  10154:     my $getpropath;
                   10155:     if ($file =~ /^userfiles\//) {
                   10156:         $getpropath = 1;
                   10157:     }
1.1136    raeburn  10158:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10159:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10160:         return ();
                   10161:     } else {
                   10162:         if (ref($listref) eq 'ARRAY') {
                   10163:             my @stats = split('&',$listref->[0]);
                   10164: 	    shift(@stats); #filename is first
                   10165: 	    return @stats;
                   10166:         }
1.712     albertel 10167:     }
                   10168:     return ();
                   10169: }
                   10170: 
1.26      www      10171: # -------------------------------------------------------- Value of a Condition
                   10172: 
1.713     albertel 10173: # gets the value of a specific preevaluated condition
                   10174: #    stored in the string  $env{user.state.<cid>}
                   10175: # or looks up a condition reference in the bighash and if if hasn't
                   10176: # already been evaluated recurses into docondval to get the value of
                   10177: # the condition, then memoizing it to 
                   10178: #   $env{user.state.<cid>.<condition>}
1.40      www      10179: sub directcondval {
                   10180:     my $number=shift;
1.620     albertel 10181:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10182: 	&Apache::lonuserstate::evalstate();
                   10183:     }
1.713     albertel 10184:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10185: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10186:     } elsif ($number =~ /^_/) {
                   10187: 	my $sub_condition;
                   10188: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10189: 		&GDBM_READER(),0640)) {
                   10190: 	    $sub_condition=$bighash{'conditions'.$number};
                   10191: 	    untie(%bighash);
                   10192: 	}
                   10193: 	my $value = &docondval($sub_condition);
1.949     raeburn  10194: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10195: 	return $value;
                   10196:     }
1.620     albertel 10197:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10198:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10199:     } else {
                   10200:        return 2;
                   10201:     }
                   10202: }
                   10203: 
1.713     albertel 10204: # get the collection of conditions for this resource
1.26      www      10205: sub condval {
                   10206:     my $condidx=shift;
1.54      www      10207:     my $allpathcond='';
1.713     albertel 10208:     foreach my $cond (split(/\|/,$condidx)) {
                   10209: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10210: 	    $allpathcond.=
                   10211: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10212: 	}
1.191     harris41 10213:     }
1.54      www      10214:     $allpathcond=~s/\|$//;
1.713     albertel 10215:     return &docondval($allpathcond);
                   10216: }
                   10217: 
                   10218: #evaluates an expression of conditions
                   10219: sub docondval {
                   10220:     my ($allpathcond) = @_;
                   10221:     my $result=0;
                   10222:     if ($env{'request.course.id'}
                   10223: 	&& defined($allpathcond)) {
                   10224: 	my $operand='|';
                   10225: 	my @stack;
                   10226: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10227: 	    if ($chunk eq '(') {
                   10228: 		push @stack,($operand,$result);
                   10229: 	    } elsif ($chunk eq ')') {
                   10230: 		my $before=pop @stack;
                   10231: 		if (pop @stack eq '&') {
                   10232: 		    $result=$result>$before?$before:$result;
                   10233: 		} else {
                   10234: 		    $result=$result>$before?$result:$before;
                   10235: 		}
                   10236: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10237: 		$operand=$chunk;
                   10238: 	    } else {
                   10239: 		my $new=directcondval($chunk);
                   10240: 		if ($operand eq '&') {
                   10241: 		    $result=$result>$new?$new:$result;
                   10242: 		} else {
                   10243: 		    $result=$result>$new?$result:$new;
                   10244: 		}
                   10245: 	    }
                   10246: 	}
1.26      www      10247:     }
                   10248:     return $result;
1.421     albertel 10249: }
                   10250: 
                   10251: # ---------------------------------------------------- Devalidate courseresdata
                   10252: 
                   10253: sub devalidatecourseresdata {
                   10254:     my ($coursenum,$coursedomain)=@_;
                   10255:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10256:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10257: }
                   10258: 
1.763     www      10259: 
1.200     www      10260: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10261: #
                   10262: #  Parameters:
                   10263: #      $coursenum    - Number of the course.
                   10264: #      $coursedomain - Domain at which the course was created.
                   10265: #  Returns:
                   10266: #     A hash of the course parameters along (I think) with timestamps
                   10267: #     and version info.
1.877     foxr     10268: 
1.624     albertel 10269: sub get_courseresdata {
                   10270:     my ($coursenum,$coursedomain)=@_;
1.200     www      10271:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10272:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10273:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10274:     my %dumpreply;
1.417     albertel 10275:     unless (defined($cached)) {
1.624     albertel 10276: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10277: 	$result=\%dumpreply;
1.251     albertel 10278: 	my ($tmp) = keys(%dumpreply);
                   10279: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10280: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10281: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10282: 	    return $tmp;
1.416     albertel 10283: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10284: 	    $result=undef;
1.599     albertel 10285: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10286: 	}
                   10287:     }
1.624     albertel 10288:     return $result;
                   10289: }
                   10290: 
1.633     albertel 10291: sub devalidateuserresdata {
                   10292:     my ($uname,$udom)=@_;
                   10293:     my $hashid="$udom:$uname";
                   10294:     &devalidate_cache_new('userres',$hashid);
                   10295: }
                   10296: 
1.624     albertel 10297: sub get_userresdata {
                   10298:     my ($uname,$udom)=@_;
                   10299:     #most student don\'t have any data set, check if there is some data
                   10300:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10301: 
                   10302:     my $hashid="$udom:$uname";
                   10303:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10304:     if (!defined($cached)) {
                   10305: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10306: 	$result=\%resourcedata;
                   10307: 	&do_cache_new('userres',$hashid,$result,600);
                   10308:     }
                   10309:     my ($tmp)=keys(%$result);
                   10310:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10311: 	return $result;
                   10312:     }
                   10313:     #error 2 occurs when the .db doesn't exist
                   10314:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10315:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10316: 	    &logthis("<font color=\"blue\">WARNING:".
                   10317: 		     " Trying to get resource data for ".
                   10318: 		     $uname." at ".$udom.": ".
                   10319: 		     $tmp."</font>");
                   10320:         }
1.624     albertel 10321:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10322: 	#&EXT_cache_set($udom,$uname);
                   10323: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10324: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10325:     }
                   10326:     return $tmp;
                   10327: }
1.879     foxr     10328: #----------------------------------------------- resdata - return resource data
                   10329: #  Purpose:
                   10330: #    Return resource data for either users or for a course.
                   10331: #  Parameters:
                   10332: #     $name      - Course/user name.
                   10333: #     $domain    - Name of the domain the user/course is registered on.
                   10334: #     $type      - Type of thing $name is (must be 'course' or 'user'
1.1301    raeburn  10335: #     $mapp      - decluttered URL of enclosing map  
                   10336: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10337: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10338: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10339: #     $courseid  - CourseID (first part of param identifier).
                   10340: #     $modifier  - Middle part of param identifier.
                   10341: #     $what      - Last part of param identifier.
1.879     foxr     10342: #     @which     - Array of names of resources desired.
                   10343: #  Returns:
                   10344: #     The value of the first reasource in @which that is found in the
                   10345: #     resource hash.
                   10346: #  Exceptional Conditions:
                   10347: #     If the $type passed in is not valid (not the string 'course' or 
                   10348: #     'user', an undefined  reference is returned.
                   10349: #     If none of the resources are found, an undef is returned
1.624     albertel 10350: sub resdata {
1.1301    raeburn  10351:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10352:         $modifier,$what,@which)=@_;
1.624     albertel 10353:     my $result;
                   10354:     if ($type eq 'course') {
                   10355: 	$result=&get_courseresdata($name,$domain);
                   10356:     } elsif ($type eq 'user') {
                   10357: 	$result=&get_userresdata($name,$domain);
                   10358:     }
                   10359:     if (!ref($result)) { return $result; }    
1.251     albertel 10360:     foreach my $item (@which) {
1.1301    raeburn  10361:         if ($item->[1] eq 'course') {
                   10362:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10363:                 unless ($$recursed) {
1.1302    raeburn  10364:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10365:                     $$recursed = 1;
                   10366:                 }
                   10367:                 foreach my $item (@${recurseup}) {
                   10368:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10369:                     last if (defined($result->{$norecursechk}));
                   10370:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10371:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10372:                 }
                   10373:             }
                   10374:         }
                   10375:         if (defined($result->{$item->[0]})) {
1.927     albertel 10376: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10377: 	}
1.250     albertel 10378:     }
1.291     albertel 10379:     return undef;
1.200     www      10380: }
                   10381: 
1.1298    raeburn  10382: sub get_domain_ltitools {
                   10383:     my ($cdom) = @_;
                   10384:     my %ltitools;
                   10385:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10386:     if (defined($cached)) {
                   10387:         if (ref($result) eq 'HASH') {
                   10388:             %ltitools = %{$result};
                   10389:         }
                   10390:     } else {
                   10391:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10392:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10393:             %ltitools = %{$domconfig{'ltitools'}};
                   10394:         }
                   10395:         my $cachetime = 24*60*60;
                   10396:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10397:     }
                   10398:     return %ltitools;
                   10399: }
                   10400: 
1.1236    raeburn  10401: sub get_numsuppfiles {
                   10402:     my ($cnum,$cdom,$ignorecache)=@_;
                   10403:     my $hashid=$cnum.':'.$cdom;
                   10404:     my ($suppcount,$cached);
                   10405:     unless ($ignorecache) {
                   10406:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10407:     }
                   10408:     unless (defined($cached)) {
                   10409:         my $chome=&homeserver($cnum,$cdom);
                   10410:         unless ($chome eq 'no_host') {
                   10411:             ($suppcount,my $errors) = (0,0);
                   10412:             my $suppmap = 'supplemental.sequence';
                   10413:             ($suppcount,$errors) = 
                   10414:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10415:         }
                   10416:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10417:     }
                   10418:     return $suppcount;
                   10419: }
                   10420: 
1.379     matthew  10421: #
                   10422: # EXT resource caching routines
                   10423: #
                   10424: 
1.1302    raeburn  10425: {
                   10426: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10427: #
                   10428: # The course for which we cache
                   10429: my $cachedmapkey='';
                   10430: # The cached recursive maps for this course
                   10431: my %cachedmaps=();
                   10432: # When this was last done
                   10433: my $cachedmaptime='';
                   10434: 
1.379     matthew  10435: sub clear_EXT_cache_status {
1.383     albertel 10436:     &delenv('cache.EXT.');
1.379     matthew  10437: }
                   10438: 
                   10439: sub EXT_cache_status {
                   10440:     my ($target_domain,$target_user) = @_;
1.383     albertel 10441:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10442:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10443:         # We know already the user has no data
                   10444:         return 1;
                   10445:     } else {
                   10446:         return 0;
                   10447:     }
                   10448: }
                   10449: 
                   10450: sub EXT_cache_set {
                   10451:     my ($target_domain,$target_user) = @_;
1.383     albertel 10452:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10453:     #&appenv({$cachename => time});
1.379     matthew  10454: }
                   10455: 
1.28      www      10456: # --------------------------------------------------------- Value of a Variable
1.58      www      10457: sub EXT {
1.715     albertel 10458: 
1.1228    raeburn  10459:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10460:     unless ($varname) { return ''; }
1.218     albertel 10461:     #get real user name/domain, courseid and symb
                   10462:     my $courseid;
1.359     albertel 10463:     my $publicuser;
1.427     www      10464:     if ($symbparm) {
                   10465: 	$symbparm=&get_symb_from_alias($symbparm);
                   10466:     }
1.218     albertel 10467:     if (!($uname && $udom)) {
1.790     albertel 10468:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10469:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10470:     } else {
1.620     albertel 10471: 	$courseid=$env{'request.course.id'};
1.218     albertel 10472:     }
1.48      www      10473:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10474:     my $rest;
1.320     albertel 10475:     if (defined($therest[0])) {
1.48      www      10476:        $rest=join('.',@therest);
                   10477:     } else {
                   10478:        $rest='';
                   10479:     }
1.320     albertel 10480: 
1.57      www      10481:     my $qualifierrest=$qualifier;
                   10482:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10483:     my $spacequalifierrest=$space;
                   10484:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10485:     if ($realm eq 'user') {
1.48      www      10486: # --------------------------------------------------------------- user.resource
                   10487: 	if ($space eq 'resource') {
1.651     albertel 10488: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10489: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10490: 		 &&
1.744     albertel 10491: 		 ($symbparm eq &symbread()) ) {	
                   10492: 		# if we are in the middle of processing the resource the
                   10493: 		# get the value we are planning on committing
                   10494:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10495:                     return $Apache::lonhomework::results{$qualifierrest};
                   10496:                 } else {
                   10497:                     return $Apache::lonhomework::history{$qualifierrest};
                   10498:                 }
1.335     albertel 10499: 	    } else {
1.359     albertel 10500: 		my %restored;
1.620     albertel 10501: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10502: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10503: 		} else {
                   10504: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10505: 		}
1.335     albertel 10506: 		return $restored{$qualifierrest};
                   10507: 	    }
1.48      www      10508: # ----------------------------------------------------------------- user.access
                   10509:         } elsif ($space eq 'access') {
1.218     albertel 10510: 	    # FIXME - not supporting calls for a specific user
1.48      www      10511:             return &allowed($qualifier,$rest);
                   10512: # ------------------------------------------ user.preferences, user.environment
                   10513:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10514: 	    if (($uname eq $env{'user.name'}) &&
                   10515: 		($udom eq $env{'user.domain'})) {
                   10516: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10517: 	    } else {
1.359     albertel 10518: 		my %returnhash;
                   10519: 		if (!$publicuser) {
                   10520: 		    %returnhash=&userenvironment($udom,$uname,
                   10521: 						 $qualifierrest);
                   10522: 		}
1.218     albertel 10523: 		return $returnhash{$qualifierrest};
                   10524: 	    }
1.48      www      10525: # ----------------------------------------------------------------- user.course
                   10526:         } elsif ($space eq 'course') {
1.218     albertel 10527: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10528:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10529: # ------------------------------------------------------------------- user.role
                   10530:         } elsif ($space eq 'role') {
1.218     albertel 10531: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10532:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10533:             if ($qualifier eq 'value') {
                   10534: 		return $role;
                   10535:             } elsif ($qualifier eq 'extent') {
                   10536:                 return $where;
                   10537:             }
                   10538: # ----------------------------------------------------------------- user.domain
                   10539:         } elsif ($space eq 'domain') {
1.218     albertel 10540:             return $udom;
1.48      www      10541: # ------------------------------------------------------------------- user.name
                   10542:         } elsif ($space eq 'name') {
1.218     albertel 10543:             return $uname;
1.48      www      10544: # ---------------------------------------------------- Any other user namespace
1.29      www      10545:         } else {
1.359     albertel 10546: 	    my %reply;
                   10547: 	    if (!$publicuser) {
                   10548: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10549: 	    }
                   10550: 	    return $reply{$qualifierrest};
1.48      www      10551:         }
1.236     www      10552:     } elsif ($realm eq 'query') {
                   10553: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10554:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10555: 						[$spacequalifierrest]);
1.620     albertel 10556: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10557:    } elsif ($realm eq 'request') {
1.48      www      10558: # ------------------------------------------------------------- request.browser
                   10559:         if ($space eq 'browser') {
1.1145    bisitz   10560:             return $env{'browser.'.$qualifier};
1.57      www      10561: # ------------------------------------------------------------ request.filename
                   10562:         } else {
1.620     albertel 10563:             return $env{'request.'.$spacequalifierrest};
1.29      www      10564:         }
1.28      www      10565:     } elsif ($realm eq 'course') {
1.48      www      10566: # ---------------------------------------------------------- course.description
1.620     albertel 10567:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10568:     } elsif ($realm eq 'resource') {
1.165     www      10569: 
1.620     albertel 10570: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10571: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10572: 	}
1.693     albertel 10573: 
1.1232    raeburn  10574:         if ($qualifier eq '') {
                   10575: 	    if ($space eq 'title') {
                   10576: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10577: 	        return &gettitle($symbparm);
                   10578: 	    }
1.693     albertel 10579: 	
1.1232    raeburn  10580: 	    if ($space eq 'map') {
                   10581: 	        my ($map) = &decode_symb($symbparm);
                   10582: 	        return &symbread($map);
                   10583: 	    }
                   10584:             if ($space eq 'maptitle') {
                   10585:                 my ($map) = &decode_symb($symbparm);
                   10586:                 return &gettitle($map);
                   10587:             }
                   10588: 	    if ($space eq 'filename') {
                   10589: 	        if ($symbparm) {
                   10590: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10591: 	        }
                   10592: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10593: 	    }
1.1232    raeburn  10594: 
1.1233    raeburn  10595:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10596:                 if ($space eq 'visibleparts') {
                   10597:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10598:                     my $item;
                   10599:                     if (ref($navmap)) {
                   10600:                         my $res = $navmap->getBySymb($symbparm);
                   10601:                         my $parts = $res->parts();
                   10602:                         if (ref($parts) eq 'ARRAY') {
                   10603:                             $item = join(',',@{$parts});
                   10604:                         }
                   10605:                         undef($navmap);
1.1232    raeburn  10606:                     }
1.1233    raeburn  10607:                     return $item;
1.1232    raeburn  10608:                 }
                   10609:             }
                   10610:         }
1.693     albertel 10611: 
1.1301    raeburn  10612: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10613: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10614:         if (($courseid eq '') && ($cid)) {
                   10615:             $courseid = $cid;
                   10616:         }
                   10617: 	if (($symbparm && $courseid) && 
                   10618: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10619: 
1.218     albertel 10620: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10621: 
1.60      www      10622: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10623: 	    my $symbp=$symbparm;
1.1301    raeburn  10624: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10625: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10626:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10627: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10628: 	    if (($env{'user.name'} eq $uname) &&
                   10629: 		($env{'user.domain'} eq $udom)) {
                   10630: 		$section=$env{'request.course.sec'};
1.733     raeburn  10631:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10632:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10633: 	    } else {
1.539     albertel 10634: 		if (! defined($usection)) {
1.551     albertel 10635: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10636: 		} else {
                   10637: 		    $section = $usection;
                   10638: 		}
1.733     raeburn  10639:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10640: 	    }
                   10641: 
                   10642: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10643: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10644:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10645: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10646: 
1.593     albertel 10647: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10648: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10649:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10650: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10651: 
1.60      www      10652: # ----------------------------------------------------------- first, check user
1.624     albertel 10653: 
1.1301    raeburn  10654: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10655:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10656: 				       ([$courselevelr,'resource'],
                   10657: 					[$courselevelm,'map'     ],
1.1301    raeburn  10658:                                         [$courseleveli,'map'     ],
1.927     albertel 10659: 					[$courselevel, 'course'  ]));
1.931     albertel 10660: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10661: 
1.594     albertel 10662: # ------------------------------------------------ second, check some of course
1.684     raeburn  10663:             my $coursereply;
1.691     raeburn  10664:             if (@groups > 0) {
                   10665:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10666:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10667:                                        $mapp,\$recursed,\@recurseup);
                   10668:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10669:             }
1.96      www      10670: 
1.684     raeburn  10671: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10672: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10673: 				  'course',$mapp,\$recursed,\@recurseup,
                   10674:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10675: 				  ([$seclevelr,   'resource'],
                   10676: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10677:                                    [$secleveli,   'map'     ],
1.927     albertel 10678: 				   [$seclevel,    'course'  ],
                   10679: 				   [$courselevelr,'resource']));
                   10680: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10681: 
1.60      www      10682: # ------------------------------------------------------ third, check map parms
1.218     albertel 10683: 	    my %parmhash=();
                   10684: 	    my $thisparm='';
                   10685: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10686: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10687: 		    &GDBM_READER(),0640)) {
1.218     albertel 10688: 		$thisparm=$parmhash{$symbparm};
                   10689: 		untie(%parmhash);
                   10690: 	    }
1.927     albertel 10691: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10692: 	}
1.594     albertel 10693: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10694:  
                   10695:         my $what = $spacequalifierrest;
                   10696: 	$what=~s/\./\_/;
1.282     albertel 10697: 	my $filename;
                   10698: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10699: 	if ($symbparm) {
1.409     www      10700: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10701: 	} else {
1.620     albertel 10702: 	    $filename=$env{'request.filename'};
1.282     albertel 10703: 	}
1.1301    raeburn  10704: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10705: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10706: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10707: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10708: 
1.1301    raeburn  10709: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10710: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10711: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10712: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10713: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10714: 				     'course',$mapp,\$recursed,\@recurseup,
                   10715:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10716: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10717:                                       [$courseleveli,'map'   ],
1.927     albertel 10718: 				      [$courselevel, 'course']));
                   10719: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10720: 	}
1.145     www      10721: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10722: 	unless ($space eq '0') {
1.336     albertel 10723: 	    my @parts=split(/_/,$space);
                   10724: 	    my $id=pop(@parts);
                   10725: 	    my $part=join('_',@parts);
                   10726: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10727: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10728: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10729: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10730: 	}
1.395     albertel 10731: 	if ($recurse) { return undef; }
                   10732: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10733: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10734: # ---------------------------------------------------- Any other user namespace
                   10735:     } elsif ($realm eq 'environment') {
                   10736: # ----------------------------------------------------------------- environment
1.620     albertel 10737: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10738: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10739: 	} else {
1.770     albertel 10740: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10741: 		return '';
                   10742: 	    }
1.219     albertel 10743: 	    my %returnhash=&userenvironment($udom,$uname,
                   10744: 					    $spacequalifierrest);
                   10745: 	    return $returnhash{$spacequalifierrest};
                   10746: 	}
1.28      www      10747:     } elsif ($realm eq 'system') {
1.48      www      10748: # ----------------------------------------------------------------- system.time
                   10749: 	if ($space eq 'time') {
                   10750: 	    return time;
                   10751:         }
1.696     albertel 10752:     } elsif ($realm eq 'server') {
                   10753: # ----------------------------------------------------------------- system.time
                   10754: 	if ($space eq 'name') {
                   10755: 	    return $ENV{'SERVER_NAME'};
                   10756:         }
1.28      www      10757:     }
1.48      www      10758:     return '';
1.61      www      10759: }
                   10760: 
1.927     albertel 10761: sub get_reply {
                   10762:     my ($reply_value) = @_;
1.940     raeburn  10763:     if (ref($reply_value) eq 'ARRAY') {
                   10764:         if (wantarray) {
                   10765: 	    return @$reply_value;
                   10766:         }
                   10767:         return $reply_value->[0];
                   10768:     } else {
                   10769:         return $reply_value;
1.927     albertel 10770:     }
                   10771: }
                   10772: 
1.691     raeburn  10773: sub check_group_parms {
1.1301    raeburn  10774:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   10775:         $recursed,$recurseupref) = @_;
                   10776:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   10777:                   [$what,'course']);
                   10778:     my $coursereply;
1.691     raeburn  10779:     foreach my $group (@{$groups}) {
1.1301    raeburn  10780:         my @groupitems = ();
1.691     raeburn  10781:         foreach my $level (@levels) {
1.927     albertel 10782:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10783:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10784:         }
1.1301    raeburn  10785:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10786:                                    $env{'course.'.$courseid.'.domain'},
                   10787:                                    'course',$mapp,$recursed,$recurseupref,
                   10788:                                    $courseid,'.['.$group.'].',$what,
                   10789:                                    @groupitems);
                   10790:         last if (defined($coursereply));
1.691     raeburn  10791:     }
                   10792:     return $coursereply;
                   10793: }
                   10794: 
1.1301    raeburn  10795: sub get_map_hierarchy {
1.1302    raeburn  10796:     my ($mapname,$courseid) = @_;
                   10797:     my @recurseup = ();
1.1301    raeburn  10798:     if ($mapname) {
1.1302    raeburn  10799:         if (($cachedmapkey eq $courseid) &&
                   10800:             (abs($cachedmaptime-time)<5)) {
                   10801:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   10802:                 return @{$cachedmaps{$mapname}};
                   10803:             }
                   10804:         }
1.1301    raeburn  10805:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10806:         if (ref($navmap)) {
                   10807:             @recurseup = $navmap->recurseup_maps($mapname);
                   10808:             undef($navmap);
1.1302    raeburn  10809:             $cachedmaps{$mapname} = \@recurseup;
                   10810:             $cachedmaptime=time;
                   10811:             $cachedmapkey=$courseid;
1.1301    raeburn  10812:         }
                   10813:     }
                   10814:     return @recurseup;
                   10815: }
                   10816: 
1.1302    raeburn  10817: }
                   10818: 
1.691     raeburn  10819: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10820:     my ($courseid,@groups) = @_;
                   10821:     @groups = sort(@groups);
1.691     raeburn  10822:     return @groups;
                   10823: }
                   10824: 
1.395     albertel 10825: sub packages_tab_default {
                   10826:     my ($uri,$varname)=@_;
                   10827:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10828: 
                   10829:     my (@extension,@specifics,$do_default);
                   10830:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10831: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10832: 	if ($pack_type eq 'default') {
                   10833: 	    $do_default=1;
                   10834: 	} elsif ($pack_type eq 'extension') {
                   10835: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10836: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10837: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10838: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10839: 	}
                   10840:     }
                   10841:     # first look for a package that matches the requested part id
                   10842:     foreach my $package (@specifics) {
                   10843: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10844: 	next if ($pack_part ne $part);
                   10845: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10846: 	    return $packagetab{"$pack_type&$name&default"};
                   10847: 	}
                   10848:     }
                   10849:     # look for any possible matching non extension_ package
                   10850:     foreach my $package (@specifics) {
                   10851: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10852: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10853: 	    return $packagetab{"$pack_type&$name&default"};
                   10854: 	}
1.585     albertel 10855: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10856: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10857: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10858: 	}
                   10859:     }
1.738     albertel 10860:     # look for any posible extension_ match
                   10861:     foreach my $package (@extension) {
                   10862: 	my ($package,$pack_type)=@{$package};
                   10863: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10864: 	    return $packagetab{"$pack_type&$name&default"};
                   10865: 	}
                   10866: 	if (defined($packagetab{$package."&$name&default"})) {
                   10867: 	    return $packagetab{$package."&$name&default"};
                   10868: 	}
                   10869:     }
                   10870:     # look for a global default setting
                   10871:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10872: 	return $packagetab{"default&$name&default"};
                   10873:     }
1.395     albertel 10874:     return undef;
                   10875: }
                   10876: 
1.334     albertel 10877: sub add_prefix_and_part {
                   10878:     my ($prefix,$part)=@_;
                   10879:     my $keyroot;
                   10880:     if (defined($prefix) && $prefix !~ /^__/) {
                   10881: 	# prefix that has a part already
                   10882: 	$keyroot=$prefix;
                   10883:     } elsif (defined($prefix)) {
                   10884: 	# prefix that is missing a part
                   10885: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10886:     } else {
                   10887: 	# no prefix at all
                   10888: 	if (defined($part)) { $keyroot='_'.$part; }
                   10889:     }
                   10890:     return $keyroot;
                   10891: }
                   10892: 
1.71      www      10893: # ---------------------------------------------------------------- Get metadata
                   10894: 
1.599     albertel 10895: my %metaentry;
1.1070    www      10896: my %importedpartids;
1.71      www      10897: sub metadata {
1.176     www      10898:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10899:     $uri=&declutter($uri);
1.288     albertel 10900:     # if it is a non metadata possible uri return quickly
1.529     albertel 10901:     if (($uri eq '') || 
                   10902: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  10903: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  10904:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10905: 	return undef;
                   10906:     }
1.1261    raeburn  10907:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10908: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10909: 	return undef;
1.288     albertel 10910:     }
1.73      www      10911:     my $filename=$uri;
                   10912:     $uri=~s/\.meta$//;
1.172     www      10913: #
                   10914: # Is the metadata already cached?
1.177     www      10915: # Look at timestamp of caching
1.172     www      10916: # Everything is cached by the main uri, libraries are never directly cached
                   10917: #
1.428     albertel 10918:     if (!defined($liburi)) {
1.599     albertel 10919: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10920: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10921:     }
                   10922:     {
1.1069    www      10923: # Imported parts would go here
1.1070    www      10924:         my %importedids=();
                   10925:         my @origfileimportpartids=();
1.1069    www      10926:         my $importedparts=0;
1.172     www      10927: #
                   10928: # Is this a recursive call for a library?
                   10929: #
1.599     albertel 10930: #	if (! exists($metacache{$uri})) {
                   10931: #	    $metacache{$uri}={};
                   10932: #	}
1.924     albertel 10933: 	my $cachetime = 60*60;
1.171     www      10934:         if ($liburi) {
                   10935: 	    $liburi=&declutter($liburi);
                   10936:             $filename=$liburi;
1.401     bowersj2 10937:         } else {
1.599     albertel 10938: 	    &devalidate_cache_new('meta',$uri);
                   10939: 	    undef(%metaentry);
1.401     bowersj2 10940: 	}
1.140     www      10941:         my %metathesekeys=();
1.73      www      10942:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10943: 	my $metastring;
1.1140    www      10944: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10945: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10946: 	    $metastring = 
1.929     albertel 10947: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10948: 					  ('grade_target' => 'meta'));
                   10949: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10950: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10951:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10952: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10953: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10954: 	    $metastring=&getfile($file);
1.489     albertel 10955: 	}
1.208     albertel 10956:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10957:         my $token;
1.140     www      10958:         undef %metathesekeys;
1.71      www      10959:         while ($token=$parser->get_token) {
1.339     albertel 10960: 	    if ($token->[0] eq 'S') {
                   10961: 		if (defined($token->[2]->{'package'})) {
1.172     www      10962: #
                   10963: # This is a package - get package info
                   10964: #
1.339     albertel 10965: 		    my $package=$token->[2]->{'package'};
                   10966: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10967: 		    if (defined($token->[2]->{'id'})) { 
                   10968: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10969: 		    }
1.599     albertel 10970: 		    if ($metaentry{':packages'}) {
                   10971: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10972: 		    } else {
1.599     albertel 10973: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10974: 		    }
1.736     albertel 10975: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10976: 			my $part=$keyroot;
                   10977: 			$part=~s/^\_//;
1.736     albertel 10978: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10979: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10980: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10981: 			    # ignore package.tab specified default values
                   10982:                             # here &package_tab_default() will fetch those
                   10983: 			    if ($subp eq 'default') { next; }
1.736     albertel 10984: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10985: 			    my $unikey;
                   10986: 			    if ($pack =~ /_0$/) {
                   10987: 				$unikey='parameter_0_'.$name;
                   10988: 				$part=0;
                   10989: 			    } else {
                   10990: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10991: 			    }
1.339     albertel 10992: 			    if ($subp eq 'display') {
                   10993: 				$value.=' [Part: '.$part.']';
                   10994: 			    }
1.599     albertel 10995: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10996: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10997: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10998: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10999: 			    }
1.599     albertel 11000: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11001: 				$metaentry{':'.$unikey}=
                   11002: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11003: 			    }
1.339     albertel 11004: 			}
                   11005: 		    }
                   11006: 		} else {
1.172     www      11007: #
                   11008: # This is not a package - some other kind of start tag
1.339     albertel 11009: #
                   11010: 		    my $entry=$token->[1];
1.1068    www      11011: 		    my $unikey='';
1.175     www      11012: 
1.339     albertel 11013: 		    if ($entry eq 'import') {
1.175     www      11014: #
                   11015: # Importing a library here
1.339     albertel 11016: #
1.1067    www      11017:                         my $location=$parser->get_text('/import');
                   11018:                         my $dir=$filename;
                   11019:                         $dir=~s|[^/]*$||;
                   11020:                         $location=&filelocation($dir,$location);
1.1069    www      11021:                        
1.1068    www      11022:                         my $importmode=$token->[2]->{'importmode'};
                   11023:                         if ($importmode eq 'problem') {
1.1069    www      11024: # Import as problem/response
1.1068    www      11025:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11026:                         } elsif ($importmode eq 'part') {
                   11027: # Import as part(s)
1.1069    www      11028:                            $importedparts=1;
                   11029: # We need to get the original file and the imported file to get the part order correct
                   11030: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11031: # Load and inspect original file
1.1070    www      11032:                            if ($#origfileimportpartids<0) {
                   11033:                               undef(%importedpartids);
                   11034:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11035:                               my $origfile=&getfile($origfilelocation);
                   11036:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11037:                            }
                   11038: 
1.1069    www      11039: # Load and inspect imported file
                   11040:                            my $impfile=&getfile($location);
                   11041:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11042:                            if ($#impfilepartids>=0) {
                   11043: # This problem had parts
1.1070    www      11044:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11045:                            } else {
                   11046: # Importing by turning a single problem into a problem part
                   11047: # It gets the import-tags ID as part-ID
                   11048:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11049:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11050:                            }
1.1068    www      11051:                         } else {
                   11052: # Normal import
                   11053:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11054:                            if (defined($token->[2]->{'id'})) {
                   11055:                               $unikey.='_'.$token->[2]->{'id'};
                   11056:                            }
1.1067    www      11057:                         }
                   11058: 
1.339     albertel 11059: 			if ($depthcount<20) {
1.736     albertel 11060: 			    my $metadata = 
                   11061: 				&metadata($uri,'keys', $location,$unikey,
                   11062: 					  $depthcount+1);
                   11063: 			    foreach my $meta (split(',',$metadata)) {
                   11064: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11065: 				$metathesekeys{$meta}=1;
1.339     albertel 11066: 			    }
1.1068    www      11067: 			
                   11068:                         }
1.1067    www      11069: 		    } else {
                   11070: #
                   11071: # Not importing, some other kind of non-package, non-library start tag
                   11072: # 
                   11073:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11074:                         if (defined($token->[2]->{'id'})) {
                   11075:                             $unikey.='_'.$token->[2]->{'id'};
                   11076:                         }
1.339     albertel 11077: 			if (defined($token->[2]->{'name'})) { 
                   11078: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11079: 			}
                   11080: 			$metathesekeys{$unikey}=1;
1.736     albertel 11081: 			foreach my $param (@{$token->[3]}) {
                   11082: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11083: 				$token->[2]->{$param};
1.339     albertel 11084: 			}
                   11085: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11086: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11087: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11088: 		 # only ws inside the tag, and not in default, so use default
                   11089: 		 # as value
1.599     albertel 11090: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11091: 			} elsif ( $internaltext =~ /\S/ ) {
                   11092: 		  # something interesting inside the tag
                   11093: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11094: 			} else {
1.908     albertel 11095: 		  # no interesting values, don't set a default
1.339     albertel 11096: 			}
1.172     www      11097: # end of not-a-package not-a-library import
1.339     albertel 11098: 		    }
1.172     www      11099: # end of not-a-package start tag
1.339     albertel 11100: 		}
1.172     www      11101: # the next is the end of "start tag"
1.339     albertel 11102: 	    }
                   11103: 	}
1.483     albertel 11104: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11105: 	$extension = lc($extension);
                   11106: 	if ($extension eq 'htm') { $extension='html'; }
                   11107: 
1.737     albertel 11108: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11109: 	    #no specific packages #how's our extension
                   11110: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11111: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11112: 					 \%metathesekeys);
                   11113: 	}
1.883     albertel 11114: 
                   11115: 	if (!exists($metaentry{':packages'})
                   11116: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11117: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11118: 		#no specific packages well let's get default then
                   11119: 		if ($key!~/^default&/) { next; }
1.488     albertel 11120: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11121: 					     \%metathesekeys);
                   11122: 	    }
                   11123: 	}
1.338     www      11124: # are there custom rights to evaluate
1.599     albertel 11125: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11126: 
1.338     www      11127:     #
                   11128:     # Importing a rights file here
1.339     albertel 11129:     #
                   11130: 	    unless ($depthcount) {
1.599     albertel 11131: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11132: 		my $dir=$filename;
                   11133: 		$dir=~s|[^/]*$||;
                   11134: 		$location=&filelocation($dir,$location);
1.736     albertel 11135: 		my $rights_metadata =
                   11136: 		    &metadata($uri,'keys',$location,'_rights',
                   11137: 			      $depthcount+1);
                   11138: 		foreach my $rights (split(',',$rights_metadata)) {
                   11139: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11140: 		    $metathesekeys{$rights}=1;
1.339     albertel 11141: 		}
                   11142: 	    }
                   11143: 	}
1.737     albertel 11144: 	# uniqifiy package listing
                   11145: 	my %seen;
                   11146: 	my @uniq_packages =
                   11147: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11148: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11149: 
1.1070    www      11150:         if ($importedparts) {
                   11151: # We had imported parts and need to rebuild partorder
                   11152:            $metaentry{':partorder'}='';
                   11153:            $metathesekeys{'partorder'}=1;
                   11154:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11155:                if ($origfileimportpartids[$index] eq 'part') {
                   11156: # original part, part of the problem
                   11157:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11158:                } else {
                   11159: # we have imported parts at this position
                   11160:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11161:                }
                   11162:            }
                   11163:            $metaentry{':partorder'}=~s/^\,//;
                   11164:         }
                   11165: 
1.737     albertel 11166: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11167: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11168: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11169: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11170: # this is the end of "was not already recently cached
1.71      www      11171:     }
1.599     albertel 11172:     return $metaentry{':'.$what};
1.261     albertel 11173: }
                   11174: 
1.488     albertel 11175: sub metadata_create_package_def {
1.483     albertel 11176:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11177:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11178:     if ($subp eq 'default') { next; }
                   11179:     
1.599     albertel 11180:     if (defined($metaentry{':packages'})) {
                   11181: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11182:     } else {
1.599     albertel 11183: 	$metaentry{':packages'}=$package;
1.483     albertel 11184:     }
                   11185:     my $value=$packagetab{$key};
                   11186:     my $unikey;
                   11187:     $unikey='parameter_0_'.$name;
1.599     albertel 11188:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11189:     $$metathesekeys{$unikey}=1;
1.599     albertel 11190:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11191: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11192:     }
1.599     albertel 11193:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11194: 	$metaentry{':'.$unikey}=
                   11195: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11196:     }
                   11197: }
                   11198: 
1.261     albertel 11199: sub metadata_generate_part0 {
                   11200:     my ($metadata,$metacache,$uri) = @_;
                   11201:     my %allnames;
1.737     albertel 11202:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11203: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11204: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11205: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11206: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11207: 	    $allnames{$name}=$part;
                   11208: 	  }
                   11209: 	}
                   11210:     }
                   11211:     foreach my $name (keys(%allnames)) {
                   11212:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11213:       my $key=":parameter_0_$name";
1.261     albertel 11214:       $$metacache{"$key.part"}='0';
                   11215:       $$metacache{"$key.name"}=$name;
1.428     albertel 11216:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11217: 					   $allnames{$name}.'_'.$name.
                   11218: 					   '.type'};
1.428     albertel 11219:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11220: 			     '.display'};
1.644     www      11221:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11222:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11223:       $$metacache{"$key.display"}=$olddis;
                   11224:     }
1.71      www      11225: }
                   11226: 
1.764     albertel 11227: # ------------------------------------------------------ Devalidate title cache
                   11228: 
                   11229: sub devalidate_title_cache {
                   11230:     my ($url)=@_;
                   11231:     if (!$env{'request.course.id'}) { return; }
                   11232:     my $symb=&symbread($url);
                   11233:     if (!$symb) { return; }
                   11234:     my $key=$env{'request.course.id'}."\0".$symb;
                   11235:     &devalidate_cache_new('title',$key);
                   11236: }
                   11237: 
1.1014    droeschl 11238: # ------------------------------------------------- Get the title of a course
                   11239: 
                   11240: sub current_course_title {
                   11241:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11242: }
1.301     www      11243: # ------------------------------------------------- Get the title of a resource
                   11244: 
                   11245: sub gettitle {
                   11246:     my $urlsymb=shift;
                   11247:     my $symb=&symbread($urlsymb);
1.534     albertel 11248:     if ($symb) {
1.620     albertel 11249: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11250: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11251: 	if (defined($cached)) { 
                   11252: 	    return $result;
                   11253: 	}
1.534     albertel 11254: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11255: 	my $title='';
1.907     albertel 11256: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11257: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11258: 	} else {
                   11259: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11260: 		    &GDBM_READER(),0640)) {
                   11261: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11262: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11263: 		untie(%bighash);
                   11264: 	    }
1.534     albertel 11265: 	}
                   11266: 	$title=~s/\&colon\;/\:/gs;
                   11267: 	if ($title) {
1.1159    www      11268: # Remember both $symb and $title for dynamic metadata
                   11269:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11270:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11271: # Cache this title and then return it
1.599     albertel 11272: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11273: 	}
                   11274: 	$urlsymb=$url;
                   11275:     }
                   11276:     my $title=&metadata($urlsymb,'title');
                   11277:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11278:     return $title;
1.301     www      11279: }
1.613     albertel 11280: 
1.614     albertel 11281: sub get_slot {
                   11282:     my ($which,$cnum,$cdom)=@_;
                   11283:     if (!$cnum || !$cdom) {
1.790     albertel 11284: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11285: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11286: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11287:     }
1.703     albertel 11288:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11289:     my %slotinfo;
                   11290:     if (exists($remembered{$key})) {
                   11291: 	$slotinfo{$which} = $remembered{$key};
                   11292:     } else {
                   11293: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11294: 	&Apache::lonhomework::showhash(%slotinfo);
                   11295: 	my ($tmp)=keys(%slotinfo);
                   11296: 	if ($tmp=~/^error:/) { return (); }
                   11297: 	$remembered{$key} = $slotinfo{$which};
                   11298:     }
1.616     albertel 11299:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11300: 	return %{$slotinfo{$which}};
                   11301:     }
                   11302:     return $slotinfo{$which};
1.614     albertel 11303: }
1.1150    raeburn  11304: 
                   11305: sub get_reservable_slots {
                   11306:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11307:     my $now = time;
                   11308:     my $reservable_info;
                   11309:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11310:     if (exists($remembered{$key})) {
                   11311:         $reservable_info = $remembered{$key};
                   11312:     } else {
                   11313:         my %resv;
                   11314:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11315:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11316:         $reservable_info = \%resv;
                   11317:         $remembered{$key} = $reservable_info;
                   11318:     }
                   11319:     return $reservable_info;
                   11320: }
                   11321: 
                   11322: sub get_course_slots {
                   11323:     my ($cnum,$cdom) = @_;
                   11324:     my $hashid=$cnum.':'.$cdom;
                   11325:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11326:     if (defined($cached)) {
                   11327:         if (ref($result) eq 'HASH') {
                   11328:             return %{$result};
                   11329:         }
                   11330:     } else {
                   11331:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11332:         my ($tmp) = keys(%slots);
                   11333:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11334:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11335:             return %slots;
                   11336:         }
                   11337:     }
                   11338:     return;
                   11339: }
                   11340: 
                   11341: sub devalidate_slots_cache {
                   11342:     my ($cnum,$cdom)=@_;
                   11343:     my $hashid=$cnum.':'.$cdom;
                   11344:     &devalidate_cache_new('allslots',$hashid);
                   11345: }
                   11346: 
1.1181    raeburn  11347: sub get_coursechange {
                   11348:     my ($cdom,$cnum) = @_;
                   11349:     if ($cdom eq '' || $cnum eq '') {
                   11350:         return unless ($env{'request.course.id'});
                   11351:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11352:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11353:     }
                   11354:     my $hashid=$cdom.'_'.$cnum;
                   11355:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11356:     if ((defined($cached)) && ($change ne '')) {
                   11357:         return $change;
                   11358:     } else {
                   11359:         my %crshash;
                   11360:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11361:         if ($crshash{'internal.contentchange'} eq '') {
                   11362:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11363:             if ($change eq '') {
                   11364:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11365:                 $change = $crshash{'internal.created'};
                   11366:             }
                   11367:         } else {
                   11368:             $change = $crshash{'internal.contentchange'};
                   11369:         }
                   11370:         my $cachetime = 600;
                   11371:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11372:     }
                   11373:     return $change;
                   11374: }
                   11375: 
                   11376: sub devalidate_coursechange_cache {
                   11377:     my ($cnum,$cdom)=@_;
                   11378:     my $hashid=$cnum.':'.$cdom;
                   11379:     &devalidate_cache_new('crschange',$hashid);
                   11380: }
                   11381: 
1.31      www      11382: # ------------------------------------------------- Update symbolic store links
                   11383: 
                   11384: sub symblist {
                   11385:     my ($mapname,%newhash)=@_;
1.438     www      11386:     $mapname=&deversion(&declutter($mapname));
1.31      www      11387:     my %hash;
1.620     albertel 11388:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11389:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11390:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11391: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11392: 		next if ($url eq 'last_known'
                   11393: 			 && $env{'form.no_update_last_known'});
                   11394: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11395: 						    $newhash{$url}->[1],
                   11396: 						    $newhash{$url}->[0]);
1.191     harris41 11397:             }
1.31      www      11398:             if (untie(%hash)) {
                   11399: 		return 'ok';
                   11400:             }
                   11401:         }
                   11402:     }
                   11403:     return 'error';
1.212     www      11404: }
                   11405: 
                   11406: # --------------------------------------------------------------- Verify a symb
                   11407: 
                   11408: sub symbverify {
1.1190    raeburn  11409:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11410:     my $thisfn=$thisurl;
1.439     www      11411:     $thisfn=&declutter($thisfn);
1.215     www      11412: # direct jump to resource in page or to a sequence - will construct own symbs
                   11413:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11414: # check URL part
1.409     www      11415:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11416: 
1.431     www      11417:     unless ($url eq $thisfn) { return 0; }
1.213     www      11418: 
1.216     www      11419:     $symb=&symbclean($symb);
1.510     www      11420:     $thisurl=&deversion($thisurl);
1.439     www      11421:     $thisfn=&deversion($thisfn);
1.213     www      11422: 
                   11423:     my %bighash;
                   11424:     my $okay=0;
1.431     www      11425: 
1.620     albertel 11426:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11427:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11428:         my $noclutter;
1.1032    raeburn  11429:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11430:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11431:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11432:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11433:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11434:                 $noclutter = 1;
                   11435:             }
                   11436:         }
                   11437:         my $ids;
                   11438:         if ($noclutter) {
                   11439:             $ids=$bighash{'ids_'.$thisurl};
                   11440:         } else {
                   11441:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11442:         }
1.1102    raeburn  11443:         unless ($ids) {
                   11444:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11445:             $ids=$bighash{$idkey};
1.216     www      11446:         }
                   11447:         if ($ids) {
                   11448: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11449:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11450:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11451:             }
1.800     albertel 11452: 	    foreach my $id (split(/\,/,$ids)) {
                   11453: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11454:                if (
                   11455:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11456:    eq $symb) {
                   11457:                    if (ref($encstate)) {
                   11458:                        $$encstate = $bighash{'encrypted_'.$id};
                   11459:                    }
1.620     albertel 11460: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11461: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11462:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11463: 		       $okay=1;
1.1202    raeburn  11464:                        last;
1.582     albertel 11465: 		   }
                   11466: 	       }
1.216     www      11467: 	   }
                   11468:         }
1.213     www      11469: 	untie(%bighash);
                   11470:     }
                   11471:     return $okay;
1.31      www      11472: }
                   11473: 
1.210     www      11474: # --------------------------------------------------------------- Clean-up symb
                   11475: 
                   11476: sub symbclean {
                   11477:     my $symb=shift;
1.568     albertel 11478:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11479: # remove version from map
                   11480:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11481: 
1.210     www      11482: # remove version from URL
                   11483:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11484: 
1.507     www      11485: # remove wrapper
                   11486: 
1.510     www      11487:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11488:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11489:     return $symb;
1.409     www      11490: }
                   11491: 
                   11492: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11493: 
                   11494: sub encode_symb {
                   11495:     my ($map,$resid,$url)=@_;
                   11496:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11497: }
1.409     www      11498: 
                   11499: sub decode_symb {
1.568     albertel 11500:     my $symb=shift;
                   11501:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11502:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11503:     return (&fixversion($map),$resid,&fixversion($url));
                   11504: }
                   11505: 
                   11506: sub fixversion {
                   11507:     my $fn=shift;
1.609     banghart 11508:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11509:     my %bighash;
                   11510:     my $uri=&clutter($fn);
1.620     albertel 11511:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11512: # is this cached?
1.599     albertel 11513:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11514:     if (defined($cached)) { return $result; }
                   11515: # unfortunately not cached, or expired
1.620     albertel 11516:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11517: 	    &GDBM_READER(),0640)) {
                   11518:  	if ($bighash{'version_'.$uri}) {
                   11519:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11520:  	    unless (($version eq 'mostrecent') || 
                   11521: 		    ($version==&getversion($uri))) {
1.440     www      11522:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11523:  	    }
                   11524:  	}
                   11525:  	untie %bighash;
1.413     www      11526:     }
1.599     albertel 11527:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11528: }
                   11529: 
                   11530: sub deversion {
                   11531:     my $url=shift;
                   11532:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11533:     return $url;
1.210     www      11534: }
                   11535: 
1.31      www      11536: # ------------------------------------------------------ Return symb list entry
                   11537: 
                   11538: sub symbread {
1.1282    raeburn  11539:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11540:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11541:     if (defined($env{$cache_str})) {
                   11542:         if ($ignorecachednull) {
                   11543:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11544:         } else {
                   11545:             return $env{$cache_str};
                   11546:         }
                   11547:     }
1.242     www      11548: # no filename provided? try from environment
1.1265    raeburn  11549:     unless ($thisfn) {
1.620     albertel 11550:         if ($env{'request.symb'}) {
                   11551: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11552: 	}
1.620     albertel 11553: 	$thisfn=$env{'request.filename'};
1.44      www      11554:     }
1.569     albertel 11555:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11556: # is that filename actually a symb? Verify, clean, and return
                   11557:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11558: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11559: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11560: 	}
1.242     www      11561:     }
1.44      www      11562:     $thisfn=declutter($thisfn);
1.31      www      11563:     my %hash;
1.37      www      11564:     my %bighash;
                   11565:     my $syval='';
1.620     albertel 11566:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11567:         my $targetfn = $thisfn;
1.609     banghart 11568:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11569:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11570:         }
1.687     albertel 11571: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11572: 	    $targetfn=$1;
                   11573: 	}
1.620     albertel 11574:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11575:                       &GDBM_READER(),0640)) {
1.481     raeburn  11576: 	    $syval=$hash{$targetfn};
1.37      www      11577:             untie(%hash);
                   11578:         }
                   11579: # ---------------------------------------------------------- There was an entry
                   11580:         if ($syval) {
1.601     albertel 11581: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11582: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11583: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11584: 		    #return $env{$cache_str}='';
1.601     albertel 11585: 		#}    
                   11586: 		#$syval.=$1;
                   11587: 	    #}
1.37      www      11588:         } else {
                   11589: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11590:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11591:                             &GDBM_READER(),0640)) {
1.37      www      11592: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11593:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11594:               unless ($ids) { 
                   11595:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11596:               }
                   11597:               unless ($ids) {
                   11598: # alias?
                   11599: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11600:               }
1.37      www      11601:               if ($ids) {
                   11602: # ------------------------------------------------------------------- Has ID(s)
                   11603:                  my @possibilities=split(/\,/,$ids);
1.39      www      11604:                  if ($#possibilities==0) {
                   11605: # ----------------------------------------------- There is only one possibility
1.37      www      11606: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11607: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11608: 						    $resid,$thisfn);
1.1282    raeburn  11609:                      if (ref($possibles) eq 'HASH') {
                   11610:                          $possibles->{$syval} = 1;    
                   11611:                      }
                   11612:                      if ($checkforblock) {
                   11613:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11614:                          if (@blockers) {
                   11615:                              $syval = '';
                   11616:                              return;
                   11617:                          }
                   11618:                      }
                   11619:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11620: # ------------------------------------------ There is more than one possibility
                   11621:                      my $realpossible=0;
1.800     albertel 11622:                      foreach my $id (@possibilities) {
                   11623: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11624:                          my $canaccess;
                   11625:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11626:                              $canaccess = 1;
                   11627:                          } else { 
                   11628:                              $canaccess = &allowed('bre',$file);
                   11629:                          }
                   11630:                          if ($canaccess) {
                   11631:          		     my ($mapid,$resid)=split(/\./,$id);
                   11632:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11633:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11634: 						             $resid,$thisfn);
                   11635:                                  if (ref($possibles) eq 'HASH') {
                   11636:                                      $possibles->{$syval} = 1;
                   11637:                                  }
                   11638:                                  if ($checkforblock) {
                   11639:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11640:                                      unless (@blockers > 0) {
                   11641:                                          $syval = $poss_syval;
                   11642:                                          $realpossible++;
                   11643:                                      }
                   11644:                                  } else {
                   11645:                                      $syval = $poss_syval;
                   11646:                                      $realpossible++;
                   11647:                                  }
                   11648:                              }
1.39      www      11649: 			 }
1.191     harris41 11650:                      }
1.39      www      11651: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11652:                  } else {
                   11653:                      $syval='';
1.37      www      11654:                  }
                   11655: 	      }
1.1282    raeburn  11656:               untie(%bighash);
1.481     raeburn  11657:            }
1.31      www      11658:         }
1.62      www      11659:         if ($syval) {
1.620     albertel 11660: 	    return $env{$cache_str}=$syval;
1.62      www      11661:         }
1.31      www      11662:     }
1.949     raeburn  11663:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11664:     return $env{$cache_str}='';
1.31      www      11665: }
                   11666: 
                   11667: # ---------------------------------------------------------- Return random seed
                   11668: 
1.32      www      11669: sub numval {
                   11670:     my $txt=shift;
                   11671:     $txt=~tr/A-J/0-9/;
                   11672:     $txt=~tr/a-j/0-9/;
                   11673:     $txt=~tr/K-T/0-9/;
                   11674:     $txt=~tr/k-t/0-9/;
                   11675:     $txt=~tr/U-Z/0-5/;
                   11676:     $txt=~tr/u-z/0-5/;
                   11677:     $txt=~s/\D//g;
1.564     albertel 11678:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11679:     return int($txt);
1.368     albertel 11680: }
                   11681: 
1.484     albertel 11682: sub numval2 {
                   11683:     my $txt=shift;
                   11684:     $txt=~tr/A-J/0-9/;
                   11685:     $txt=~tr/a-j/0-9/;
                   11686:     $txt=~tr/K-T/0-9/;
                   11687:     $txt=~tr/k-t/0-9/;
                   11688:     $txt=~tr/U-Z/0-5/;
                   11689:     $txt=~tr/u-z/0-5/;
                   11690:     $txt=~s/\D//g;
                   11691:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11692:     my $total;
                   11693:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11694:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11695:     return int($total);
                   11696: }
                   11697: 
1.575     albertel 11698: sub numval3 {
                   11699:     use integer;
                   11700:     my $txt=shift;
                   11701:     $txt=~tr/A-J/0-9/;
                   11702:     $txt=~tr/a-j/0-9/;
                   11703:     $txt=~tr/K-T/0-9/;
                   11704:     $txt=~tr/k-t/0-9/;
                   11705:     $txt=~tr/U-Z/0-5/;
                   11706:     $txt=~tr/u-z/0-5/;
                   11707:     $txt=~s/\D//g;
                   11708:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11709:     my $total;
                   11710:     foreach my $val (@txts) { $total+=$val; }
                   11711:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11712:     return $total;
                   11713: }
                   11714: 
1.675     albertel 11715: sub digest {
                   11716:     my ($data)=@_;
                   11717:     my $digest=&Digest::MD5::md5($data);
                   11718:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11719:     my ($e,$f);
                   11720:     {
                   11721:         use integer;
                   11722:         $e=($a+$b);
                   11723:         $f=($c+$d);
                   11724:         if ($_64bit) {
                   11725:             $e=(($e<<32)>>32);
                   11726:             $f=(($f<<32)>>32);
                   11727:         }
                   11728:     }
                   11729:     if (wantarray) {
                   11730: 	return ($e,$f);
                   11731:     } else {
                   11732: 	my $g;
                   11733: 	{
                   11734: 	    use integer;
                   11735: 	    $g=($e+$f);
                   11736: 	    if ($_64bit) {
                   11737: 		$g=(($g<<32)>>32);
                   11738: 	    }
                   11739: 	}
                   11740: 	return $g;
                   11741:     }
                   11742: }
                   11743: 
1.368     albertel 11744: sub latest_rnd_algorithm_id {
1.675     albertel 11745:     return '64bit5';
1.366     albertel 11746: }
1.32      www      11747: 
1.503     albertel 11748: sub get_rand_alg {
                   11749:     my ($courseid)=@_;
1.790     albertel 11750:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11751:     if ($courseid) {
1.620     albertel 11752: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11753:     }
                   11754:     return &latest_rnd_algorithm_id();
                   11755: }
                   11756: 
1.562     albertel 11757: sub validCODE {
                   11758:     my ($CODE)=@_;
                   11759:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11760:     return 0;
                   11761: }
                   11762: 
1.491     albertel 11763: sub getCODE {
1.620     albertel 11764:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11765:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11766: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11767: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11768: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11769:     }
                   11770:     return undef;
                   11771: }
1.1133    foxr     11772: #
                   11773: #  Determines the random seed for a specific context:
                   11774: #
                   11775: # parameters:
                   11776: #   symb      - in course context the symb for the seed.
                   11777: #   course_id - The course id of the form domain_coursenum.
                   11778: #   domain    - Domain for the user.
                   11779: #   course    - Course for the user.
                   11780: #   cenv      - environment of the course.
                   11781: #
                   11782: # NOTE:
                   11783: #   All parameters are picked out of the environment if missing
                   11784: #   or not defined.
                   11785: #   If a symb cannot be determined the current time is used instead.
                   11786: #
                   11787: #  For a given well defined symb, courside, domain, username,
                   11788: #  and course environment, the seed is reproducible.
                   11789: #
1.31      www      11790: sub rndseed {
1.1133    foxr     11791:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11792:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11793:     if (!defined($symb)) {
1.366     albertel 11794: 	unless ($symb=$wsymb) { return time; }
                   11795:     }
1.1146    foxr     11796:     if (!defined $courseid) { 
                   11797: 	$courseid=$wcourseid; 
                   11798:     }
                   11799:     if (!defined $domain) { $domain=$wdomain; }
                   11800:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11801: 
                   11802:     my $which;
                   11803:     if (defined($cenv->{'rndseed'})) {
                   11804: 	$which = $cenv->{'rndseed'};
                   11805:     } else {
                   11806: 	$which =&get_rand_alg($courseid);
                   11807:     }
1.491     albertel 11808:     if (defined(&getCODE())) {
1.1133    foxr     11809: 
1.675     albertel 11810: 	if ($which eq '64bit5') {
                   11811: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11812: 	} elsif ($which eq '64bit4') {
1.575     albertel 11813: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11814: 	} else {
                   11815: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11816: 	}
1.675     albertel 11817:     } elsif ($which eq '64bit5') {
                   11818: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11819:     } elsif ($which eq '64bit4') {
                   11820: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11821:     } elsif ($which eq '64bit3') {
                   11822: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11823:     } elsif ($which eq '64bit2') {
                   11824: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11825:     } elsif ($which eq '64bit') {
                   11826: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11827:     }
                   11828:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11829: }
                   11830: 
                   11831: sub rndseed_32bit {
                   11832:     my ($symb,$courseid,$domain,$username)=@_;
                   11833:     {
                   11834: 	use integer;
                   11835: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11836: 	my $symbseed=numval($symb) << 22;
                   11837: 	my $namechck=unpack("%32C*",$username) << 17;
                   11838: 	my $nameseed=numval($username) << 12;
                   11839: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11840: 	my $courseseed=unpack("%32C*",$courseid);
                   11841: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11842: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11843: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11844: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11845: 	return $num;
                   11846:     }
                   11847: }
                   11848: 
                   11849: sub rndseed_64bit {
                   11850:     my ($symb,$courseid,$domain,$username)=@_;
                   11851:     {
                   11852: 	use integer;
                   11853: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11854: 	my $symbseed=numval($symb) << 10;
                   11855: 	my $namechck=unpack("%32S*",$username);
                   11856: 	
                   11857: 	my $nameseed=numval($username) << 21;
                   11858: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11859: 	my $courseseed=unpack("%32S*",$courseid);
                   11860: 	
                   11861: 	my $num1=$symbchck+$symbseed+$namechck;
                   11862: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11863: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11864: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11865: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11866: 	return "$num1,$num2";
1.155     albertel 11867:     }
1.366     albertel 11868: }
                   11869: 
1.443     albertel 11870: sub rndseed_64bit2 {
                   11871:     my ($symb,$courseid,$domain,$username)=@_;
                   11872:     {
                   11873: 	use integer;
                   11874: 	# strings need to be an even # of cahracters long, it it is odd the
                   11875:         # last characters gets thrown away
                   11876: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11877: 	my $symbseed=numval($symb) << 10;
                   11878: 	my $namechck=unpack("%32S*",$username.' ');
                   11879: 	
                   11880: 	my $nameseed=numval($username) << 21;
1.501     albertel 11881: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11882: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11883: 	
                   11884: 	my $num1=$symbchck+$symbseed+$namechck;
                   11885: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11886: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11887: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11888: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11889: 	return "$num1,$num2";
                   11890:     }
                   11891: }
                   11892: 
                   11893: sub rndseed_64bit3 {
                   11894:     my ($symb,$courseid,$domain,$username)=@_;
                   11895:     {
                   11896: 	use integer;
                   11897: 	# strings need to be an even # of cahracters long, it it is odd the
                   11898:         # last characters gets thrown away
                   11899: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11900: 	my $symbseed=numval2($symb) << 10;
                   11901: 	my $namechck=unpack("%32S*",$username.' ');
                   11902: 	
                   11903: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11904: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11905: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11906: 	
                   11907: 	my $num1=$symbchck+$symbseed+$namechck;
                   11908: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11909: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11910: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11911: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11912: 	
1.503     albertel 11913: 	return "$num1:$num2";
1.443     albertel 11914:     }
                   11915: }
                   11916: 
1.575     albertel 11917: sub rndseed_64bit4 {
                   11918:     my ($symb,$courseid,$domain,$username)=@_;
                   11919:     {
                   11920: 	use integer;
                   11921: 	# strings need to be an even # of cahracters long, it it is odd the
                   11922:         # last characters gets thrown away
                   11923: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11924: 	my $symbseed=numval3($symb) << 10;
                   11925: 	my $namechck=unpack("%32S*",$username.' ');
                   11926: 	
                   11927: 	my $nameseed=numval3($username) << 21;
                   11928: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11929: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11930: 	
                   11931: 	my $num1=$symbchck+$symbseed+$namechck;
                   11932: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11933: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11934: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11935: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11936: 	
1.575     albertel 11937: 	return "$num1:$num2";
                   11938:     }
                   11939: }
                   11940: 
1.675     albertel 11941: sub rndseed_64bit5 {
                   11942:     my ($symb,$courseid,$domain,$username)=@_;
                   11943:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11944:     return "$num1:$num2";
                   11945: }
                   11946: 
1.366     albertel 11947: sub rndseed_CODE_64bit {
                   11948:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11949:     {
1.366     albertel 11950: 	use integer;
1.443     albertel 11951: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11952: 	my $symbseed=numval2($symb);
1.491     albertel 11953: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11954: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11955: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11956: 	my $num1=$symbseed+$CODEchck;
                   11957: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11958: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11959: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11960: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11961: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11962: 	return "$num1:$num2";
1.366     albertel 11963:     }
                   11964: }
                   11965: 
1.575     albertel 11966: sub rndseed_CODE_64bit4 {
                   11967:     my ($symb,$courseid,$domain,$username)=@_;
                   11968:     {
                   11969: 	use integer;
                   11970: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11971: 	my $symbseed=numval3($symb);
                   11972: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11973: 	my $CODEseed=numval3(&getCODE());
                   11974: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11975: 	my $num1=$symbseed+$CODEchck;
                   11976: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11977: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11978: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11979: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11980: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11981: 	return "$num1:$num2";
                   11982:     }
                   11983: }
                   11984: 
1.675     albertel 11985: sub rndseed_CODE_64bit5 {
                   11986:     my ($symb,$courseid,$domain,$username)=@_;
                   11987:     my $code = &getCODE();
                   11988:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11989:     return "$num1:$num2";
                   11990: }
                   11991: 
1.366     albertel 11992: sub setup_random_from_rndseed {
                   11993:     my ($rndseed)=@_;
1.503     albertel 11994:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11995:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11996:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11997:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11998:         } else {
                   11999:             &Math::Random::random_set_seed($num1,$num2);
                   12000:         }
1.366     albertel 12001:     } else {
                   12002: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12003:     }
1.36      albertel 12004: }
                   12005: 
1.474     albertel 12006: sub latest_receipt_algorithm_id {
1.835     albertel 12007:     return 'receipt3';
1.474     albertel 12008: }
                   12009: 
1.480     www      12010: sub recunique {
                   12011:     my $fucourseid=shift;
                   12012:     my $unique;
1.835     albertel 12013:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12014: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12015: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12016:     } else {
                   12017: 	$unique=$perlvar{'lonReceipt'};
                   12018:     }
                   12019:     return unpack("%32C*",$unique);
                   12020: }
                   12021: 
                   12022: sub recprefix {
                   12023:     my $fucourseid=shift;
                   12024:     my $prefix;
1.835     albertel 12025:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12026: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12027: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12028:     } else {
                   12029: 	$prefix=$perlvar{'lonHostID'};
                   12030:     }
                   12031:     return unpack("%32C*",$prefix);
                   12032: }
                   12033: 
1.76      www      12034: sub ireceipt {
1.474     albertel 12035:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12036: 
                   12037:     my $return =&recprefix($fucourseid).'-';
                   12038: 
                   12039:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12040: 	$env{'request.state'} eq 'construct') {
                   12041: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12042: 	return $return;
                   12043:     }
                   12044: 
1.76      www      12045:     my $cuname=unpack("%32C*",$funame);
                   12046:     my $cudom=unpack("%32C*",$fudom);
                   12047:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12048:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12049:     my $cunique=&recunique($fucourseid);
1.474     albertel 12050:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12051:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12052: 
1.790     albertel 12053: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12054: 			       
                   12055: 	$return.= ($cunique%$cuname+
                   12056: 		   $cunique%$cudom+
                   12057: 		   $cusymb%$cuname+
                   12058: 		   $cusymb%$cudom+
                   12059: 		   $cucourseid%$cuname+
                   12060: 		   $cucourseid%$cudom+
                   12061: 		   $cpart%$cuname+
                   12062: 		   $cpart%$cudom);
                   12063:     } else {
                   12064: 	$return.= ($cunique%$cuname+
                   12065: 		   $cunique%$cudom+
                   12066: 		   $cusymb%$cuname+
                   12067: 		   $cusymb%$cudom+
                   12068: 		   $cucourseid%$cuname+
                   12069: 		   $cucourseid%$cudom);
                   12070:     }
                   12071:     return $return;
1.76      www      12072: }
                   12073: 
                   12074: sub receipt {
1.474     albertel 12075:     my ($part)=@_;
1.790     albertel 12076:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12077:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12078: }
1.260     ng       12079: 
1.790     albertel 12080: sub whichuser {
                   12081:     my ($passedsymb)=@_;
                   12082:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12083:     if (defined($env{'form.grade_symb'})) {
                   12084: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12085: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12086: 	if (!$allowed &&
                   12087: 	    exists($env{'request.course.sec'}) &&
                   12088: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12089: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12090: 			      '/'.$env{'request.course.sec'});
                   12091: 	}
                   12092: 	if ($allowed) {
                   12093: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12094: 	    $courseid=$tmp_courseid;
                   12095: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12096: 	    ($name)=&get_env_multiple('form.grade_username');
                   12097: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12098: 	}
                   12099:     }
                   12100:     if (!$passedsymb) {
                   12101: 	$symb=&symbread();
                   12102:     } else {
                   12103: 	$symb=$passedsymb;
                   12104:     }
                   12105:     $courseid=$env{'request.course.id'};
                   12106:     $domain=$env{'user.domain'};
                   12107:     $name=$env{'user.name'};
                   12108:     if ($name eq 'public' && $domain eq 'public') {
                   12109: 	if (!defined($env{'form.username'})) {
                   12110: 	    $env{'form.username'}.=time.rand(10000000);
                   12111: 	}
                   12112: 	$name.=$env{'form.username'};
                   12113:     }
                   12114:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12115: 
                   12116: }
                   12117: 
1.36      albertel 12118: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12119: # returns either the contents of the file or 
                   12120: # -1 if the file doesn't exist
1.481     raeburn  12121: #
                   12122: # if the target is a file that was uploaded via DOCS, 
                   12123: # a check will be made to see if a current copy exists on the local server,
                   12124: # if it does this will be served, otherwise a copy will be retrieved from
                   12125: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12126: # the local server.   
1.472     albertel 12127: 
1.36      albertel 12128: sub getfile {
1.538     albertel 12129:     my ($file) = @_;
1.609     banghart 12130:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12131:     &repcopy($file);
                   12132:     return &readfile($file);
                   12133: }
                   12134: 
                   12135: sub repcopy_userfile {
                   12136:     my ($file)=@_;
1.1142    raeburn  12137:     my $londocroot = $perlvar{'lonDocRoot'};
                   12138:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12139:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12140:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12141: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12142:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12143:     if (-e "$file") {
1.828     www      12144: # we already have a local copy, check it out
1.538     albertel 12145: 	my @fileinfo = stat($file);
1.828     www      12146: 	my $rtncode;
                   12147: 	my $info;
1.538     albertel 12148: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12149: 	if ($lwpresp ne 'ok') {
1.828     www      12150: # there is no such file anymore, even though we had a local copy
1.482     albertel 12151: 	    if ($rtncode eq '404') {
1.538     albertel 12152: 		unlink($file);
1.482     albertel 12153: 	    }
                   12154: 	    return -1;
                   12155: 	}
                   12156: 	if ($info < $fileinfo[9]) {
1.828     www      12157: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12158: 	    return 'ok';
1.828     www      12159: 	} else {
                   12160: # the file is outdated, get rid of it
                   12161: 	    unlink($file);
1.482     albertel 12162: 	}
1.828     www      12163:     }
                   12164: # one way or the other, at this point, we don't have the file
                   12165: # construct the correct path for the file
                   12166:     my @parts = ($cdom,$cnum); 
                   12167:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12168: 	push @parts, split(/\//,$1);
                   12169:     }
                   12170:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12171:     foreach my $part (@parts) {
                   12172: 	$path .= '/'.$part;
                   12173: 	if (!-e $path) {
                   12174: 	    mkdir($path,0770);
1.482     albertel 12175: 	}
                   12176:     }
1.828     www      12177: # now the path exists for sure
                   12178: # get a user agent
                   12179:     my $ua=new LWP::UserAgent;
                   12180:     my $transferfile=$file.'.in.transfer';
                   12181: # FIXME: this should flock
                   12182:     if (-e $transferfile) { return 'ok'; }
                   12183:     my $request;
                   12184:     $uri=~s/^\///;
1.980     raeburn  12185:     my $homeserver = &homeserver($cnum,$cdom);
                   12186:     my $protocol = $protocol{$homeserver};
                   12187:     $protocol = 'http' if ($protocol ne 'https');
                   12188:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12189:     my $response=$ua->request($request,$transferfile);
                   12190: # did it work?
                   12191:     if ($response->is_error()) {
                   12192: 	unlink($transferfile);
                   12193: 	&logthis("Userfile repcopy failed for $uri");
                   12194: 	return -1;
                   12195:     }
                   12196: # worked, rename the transfer file
                   12197:     rename($transferfile,$file);
1.607     raeburn  12198:     return 'ok';
1.481     raeburn  12199: }
                   12200: 
1.517     albertel 12201: sub tokenwrapper {
                   12202:     my $uri=shift;
1.980     raeburn  12203:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12204:     $uri=~s|^/||;
1.620     albertel 12205:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12206:     my $token=$1;
1.552     albertel 12207:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12208:     if ($udom && $uname && $file) {
                   12209: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12210:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12211:         my $homeserver = &homeserver($uname,$udom);
                   12212:         my $protocol = $protocol{$homeserver};
                   12213:         $protocol = 'http' if ($protocol ne 'https');
                   12214:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12215:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12216:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12217:     } else {
                   12218:         return '/adm/notfound.html';
                   12219:     }
                   12220: }
                   12221: 
1.828     www      12222: # call with reqtype HEAD: get last modification time
                   12223: # call with reqtype GET: get the file contents
                   12224: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12225: #
1.481     raeburn  12226: sub getuploaded {
                   12227:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12228:     $uri=~s/^\///;
1.980     raeburn  12229:     my $homeserver = &homeserver($cnum,$cdom);
                   12230:     my $protocol = $protocol{$homeserver};
                   12231:     $protocol = 'http' if ($protocol ne 'https');
                   12232:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12233:     my $ua=new LWP::UserAgent;
                   12234:     my $request=new HTTP::Request($reqtype,$uri);
                   12235:     my $response=$ua->request($request);
                   12236:     $$rtncode = $response->code;
1.482     albertel 12237:     if (! $response->is_success()) {
                   12238: 	return 'failed';
                   12239:     }      
                   12240:     if ($reqtype eq 'HEAD') {
1.486     www      12241: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12242:     } elsif ($reqtype eq 'GET') {
                   12243: 	$$info = $response->content;
1.472     albertel 12244:     }
1.482     albertel 12245:     return 'ok';
1.36      albertel 12246: }
                   12247: 
1.481     raeburn  12248: sub readfile {
                   12249:     my $file = shift;
                   12250:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12251:     my $fh;
                   12252:     open($fh,"<$file");
                   12253:     my $a='';
1.800     albertel 12254:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12255:     return $a;
                   12256: }
                   12257: 
1.36      albertel 12258: sub filelocation {
1.590     banghart 12259:     my ($dir,$file) = @_;
                   12260:     my $location;
                   12261:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12262: 
                   12263:     if ($file =~ m-^/adm/-) {
                   12264: 	$file=~s-^/adm/wrapper/-/-;
                   12265: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12266:     }
1.882     albertel 12267: 
1.1139    www      12268:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12269:         $location = $file;
1.609     banghart 12270:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12271:         my ($udom,$uname,$filename)=
1.811     albertel 12272:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12273:         my $home=&homeserver($uname,$udom);
                   12274:         my $is_me=0;
                   12275:         my @ids=&current_machine_ids();
                   12276:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12277:         if ($is_me) {
1.1117    foxr     12278:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12279:         } else {
                   12280:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12281:   	      $udom.'/'.$uname.'/'.$filename;
                   12282:         }
1.882     albertel 12283:     } elsif ($file =~ m-^/adm/-) {
                   12284: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12285:     } else {
                   12286:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12287:         $file=~s:^/(res|priv)/:/:;
                   12288:         my $space=$1;
1.590     banghart 12289:         if ( !( $file =~ m:^/:) ) {
                   12290:             $location = $dir. '/'.$file;
                   12291:         } else {
1.1142    raeburn  12292:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12293:         }
1.59      albertel 12294:     }
1.590     banghart 12295:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12296:     while ($location=~m{/\.\./}) {
                   12297: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12298: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12299: 	} else {
                   12300: 	    $location=~ s{/\.\./}{/}g;
                   12301: 	}
                   12302:     } #remove dir/..
1.590     banghart 12303:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12304:     return $location;
1.46      www      12305: }
1.36      albertel 12306: 
1.46      www      12307: sub hreflocation {
                   12308:     my ($dir,$file)=@_;
1.980     raeburn  12309:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12310: 	$file=filelocation($dir,$file);
1.700     albertel 12311:     } elsif ($file=~m-^/adm/-) {
                   12312: 	$file=~s-^/adm/wrapper/-/-;
                   12313: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12314:     }
                   12315:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12316: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12317:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12318: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12319: 	        {/uploaded/$1/$2/}x;
1.46      www      12320:     }
1.913     albertel 12321:     if ($file=~ m{^/userfiles/}) {
                   12322: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12323:     }
1.462     albertel 12324:     return $file;
1.465     albertel 12325: }
                   12326: 
1.1139    www      12327: 
                   12328: 
                   12329: 
                   12330: 
1.465     albertel 12331: sub current_machine_domains {
1.853     albertel 12332:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12333: }
                   12334: 
                   12335: sub machine_domains {
                   12336:     my ($hostname) = @_;
1.465     albertel 12337:     my @domains;
1.838     albertel 12338:     my %hostname = &all_hostnames();
1.465     albertel 12339:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12340: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12341: 	if ($hostname eq $name) {
1.844     albertel 12342: 	    push(@domains,&host_domain($id));
1.465     albertel 12343: 	}
                   12344:     }
                   12345:     return @domains;
                   12346: }
                   12347: 
                   12348: sub current_machine_ids {
1.853     albertel 12349:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12350: }
                   12351: 
                   12352: sub machine_ids {
                   12353:     my ($hostname) = @_;
                   12354:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12355:     my @ids;
1.888     albertel 12356:     my %name_to_host = &all_names();
1.889     albertel 12357:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12358: 	return @{ $name_to_host{$hostname} };
                   12359:     }
                   12360:     return;
1.31      www      12361: }
                   12362: 
1.824     raeburn  12363: sub additional_machine_domains {
                   12364:     my @domains;
                   12365:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12366:     while( my $line = <$fh>) {
                   12367:         $line =~ s/\s//g;
                   12368:         push(@domains,$line);
                   12369:     }
                   12370:     return @domains;
                   12371: }
                   12372: 
                   12373: sub default_login_domain {
                   12374:     my $domain = $perlvar{'lonDefDomain'};
                   12375:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12376:     foreach my $posdom (&current_machine_domains(),
                   12377:                         &additional_machine_domains()) {
                   12378:         if (lc($posdom) eq lc($testdomain)) {
                   12379:             $domain=$posdom;
                   12380:             last;
                   12381:         }
                   12382:     }
                   12383:     return $domain;
                   12384: }
                   12385: 
1.31      www      12386: # ------------------------------------------------------------- Declutters URLs
                   12387: 
                   12388: sub declutter {
                   12389:     my $thisfn=shift;
1.569     albertel 12390:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12391:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12392:         $thisfn=~s{^/home/httpd/html}{};
                   12393:     }
1.31      www      12394:     $thisfn=~s/^\///;
1.697     albertel 12395:     $thisfn=~s|^adm/wrapper/||;
                   12396:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12397:     $thisfn=~s/^res\///;
1.1172    bisitz   12398:     $thisfn=~s/^priv\///;
1.1032    raeburn  12399:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12400:         $thisfn=~s/\?.+$//;
                   12401:     }
1.268     www      12402:     return $thisfn;
                   12403: }
                   12404: 
                   12405: # ------------------------------------------------------------- Clutter up URLs
                   12406: 
                   12407: sub clutter {
                   12408:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12409:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12410: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12411:        $thisfn='/res'.$thisfn; 
                   12412:     }
1.1031    raeburn  12413:     if ($thisfn !~m|^/adm|) {
                   12414: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12415: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12416: 	} else {
                   12417: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12418: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12419: 	    if ($embstyle eq 'ssi'
                   12420: 		|| ($embstyle eq 'hdn')
                   12421: 		|| ($embstyle eq 'rat')
                   12422: 		|| ($embstyle eq 'prv')
                   12423: 		|| ($embstyle eq 'ign')) {
                   12424: 		#do nothing with these
                   12425: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12426: 		|| ($embstyle eq 'emb')
                   12427: 		|| ($embstyle eq 'wrp')) {
                   12428: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12429: 	    } elsif ($embstyle eq 'unk'
                   12430: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12431: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12432: 	    } else {
1.718     www      12433: #		&logthis("Got a blank emb style");
1.695     albertel 12434: 	    }
1.694     albertel 12435: 	}
1.1298    raeburn  12436:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12437:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12438:     }
1.31      www      12439:     return $thisfn;
1.12      www      12440: }
                   12441: 
1.787     albertel 12442: sub clutter_with_no_wrapper {
                   12443:     my $uri = &clutter(shift);
                   12444:     if ($uri =~ m-^/adm/-) {
                   12445: 	$uri =~ s-^/adm/wrapper/-/-;
                   12446: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12447:     }
                   12448:     return $uri;
                   12449: }
                   12450: 
1.557     albertel 12451: sub freeze_escape {
                   12452:     my ($value)=@_;
                   12453:     if (ref($value)) {
                   12454: 	$value=&nfreeze($value);
                   12455: 	return '__FROZEN__'.&escape($value);
                   12456:     }
                   12457:     return &escape($value);
                   12458: }
                   12459: 
1.11      www      12460: 
1.557     albertel 12461: sub thaw_unescape {
                   12462:     my ($value)=@_;
                   12463:     if ($value =~ /^__FROZEN__/) {
                   12464: 	substr($value,0,10,undef);
                   12465: 	$value=&unescape($value);
                   12466: 	return &thaw($value);
                   12467:     }
                   12468:     return &unescape($value);
                   12469: }
                   12470: 
1.436     albertel 12471: sub correct_line_ends {
                   12472:     my ($result)=@_;
                   12473:     $$result =~s/\r\n/\n/mg;
                   12474:     $$result =~s/\r/\n/mg;
1.415     albertel 12475: }
1.1       albertel 12476: # ================================================================ Main Program
                   12477: 
1.184     www      12478: sub goodbye {
1.204     albertel 12479:    &logthis("Starting Shut down");
1.443     albertel 12480: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12481:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12482: #converted
1.599     albertel 12483: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12484:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12485: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12486: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12487: #1.1 only
1.870     albertel 12488: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12489: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12490: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12491: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12492:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12493:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12494:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12495:    &flushcourselogs();
                   12496:    &logthis("Shutting down");
                   12497: }
                   12498: 
1.852     albertel 12499: sub get_dns {
1.1210    raeburn  12500:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12501:     if (!$ignore_cache) {
                   12502: 	my ($content,$cached)=
                   12503: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12504: 	if ($cached) {
1.1210    raeburn  12505: 	    &$func($content,$hashref);
1.869     albertel 12506: 	    return;
                   12507: 	}
                   12508:     }
                   12509: 
                   12510:     my %alldns;
1.852     albertel 12511:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12512:     foreach my $dns (<$config>) {
                   12513: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12514:         my $line = $1;
                   12515:         my ($host,$protocol) = split(/:/,$line);
                   12516:         if ($protocol ne 'https') {
                   12517:             $protocol = 'http';
                   12518:         }
                   12519: 	$alldns{$host} = $protocol;
1.869     albertel 12520:     }
                   12521:     while (%alldns) {
1.1263    raeburn  12522: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12523: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12524:         $ua->timeout(30);
1.979     raeburn  12525: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12526: 	my $response=$ua->request($request);
1.979     raeburn  12527:         delete($alldns{$dns});
1.852     albertel 12528: 	next if ($response->is_error());
                   12529: 	my @content = split("\n",$response->content);
1.1210    raeburn  12530: 	unless ($nocache) {
1.1219    raeburn  12531: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12532: 	}
                   12533: 	&$func(\@content,$hashref);
1.869     albertel 12534: 	return;
1.852     albertel 12535:     }
                   12536:     close($config);
1.871     albertel 12537:     my $which = (split('/',$url))[3];
                   12538:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12539:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12540:     my @content = <$config>;
1.1210    raeburn  12541:     &$func(\@content,$hashref);
                   12542:     return;
                   12543: }
                   12544: 
                   12545: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12546: sub parse_dns_checksums_tab {
1.1210    raeburn  12547:     my ($lines,$hashref) = @_;
1.1264    raeburn  12548:     my $lonhost = $perlvar{'lonHostID'};
                   12549:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12550:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12551:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12552:     my $webconfdir = '/etc/httpd/conf';
                   12553:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12554:         $webconfdir = '/etc/apache2';
                   12555:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12556:         if ($1 >= 10) {
                   12557:             $webconfdir = '/etc/apache2';
                   12558:         }
                   12559:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12560:         if ($1 >= 10.0) {
                   12561:             $webconfdir = '/etc/apache2';
                   12562:         }
                   12563:     }
1.1210    raeburn  12564:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12565:     my (%chksum,%revnum);
                   12566:     if (ref($lines) eq 'ARRAY') {
                   12567:         chomp(@{$lines});
1.1238    raeburn  12568:         my $version = shift(@{$lines});
                   12569:         if ($version eq $release) {  
1.1210    raeburn  12570:             foreach my $line (@{$lines}) {
1.1238    raeburn  12571:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12572:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12573:                     if ($webconfdir eq '/etc/apache2') {
                   12574:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12575:                     }
                   12576:                 }
1.1238    raeburn  12577:                 $chksum{$file} = $shasum;
                   12578:                 $revnum{$file} = $version;
1.1210    raeburn  12579:             }
                   12580:             if (ref($hashref) eq 'HASH') {
                   12581:                 %{$hashref} = (
                   12582:                                 sums     => \%chksum,
                   12583:                                 versions => \%revnum,
                   12584:                               );
                   12585:             }
                   12586:         }
                   12587:     }
1.869     albertel 12588:     return;
1.852     albertel 12589: }
1.1210    raeburn  12590: 
                   12591: sub fetch_dns_checksums {
1.1238    raeburn  12592:     my %checksums;
                   12593:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12594:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12595:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12596:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12597:              \%checksums);
1.1210    raeburn  12598:     return \%checksums;
                   12599: }
                   12600: 
1.327     albertel 12601: # ------------------------------------------------------------ Read domain file
                   12602: {
1.852     albertel 12603:     my $loaded;
1.846     albertel 12604:     my %domain;
                   12605: 
1.852     albertel 12606:     sub parse_domain_tab {
                   12607: 	my ($lines) = @_;
                   12608: 	foreach my $line (@$lines) {
                   12609: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12610: 
1.846     albertel 12611: 	    chomp($line);
1.852     albertel 12612: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12613: 	    my %this_domain;
                   12614: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12615: 			       'lang_def', 'city', 'longi', 'lati',
                   12616: 			       'primary') {
                   12617: 		$this_domain{$field} = shift(@elements);
                   12618: 	    }
                   12619: 	    $domain{$name} = \%this_domain;
1.852     albertel 12620: 	}
                   12621:     }
1.864     albertel 12622: 
                   12623:     sub reset_domain_info {
                   12624: 	undef($loaded);
                   12625: 	undef(%domain);
                   12626:     }
                   12627: 
1.852     albertel 12628:     sub load_domain_tab {
1.1293    raeburn  12629: 	my ($ignore_cache,$nocache) = @_;
                   12630: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12631: 	my $fh;
                   12632: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12633: 	    my @lines = <$fh>;
                   12634: 	    &parse_domain_tab(\@lines);
1.448     albertel 12635: 	}
1.852     albertel 12636: 	close($fh);
                   12637: 	$loaded = 1;
1.327     albertel 12638:     }
1.846     albertel 12639: 
                   12640:     sub domain {
1.852     albertel 12641: 	&load_domain_tab() if (!$loaded);
                   12642: 
1.846     albertel 12643: 	my ($name,$what) = @_;
                   12644: 	return if ( !exists($domain{$name}) );
                   12645: 
                   12646: 	if (!$what) {
                   12647: 	    return $domain{$name}{'description'};
                   12648: 	}
                   12649: 	return $domain{$name}{$what};
                   12650:     }
1.974     raeburn  12651: 
                   12652:     sub domain_info {
                   12653:         &load_domain_tab() if (!$loaded);
                   12654:         return %domain;
                   12655:     }
                   12656: 
1.327     albertel 12657: }
                   12658: 
                   12659: 
1.1       albertel 12660: # ------------------------------------------------------------- Read hosts file
                   12661: {
1.838     albertel 12662:     my %hostname;
1.844     albertel 12663:     my %hostdom;
1.845     albertel 12664:     my %libserv;
1.852     albertel 12665:     my $loaded;
1.888     albertel 12666:     my %name_to_host;
1.1074    raeburn  12667:     my %internetdom;
1.1107    raeburn  12668:     my %LC_dns_serv;
1.852     albertel 12669: 
                   12670:     sub parse_hosts_tab {
                   12671: 	my ($file) = @_;
                   12672: 	foreach my $configline (@$file) {
                   12673: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12674:             chomp($configline);
                   12675: 	    if ($configline =~ /^\^/) {
                   12676:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12677:                     $LC_dns_serv{$1} = 1;
                   12678:                 }
                   12679:                 next;
                   12680:             }
1.1074    raeburn  12681: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12682: 	    $name=~s/\s//g;
                   12683: 	    if ($id && $domain && $role && $name) {
                   12684: 		$hostname{$id}=$name;
1.888     albertel 12685: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12686: 		$hostdom{$id}=$domain;
                   12687: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12688:                 if (defined($protocol)) {
                   12689:                     if ($protocol eq 'https') {
                   12690:                         $protocol{$id} = $protocol;
                   12691:                     } else {
                   12692:                         $protocol{$id} = 'http'; 
                   12693:                     }
1.968     raeburn  12694:                 } else {
1.969     raeburn  12695:                     $protocol{$id} = 'http';
1.968     raeburn  12696:                 }
1.1074    raeburn  12697:                 if (defined($intdom)) {
                   12698:                     $internetdom{$id} = $intdom;
                   12699:                 }
1.852     albertel 12700: 	    }
                   12701: 	}
                   12702:     }
1.864     albertel 12703:     
                   12704:     sub reset_hosts_info {
1.897     albertel 12705: 	&purge_remembered();
1.864     albertel 12706: 	&reset_domain_info();
                   12707: 	&reset_hosts_ip_info();
1.892     albertel 12708: 	undef(%name_to_host);
1.864     albertel 12709: 	undef(%hostname);
                   12710: 	undef(%hostdom);
                   12711: 	undef(%libserv);
                   12712: 	undef($loaded);
                   12713:     }
1.1       albertel 12714: 
1.852     albertel 12715:     sub load_hosts_tab {
1.1293    raeburn  12716: 	my ($ignore_cache,$nocache) = @_;
                   12717: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12718: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12719: 	my @config = <$config>;
                   12720: 	&parse_hosts_tab(\@config);
                   12721: 	close($config);
                   12722: 	$loaded=1;
1.1       albertel 12723:     }
1.852     albertel 12724: 
1.838     albertel 12725:     sub hostname {
1.852     albertel 12726: 	&load_hosts_tab() if (!$loaded);
                   12727: 
1.838     albertel 12728: 	my ($lonid) = @_;
                   12729: 	return $hostname{$lonid};
                   12730:     }
1.845     albertel 12731: 
1.838     albertel 12732:     sub all_hostnames {
1.852     albertel 12733: 	&load_hosts_tab() if (!$loaded);
                   12734: 
1.838     albertel 12735: 	return %hostname;
                   12736:     }
1.845     albertel 12737: 
1.888     albertel 12738:     sub all_names {
1.1293    raeburn  12739:         my ($ignore_cache,$nocache) = @_;
                   12740: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12741: 
                   12742: 	return %name_to_host;
                   12743:     }
                   12744: 
1.974     raeburn  12745:     sub all_host_domain {
                   12746:         &load_hosts_tab() if (!$loaded);
                   12747:         return %hostdom;
                   12748:     }
                   12749: 
1.845     albertel 12750:     sub is_library {
1.852     albertel 12751: 	&load_hosts_tab() if (!$loaded);
                   12752: 
1.845     albertel 12753: 	return exists($libserv{$_[0]});
                   12754:     }
                   12755: 
                   12756:     sub all_library {
1.852     albertel 12757: 	&load_hosts_tab() if (!$loaded);
                   12758: 
1.845     albertel 12759: 	return %libserv;
                   12760:     }
                   12761: 
1.1062    droeschl 12762:     sub unique_library {
                   12763: 	#2x reverse removes all hostnames that appear more than once
                   12764:         my %unique = reverse &all_library();
                   12765:         return reverse %unique;
                   12766:     }
                   12767: 
1.841     albertel 12768:     sub get_servers {
1.852     albertel 12769: 	&load_hosts_tab() if (!$loaded);
                   12770: 
1.841     albertel 12771: 	my ($domain,$type) = @_;
                   12772: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12773: 	                                          : %hostname;
                   12774: 	my %result;
1.842     albertel 12775: 	if (ref($domain) eq 'ARRAY') {
                   12776: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12777: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12778: 		    $result{$host} = $hostname;
                   12779: 		}
                   12780: 	    }
                   12781: 	} else {
                   12782: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12783: 		if ($hostdom{$host} eq $domain) {
                   12784: 		    $result{$host} = $hostname;
                   12785: 		}
1.841     albertel 12786: 	    }
                   12787: 	}
                   12788: 	return %result;
                   12789:     }
1.845     albertel 12790: 
1.1062    droeschl 12791:     sub get_unique_servers {
                   12792:         my %unique = reverse &get_servers(@_);
                   12793: 	return reverse %unique;
                   12794:     }
                   12795: 
1.844     albertel 12796:     sub host_domain {
1.852     albertel 12797: 	&load_hosts_tab() if (!$loaded);
                   12798: 
1.844     albertel 12799: 	my ($lonid) = @_;
                   12800: 	return $hostdom{$lonid};
                   12801:     }
                   12802: 
1.841     albertel 12803:     sub all_domains {
1.852     albertel 12804: 	&load_hosts_tab() if (!$loaded);
                   12805: 
1.841     albertel 12806: 	my %seen;
                   12807: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12808: 	return @uniq;
                   12809:     }
1.1074    raeburn  12810: 
                   12811:     sub internet_dom {
                   12812:         &load_hosts_tab() if (!$loaded);
                   12813: 
                   12814:         my ($lonid) = @_;
                   12815:         return $internetdom{$lonid};
                   12816:     }
1.1107    raeburn  12817: 
                   12818:     sub is_LC_dns {
                   12819:         &load_hosts_tab() if (!$loaded);
                   12820: 
                   12821:         my ($hostname) = @_;
                   12822:         return exists($LC_dns_serv{$hostname});
                   12823:     }
                   12824: 
1.1       albertel 12825: }
                   12826: 
1.847     albertel 12827: { 
                   12828:     my %iphost;
1.856     albertel 12829:     my %name_to_ip;
                   12830:     my %lonid_to_ip;
1.869     albertel 12831: 
1.847     albertel 12832:     sub get_hosts_from_ip {
                   12833: 	my ($ip) = @_;
                   12834: 	my %iphosts = &get_iphost();
                   12835: 	if (ref($iphosts{$ip})) {
                   12836: 	    return @{$iphosts{$ip}};
                   12837: 	}
                   12838: 	return;
1.839     albertel 12839:     }
1.864     albertel 12840:     
                   12841:     sub reset_hosts_ip_info {
                   12842: 	undef(%iphost);
                   12843: 	undef(%name_to_ip);
                   12844: 	undef(%lonid_to_ip);
                   12845:     }
1.856     albertel 12846: 
                   12847:     sub get_host_ip {
                   12848: 	my ($lonid) = @_;
                   12849: 	if (exists($lonid_to_ip{$lonid})) {
                   12850: 	    return $lonid_to_ip{$lonid};
                   12851: 	}
                   12852: 	my $name=&hostname($lonid);
                   12853:    	my $ip = gethostbyname($name);
                   12854: 	return if (!$ip || length($ip) ne 4);
                   12855: 	$ip=inet_ntoa($ip);
                   12856: 	$name_to_ip{$name}   = $ip;
                   12857: 	$lonid_to_ip{$lonid} = $ip;
                   12858: 	return $ip;
                   12859:     }
1.847     albertel 12860:     
                   12861:     sub get_iphost {
1.1293    raeburn  12862: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12863: 
1.869     albertel 12864: 	if (!$ignore_cache) {
                   12865: 	    if (%iphost) {
                   12866: 		return %iphost;
                   12867: 	    }
                   12868: 	    my ($ip_info,$cached)=
                   12869: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12870: 	    if ($cached) {
                   12871: 		%iphost      = %{$ip_info->[0]};
                   12872: 		%name_to_ip  = %{$ip_info->[1]};
                   12873: 		%lonid_to_ip = %{$ip_info->[2]};
                   12874: 		return %iphost;
                   12875: 	    }
                   12876: 	}
1.894     albertel 12877: 
                   12878: 	# get yesterday's info for fallback
                   12879: 	my %old_name_to_ip;
                   12880: 	my ($ip_info,$cached)=
                   12881: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12882: 	if ($cached) {
                   12883: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12884: 	}
                   12885: 
1.1293    raeburn  12886: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 12887: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12888: 	    my $ip;
                   12889: 	    if (!exists($name_to_ip{$name})) {
                   12890: 		$ip = gethostbyname($name);
                   12891: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12892: 		    if (defined($old_name_to_ip{$name})) {
                   12893: 			$ip = $old_name_to_ip{$name};
                   12894: 			&logthis("Can't find $name defaulting to old $ip");
                   12895: 		    } else {
                   12896: 			&logthis("Name $name no IP found");
                   12897: 			next;
                   12898: 		    }
                   12899: 		} else {
                   12900: 		    $ip=inet_ntoa($ip);
1.847     albertel 12901: 		}
                   12902: 		$name_to_ip{$name} = $ip;
                   12903: 	    } else {
                   12904: 		$ip = $name_to_ip{$name};
1.653     albertel 12905: 	    }
1.888     albertel 12906: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12907: 		$lonid_to_ip{$id} = $ip;
                   12908: 	    }
                   12909: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12910: 	}
1.1293    raeburn  12911:         unless ($nocache) {
                   12912: 	    &do_cache_new('iphost','iphost',
                   12913: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12914: 		          48*60*60);
                   12915:         }
1.869     albertel 12916: 
1.847     albertel 12917: 	return %iphost;
1.598     albertel 12918:     }
                   12919: 
1.992     raeburn  12920:     #
                   12921:     #  Given a DNS returns the loncapa host name for that DNS 
                   12922:     # 
                   12923:     sub host_from_dns {
                   12924:         my ($dns) = @_;
                   12925:         my @hosts;
                   12926:         my $ip;
                   12927: 
1.993     raeburn  12928:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12929:             $ip = $name_to_ip{$dns};
                   12930:         }
                   12931:         if (!$ip) {
                   12932:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12933:             if (length($ip) == 4) { 
                   12934: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12935:             }
                   12936:         }
                   12937:         if ($ip) {
                   12938: 	    @hosts = get_hosts_from_ip($ip);
                   12939: 	    return $hosts[0];
                   12940:         }
                   12941:         return undef;
1.986     foxr     12942:     }
1.992     raeburn  12943: 
1.1074    raeburn  12944:     sub get_internet_names {
                   12945:         my ($lonid) = @_;
                   12946:         return if ($lonid eq '');
                   12947:         my ($idnref,$cached)=
                   12948:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12949:         if ($cached) {
                   12950:             return $idnref;
                   12951:         }
                   12952:         my $ip = &get_host_ip($lonid);
                   12953:         my @hosts = &get_hosts_from_ip($ip);
                   12954:         my %iphost = &get_iphost();
                   12955:         my (@idns,%seen);
                   12956:         foreach my $id (@hosts) {
                   12957:             my $dom = &host_domain($id);
                   12958:             my $prim_id = &domain($dom,'primary');
                   12959:             my $prim_ip = &get_host_ip($prim_id);
                   12960:             next if ($seen{$prim_ip});
                   12961:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12962:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12963:                     my $intdom = &internet_dom($id);
                   12964:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12965:                         push(@idns,$intdom);
                   12966:                     }
                   12967:                 }
                   12968:             }
                   12969:             $seen{$prim_ip} = 1;
                   12970:         }
1.1219    raeburn  12971:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12972:     }
                   12973: 
1.986     foxr     12974: }
                   12975: 
1.1079    raeburn  12976: sub all_loncaparevs {
1.1249    raeburn  12977:     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  12978: }
                   12979: 
1.1227    raeburn  12980: # ---------------------------------------------------------- Read loncaparev table
                   12981: {
                   12982:     sub load_loncaparevs { 
                   12983:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12984:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12985:                 while (my $configline=<$config>) {
                   12986:                     chomp($configline);
                   12987:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12988:                     $loncaparevs{$hostid}=$loncaparev;
                   12989:                 }
                   12990:                 close($config);
                   12991:             }
                   12992:         }
                   12993:     }
                   12994: }
                   12995: 
                   12996: # ---------------------------------------------------------- Read serverhostID table
                   12997: {
                   12998:     sub load_serverhomeIDs {
                   12999:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13000:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13001:                 while (my $configline=<$config>) {
                   13002:                     chomp($configline);
                   13003:                     my ($name,$id)=split(/:/,$configline);
                   13004:                     $serverhomeIDs{$name}=$id;
                   13005:                 }
                   13006:                 close($config);
                   13007:             }
                   13008:         }
                   13009:     }
                   13010: }
                   13011: 
                   13012: 
1.862     albertel 13013: BEGIN {
                   13014: 
                   13015: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13016:     unless ($readit) {
                   13017: {
                   13018:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13019:     %perlvar = (%perlvar,%{$configvars});
                   13020: }
                   13021: 
                   13022: 
1.1       albertel 13023: # ------------------------------------------------------ Read spare server file
                   13024: {
1.448     albertel 13025:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13026: 
                   13027:     while (my $configline=<$config>) {
                   13028:        chomp($configline);
1.284     matthew  13029:        if ($configline) {
1.784     albertel 13030: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13031: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13032: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13033:        }
                   13034:     }
1.448     albertel 13035:     close($config);
1.1       albertel 13036: }
1.11      www      13037: # ------------------------------------------------------------ Read permissions
                   13038: {
1.448     albertel 13039:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13040: 
                   13041:     while (my $configline=<$config>) {
1.448     albertel 13042: 	chomp($configline);
                   13043: 	if ($configline) {
                   13044: 	    my ($role,$perm)=split(/ /,$configline);
                   13045: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13046: 	}
1.11      www      13047:     }
1.448     albertel 13048:     close($config);
1.11      www      13049: }
                   13050: 
                   13051: # -------------------------------------------- Read plain texts for permissions
                   13052: {
1.448     albertel 13053:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13054: 
                   13055:     while (my $configline=<$config>) {
1.448     albertel 13056: 	chomp($configline);
                   13057: 	if ($configline) {
1.742     raeburn  13058: 	    my ($short,@plain)=split(/:/,$configline);
                   13059:             %{$prp{$short}} = ();
                   13060: 	    if (@plain > 0) {
                   13061:                 $prp{$short}{'std'} = $plain[0];
                   13062:                 for (my $i=1; $i<@plain; $i++) {
                   13063:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13064:                 }
                   13065:             }
1.448     albertel 13066: 	}
1.135     www      13067:     }
1.448     albertel 13068:     close($config);
1.135     www      13069: }
                   13070: 
                   13071: # ---------------------------------------------------------- Read package table
                   13072: {
1.448     albertel 13073:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13074: 
                   13075:     while (my $configline=<$config>) {
1.483     albertel 13076: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13077: 	chomp($configline);
                   13078: 	my ($short,$plain)=split(/:/,$configline);
                   13079: 	my ($pack,$name)=split(/\&/,$short);
                   13080: 	if ($plain ne '') {
                   13081: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13082: 	    $packagetab{$short}=$plain; 
                   13083: 	}
1.11      www      13084:     }
1.448     albertel 13085:     close($config);
1.329     matthew  13086: }
                   13087: 
1.1073    raeburn  13088: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13089: 
                   13090: &load_loncaparevs();
1.1073    raeburn  13091: 
1.1074    raeburn  13092: # ---------------------------------------------------------- Read serverhostID table
                   13093: 
1.1227    raeburn  13094: &load_serverhomeIDs();
                   13095: 
                   13096: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13097: {
                   13098:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13099:     if (-e $file) {
                   13100:         my $parser = HTML::LCParser->new($file);
                   13101:         while (my $token = $parser->get_token()) {
                   13102:             if ($token->[0] eq 'S') {
                   13103:                 my $item = $token->[1];
                   13104:                 my $name = $token->[2]{'name'};
                   13105:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13106:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13107:                 my $namematch = $token->[2]{'namematch'};
                   13108:                 if ($item eq 'parameter') {
                   13109:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13110:                         my $release = $parser->get_text();
                   13111:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13112:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13113:                     }
                   13114:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13115:                     my $release = $parser->get_text();
                   13116:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13117:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13118:                 }
                   13119:             }
                   13120:         }
                   13121:     }
1.1073    raeburn  13122: }
                   13123: 
1.1138    raeburn  13124: # ---------------------------------------------------------- Read managers table
                   13125: {
                   13126:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13127:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13128:             while (my $configline=<$config>) {
                   13129:                 chomp($configline);
                   13130:                 next if ($configline =~ /^\#/);
                   13131:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13132:                     $managerstab{$configline} = 1;
                   13133:                 }
                   13134:             }
                   13135:             close($config);
                   13136:         }
                   13137:     }
                   13138: }
                   13139: 
1.329     matthew  13140: # ------------- set up temporary directory
                   13141: {
1.1117    foxr     13142:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13143: 
1.11      www      13144: }
                   13145: 
1.794     albertel 13146: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13147: 				'compress_threshold'=> 20_000,
                   13148:  			        });
1.185     www      13149: 
1.281     www      13150: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13151: $dumpcount=0;
1.958     www      13152: $locknum=0;
1.22      www      13153: 
1.163     harris41 13154: &logtouch();
1.672     albertel 13155: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13156: $readit=1;
1.564     albertel 13157:     {
                   13158: 	use integer;
                   13159: 	my $test=(2**32)+1;
1.568     albertel 13160: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13161: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13162:     }
1.195     www      13163: }
1.1       albertel 13164: }
1.179     www      13165: 
1.1       albertel 13166: 1;
1.191     harris41 13167: __END__
                   13168: 
1.243     albertel 13169: =pod
                   13170: 
1.191     harris41 13171: =head1 NAME
                   13172: 
1.243     albertel 13173: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13174: 
                   13175: =head1 SYNOPSIS
                   13176: 
1.243     albertel 13177: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13178: 
                   13179:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13180: 
1.243     albertel 13181: Common parameters:
                   13182: 
                   13183: =over 4
                   13184: 
                   13185: =item *
                   13186: 
                   13187: $uname : an internal username (if $cname expecting a course Id specifically)
                   13188: 
                   13189: =item *
                   13190: 
                   13191: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13192: 
                   13193: =item *
                   13194: 
                   13195: $symb : a resource instance identifier
                   13196: 
                   13197: =item *
                   13198: 
                   13199: $namespace : the name of a .db file that contains the data needed or
                   13200: being set.
                   13201: 
                   13202: =back
                   13203: 
1.394     bowersj2 13204: =head1 OVERVIEW
1.191     harris41 13205: 
1.394     bowersj2 13206: lonnet provides subroutines which interact with the
                   13207: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13208: about classes, users, and resources.
1.243     albertel 13209: 
                   13210: For many of these objects you can also use this to store data about
                   13211: them or modify them in various ways.
1.191     harris41 13212: 
1.394     bowersj2 13213: =head2 Symbs
1.191     harris41 13214: 
1.394     bowersj2 13215: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13216: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13217: map, the resource number of the resource in the map, and the URL of
                   13218: the resource itself. The latter is somewhat redundant, but might help
                   13219: if maps change.
                   13220: 
                   13221: An example is
                   13222: 
                   13223:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13224: 
                   13225: The respective map entry is
                   13226: 
                   13227:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13228:   title="Problem 2">
                   13229:  </resource>
                   13230: 
                   13231: Symbs are used by the random number generator, as well as to store and
                   13232: restore data specific to a certain instance of for example a problem.
                   13233: 
                   13234: =head2 Storing And Retrieving Data
                   13235: 
                   13236: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13237: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13238: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13239: is is the non-critical message twin of cstore. These functions are for
                   13240: handlers to store a perl hash to a user's permanent data space in an
                   13241: easy manner, and to retrieve it again on another call. It is expected
                   13242: that a handler would use this once at the beginning to retrieve data,
                   13243: and then again once at the end to send only the new data back.
                   13244: 
                   13245: The data is stored in the user's data directory on the user's
                   13246: homeserver under the ID of the course.
                   13247: 
                   13248: The hash that is returned by restore will have all of the previous
                   13249: value for all of the elements of the hash.
                   13250: 
                   13251: Example:
                   13252: 
                   13253:  #creating a hash
                   13254:  my %hash;
                   13255:  $hash{'foo'}='bar';
                   13256: 
                   13257:  #storing it
                   13258:  &Apache::lonnet::cstore(\%hash);
                   13259: 
                   13260:  #changing a value
                   13261:  $hash{'foo'}='notbar';
                   13262: 
                   13263:  #adding a new value
                   13264:  $hash{'bar'}='foo';
                   13265:  &Apache::lonnet::cstore(\%hash);
                   13266: 
                   13267:  #retrieving the hash
                   13268:  my %history=&Apache::lonnet::restore();
                   13269: 
                   13270:  #print the hash
                   13271:  foreach my $key (sort(keys(%history))) {
                   13272:    print("\%history{$key} = $history{$key}");
                   13273:  }
                   13274: 
                   13275: Will print out:
1.191     harris41 13276: 
1.394     bowersj2 13277:  %history{1:foo} = bar
                   13278:  %history{1:keys} = foo:timestamp
                   13279:  %history{1:timestamp} = 990455579
                   13280:  %history{2:bar} = foo
                   13281:  %history{2:foo} = notbar
                   13282:  %history{2:keys} = foo:bar:timestamp
                   13283:  %history{2:timestamp} = 990455580
                   13284:  %history{bar} = foo
                   13285:  %history{foo} = notbar
                   13286:  %history{timestamp} = 990455580
                   13287:  %history{version} = 2
                   13288: 
                   13289: Note that the special hash entries C<keys>, C<version> and
                   13290: C<timestamp> were added to the hash. C<version> will be equal to the
                   13291: total number of versions of the data that have been stored. The
                   13292: C<timestamp> attribute will be the UNIX time the hash was
                   13293: stored. C<keys> is available in every historical section to list which
                   13294: keys were added or changed at a specific historical revision of a
                   13295: hash.
                   13296: 
                   13297: B<Warning>: do not store the hash that restore returns directly. This
                   13298: will cause a mess since it will restore the historical keys as if the
                   13299: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13300: 
1.394     bowersj2 13301: Calling convention:
1.191     harris41 13302: 
1.1225    raeburn  13303:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13304:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13305: 
1.394     bowersj2 13306: For more detailed information, see lonnet specific documentation.
1.191     harris41 13307: 
1.394     bowersj2 13308: =head1 RETURN MESSAGES
1.191     harris41 13309: 
1.394     bowersj2 13310: =over 4
1.191     harris41 13311: 
1.394     bowersj2 13312: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13313: 
1.394     bowersj2 13314: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13315: when the connection is brought back up
1.191     harris41 13316: 
1.394     bowersj2 13317: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13318: for later delivery
1.191     harris41 13319: 
1.967     bisitz   13320: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13321: 
1.394     bowersj2 13322: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13323: that was requested
1.191     harris41 13324: 
1.243     albertel 13325: =back
1.191     harris41 13326: 
1.243     albertel 13327: =head1 PUBLIC SUBROUTINES
1.191     harris41 13328: 
1.243     albertel 13329: =head2 Session Environment Functions
1.191     harris41 13330: 
1.243     albertel 13331: =over 4
1.191     harris41 13332: 
1.394     bowersj2 13333: =item * 
                   13334: X<appenv()>
1.949     raeburn  13335: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13336: the user envirnoment file, and will be restored for each access this
1.620     albertel 13337: user makes during this session, also modifies the %env for the current
1.949     raeburn  13338: process. Optional rolesarrayref - if defined contains a reference to an array
                   13339: of roles which are exempt from the restriction on modifying user.role entries 
                   13340: in the user's environment.db and in %env.    
1.191     harris41 13341: 
                   13342: =item *
1.394     bowersj2 13343: X<delenv()>
1.987     raeburn  13344: B<delenv($delthis,$regexp)>: removes all items from the session
                   13345: environment file that begin with $delthis. If the 
                   13346: optional second arg - $regexp - is true, $delthis is treated as a 
                   13347: regular expression, otherwise \Q$delthis\E is used. 
                   13348: The values are also deleted from the current processes %env.
1.191     harris41 13349: 
1.795     albertel 13350: =item * get_env_multiple($name) 
                   13351: 
                   13352: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13353: values may be defined and end up as an array ref.
                   13354: 
                   13355: returns an array of values
                   13356: 
1.243     albertel 13357: =back
                   13358: 
                   13359: =head2 User Information
1.191     harris41 13360: 
1.243     albertel 13361: =over 4
1.191     harris41 13362: 
                   13363: =item *
1.394     bowersj2 13364: X<queryauthenticate()>
                   13365: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13366: authentication scheme
                   13367: 
                   13368: =item *
1.394     bowersj2 13369: X<authenticate()>
1.1073    raeburn  13370: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13371: authenticate user from domain's lib servers (first use the current
                   13372: one). C<$upass> should be the users password.
1.1073    raeburn  13373: $checkdefauth is optional (value is 1 if a check should be made to
                   13374:    authenticate user using default authentication method, and allow
                   13375:    account creation if username does not have account in the domain).
                   13376: $clientcancheckhost is optional (value is 1 if checking whether the
                   13377:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13378: 
                   13379: =item *
1.394     bowersj2 13380: X<homeserver()>
                   13381: B<homeserver($uname,$udom)>: find the server which has
                   13382: the user's directory and files (there must be only one), this caches
                   13383: the answer, and also caches if there is a borken connection.
1.191     harris41 13384: 
                   13385: =item *
1.394     bowersj2 13386: X<idget()>
1.1300    raeburn  13387: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13388: a list of student/employee IDs or clicker IDs
                   13389: (student/employee IDs are a unique resource in a domain, there must be 
                   13390: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13391: clickerIDs are not necessarily unique, as students might share clickers.
                   13392: (returns hash: id=>name,id=>name)
1.191     harris41 13393: 
                   13394: =item *
1.394     bowersj2 13395: X<idrget()>
                   13396: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13397: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13398: 
                   13399: =item *
1.394     bowersj2 13400: X<idput()>
1.1300    raeburn  13401: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13402: names and associated student/employee IDs or clicker IDs.
                   13403: 
                   13404: =item *
                   13405: X<iddel()>
                   13406: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13407: student/employee ID or clicker ID username look-ups from domain.
                   13408: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13409: If no $uhome is provided, it will be determined usig &homeserver()
                   13410: for each user.  If no $namespace is provided, the default is ids.
                   13411: 
                   13412: =item *
                   13413: X<updateclickers()>
                   13414: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13415: clicker ID-to-username look-ups in clickers.db on library server.
                   13416: Permitted actions are add or del (i.e., add or delete). The 
                   13417: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13418: value is an escaped comma-separated list of usernames (for whom the
                   13419: library server is the homeserver), who registered that particular ID.
                   13420: If $critical is true, the update will be sent via &critical, otherwise
                   13421: &reply() will be used.
1.191     harris41 13422: 
                   13423: =item *
1.394     bowersj2 13424: X<rolesinit()>
1.1169    droeschl 13425: B<rolesinit($udom,$username)>: get user privileges.
                   13426: returns user role, first access and timer interval hashes
1.243     albertel 13427: 
                   13428: =item *
1.1171    droeschl 13429: X<privileged()>
                   13430: B<privileged($username,$domain)>: returns a true if user has a
                   13431: privileged and active role (i.e. su or dc), false otherwise.
                   13432: 
                   13433: =item *
1.551     albertel 13434: X<getsection()>
                   13435: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13436: course $cname, return section name/number or '' for "not in course"
                   13437: and '-1' for "no section"
                   13438: 
                   13439: =item *
1.394     bowersj2 13440: X<userenvironment()>
                   13441: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13442: passed in @what from the requested user's environment, returns a hash
                   13443: 
1.858     raeburn  13444: =item * 
                   13445: X<userlog_query()>
1.859     albertel 13446: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13447: activity.log file. %filters defines filters applied when parsing the
                   13448: log file. These can be start or end timestamps, or the type of action
                   13449: - log to look for Login or Logout events, check for Checkin or
                   13450: Checkout, role for role selection. The response is in the form
                   13451: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13452: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13453: 
1.243     albertel 13454: =back
                   13455: 
                   13456: =head2 User Roles
                   13457: 
                   13458: =over 4
                   13459: 
                   13460: =item *
                   13461: 
1.1284    raeburn  13462: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13463: returns codes for allowed actions.
                   13464: 
                   13465: The first argument is required, all others are optional.
                   13466: 
                   13467: $priv is the privilege being checked.
                   13468: $uri contains additional information about what is being checked for access (e.g.,
                   13469: URL, course ID etc.). 
                   13470: $symb is the unique resource instance identifier in a course; if needed,
                   13471: but not provided, it will be retrieved via a call to &symbread(). 
                   13472: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13473: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13474: files).
                   13475: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13476: prevents recursive calls to &allowed.
                   13477: 
1.243     albertel 13478:  F: full access
                   13479:  U,I,K: authentication modes (cxx only)
                   13480:  '': forbidden
                   13481:  1: user needs to choose course
                   13482:  2: browse allowed
1.766     albertel 13483:  A: passphrase authentication needed
1.1284    raeburn  13484:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13485: 
                   13486: =item *
                   13487: 
1.1192    raeburn  13488: constructaccess($url,$setpriv) : check for access to construction space URL
                   13489: 
                   13490: See if the owner domain and name in the URL match those in the
                   13491: expected environment.  If so, return three element list
                   13492: ($ownername,$ownerdomain,$ownerhome).
                   13493: 
                   13494: Otherwise return the null string.
                   13495: 
                   13496: If second argument 'setpriv' is true, it assigns the privileges,
                   13497: and returns the same three element list, unless the owner has
                   13498: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13499: in which case the null string is returned.
                   13500: 
                   13501: =item *
                   13502: 
1.243     albertel 13503: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13504: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13505: and course level
                   13506: 
                   13507: =item *
                   13508: 
1.988     raeburn  13509: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13510: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13511: $type is Course (default) or Community.
1.988     raeburn  13512: If $forcedefault evaluates to true, text returned will be default 
                   13513: text for $type. Otherwise, if this is a course, the text returned 
                   13514: will be a custom name for the role (if defined in the course's 
                   13515: environment).  If no custom name is defined the default is returned.
                   13516:    
1.832     raeburn  13517: =item *
                   13518: 
1.1219    raeburn  13519: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13520: All arguments are optional. Returns a hash of a roles, either for
                   13521: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13522: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13523: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13524: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13525: For each key, value is set to colon-separated start and end times for
                   13526: the role.  If no username and domain are specified, will default to
1.934     raeburn  13527: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13528: of role statuses (active, future or previous), roles 
                   13529: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13530: to restrict the list of roles reported. If no array ref is 
                   13531: provided for types, will default to return only active roles.
1.834     albertel 13532: 
1.1195    raeburn  13533: =item *
                   13534: 
                   13535: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13536: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13537: 
                   13538: Additional optional arguments are: $type (if role checking is to be restricted 
                   13539: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13540: available roles) or future (roles available in the future), and
                   13541: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13542: have active Domain Coordinator role in course's domain or in additional
                   13543: domains (specified in 'Domains to check for privileged users' in course
                   13544: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13545: 
                   13546: =item *
                   13547: 
                   13548: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13549: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13550: $possdomains and $possroles are optional array refs -- to domains to check and
                   13551: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13552: users' roles.db to check for a dc or su role in any domain. This can be
                   13553: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13554: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13555: this then allows &privileged_by_domain() to be used, which caches the identity
                   13556: of privileged users, eliminating the need for repeated calls to &dump().
                   13557: 
                   13558: =item *
                   13559: 
                   13560: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13561: where the outer hash keys are domains specified in the $possdomains array ref,
                   13562: next inner hash keys are privileged roles specified in the $roles array ref,
                   13563: and the innermost hash contains key = value pairs for username:domain = end:start
                   13564: for active or future "privileged" users with that role in that domain. To avoid
                   13565: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13566: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13567: 
1.243     albertel 13568: =back
                   13569: 
                   13570: =head2 User Modification
                   13571: 
                   13572: =over 4
                   13573: 
                   13574: =item *
                   13575: 
1.957     raeburn  13576: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13577: user for the level given by URL.  Optional start and end dates (leave empty
                   13578: string or zero for "no date")
1.191     harris41 13579: 
                   13580: =item *
                   13581: 
1.243     albertel 13582: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13583: change a users, password, possible return values are: ok,
                   13584: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13585: refused
1.191     harris41 13586: 
                   13587: =item *
                   13588: 
1.243     albertel 13589: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13590: 
                   13591: =item *
                   13592: 
1.1058    raeburn  13593: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13594:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13595: 
                   13596: will update user information (firstname,middlename,lastname,generation,
                   13597: permanentemail), and if forceid is true, student/employee ID also.
                   13598: A user's institutional affiliation(s) can also be updated.
                   13599: User information fields will not be overwritten with empty entries 
                   13600: unless the field is included in the $candelete array reference.
                   13601: This array is included when a single user is modified via "Manage Users",
                   13602: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13603: 
                   13604: =item *
                   13605: 
1.286     matthew  13606: modifystudent
                   13607: 
1.957     raeburn  13608: modify a student's enrollment and identification information.
1.1235    raeburn  13609: The course id is resolved based on the current user's environment.  
                   13610: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13611: associated with a course.
                   13612: 
1.297     matthew  13613: This call is essentially a wrapper for lonnet::modifyuser and
                   13614: lonnet::modify_student_enrollment
1.286     matthew  13615: 
                   13616: Inputs: 
                   13617: 
                   13618: =over 4
                   13619: 
1.957     raeburn  13620: =item B<$udom> Student's loncapa domain
1.286     matthew  13621: 
1.957     raeburn  13622: =item B<$uname> Student's loncapa login name
1.286     matthew  13623: 
1.964     bisitz   13624: =item B<$uid> Student/Employee ID
1.286     matthew  13625: 
1.957     raeburn  13626: =item B<$umode> Student's authentication mode
1.286     matthew  13627: 
1.957     raeburn  13628: =item B<$upass> Student's password
1.286     matthew  13629: 
1.957     raeburn  13630: =item B<$first> Student's first name
1.286     matthew  13631: 
1.957     raeburn  13632: =item B<$middle> Student's middle name
1.286     matthew  13633: 
1.957     raeburn  13634: =item B<$last> Student's last name
1.286     matthew  13635: 
1.957     raeburn  13636: =item B<$gene> Student's generation
1.286     matthew  13637: 
1.957     raeburn  13638: =item B<$usec> Student's section in course
1.286     matthew  13639: 
                   13640: =item B<$end> Unix time of the roles expiration
                   13641: 
                   13642: =item B<$start> Unix time of the roles start date
                   13643: 
                   13644: =item B<$forceid> If defined, allow $uid to be changed
                   13645: 
                   13646: =item B<$desiredhome> server to use as home server for student
                   13647: 
1.957     raeburn  13648: =item B<$email> Student's permanent e-mail address
                   13649: 
                   13650: =item B<$type> Type of enrollment (auto or manual)
                   13651: 
1.963     raeburn  13652: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13653: 
                   13654: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13655: 
1.963     raeburn  13656: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13657: 
1.963     raeburn  13658: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13659: 
1.1216    raeburn  13660: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13661: 
                   13662: =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  13663: 
1.286     matthew  13664: =back
1.297     matthew  13665: 
                   13666: =item *
                   13667: 
                   13668: modify_student_enrollment
                   13669: 
1.1235    raeburn  13670: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13671: 'role.request.course' must be defined for this function to proceed.
                   13672: 
                   13673: Inputs:
                   13674: 
                   13675: =over 4
                   13676: 
1.1235    raeburn  13677: =item $udom, student's domain
1.297     matthew  13678: 
1.1235    raeburn  13679: =item $uname, student's name
1.297     matthew  13680: 
1.1235    raeburn  13681: =item $uid, student's user id
1.297     matthew  13682: 
1.1235    raeburn  13683: =item $first, student's first name
1.297     matthew  13684: 
                   13685: =item $middle
                   13686: 
                   13687: =item $last
                   13688: 
                   13689: =item $gene
                   13690: 
                   13691: =item $usec
                   13692: 
                   13693: =item $end
                   13694: 
                   13695: =item $start
                   13696: 
1.957     raeburn  13697: =item $type
                   13698: 
                   13699: =item $locktype
                   13700: 
                   13701: =item $cid
                   13702: 
                   13703: =item $selfenroll
                   13704: 
                   13705: =item $context
                   13706: 
1.1216    raeburn  13707: =item $credits, number of credits student will earn from this class
                   13708: 
1.297     matthew  13709: =back
                   13710: 
1.191     harris41 13711: 
                   13712: =item *
                   13713: 
1.243     albertel 13714: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13715: custom role; give a custom role to a user for the level given by URL.  Specify
                   13716: name and domain of role author, and role name
1.191     harris41 13717: 
                   13718: =item *
                   13719: 
1.243     albertel 13720: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13721: 
                   13722: =item *
                   13723: 
1.243     albertel 13724: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13725: 
                   13726: =back
                   13727: 
                   13728: =head2 Course Infomation
                   13729: 
                   13730: =over 4
1.191     harris41 13731: 
                   13732: =item *
                   13733: 
1.1118    foxr     13734: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13735: specified course id, including all environment settings for the
                   13736: course, the description of the course will be in the hash under the
                   13737: key 'description'
1.191     harris41 13738: 
1.1118    foxr     13739: $options is an optional parameter that if supplied is a hash reference that controls
                   13740: what how this function works.  It has the following key/values:
                   13741: 
                   13742: =over 4
                   13743: 
                   13744: =item freshen_cache
                   13745: 
                   13746: If defined, and the environment cache for the course is valid, it is 
                   13747: returned in the returned hash.
                   13748: 
                   13749: =item one_time
                   13750: 
                   13751: If defined, the last cache time is set to _now_
                   13752: 
                   13753: =item user
                   13754: 
                   13755: If defined, the supplied username is used instead of the current user.
                   13756: 
                   13757: 
                   13758: =back
                   13759: 
1.191     harris41 13760: =item *
                   13761: 
1.624     albertel 13762: resdata($name,$domain,$type,@which) : request for current parameter
                   13763: setting for a specific $type, where $type is either 'course' or 'user',
                   13764: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13765: answers for 10 minutes.
1.243     albertel 13766: 
1.877     foxr     13767: =item *
                   13768: 
                   13769: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13770: data base, returning a hash that is keyed by the resource name and has
                   13771: values that are the resource value.  I believe that the timestamps and
                   13772: versions are also returned.
                   13773: 
1.1236    raeburn  13774: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13775: supplemental content area. This routine caches the number of files for 
                   13776: 10 minutes.
                   13777: 
1.243     albertel 13778: =back
                   13779: 
                   13780: =head2 Course Modification
                   13781: 
                   13782: =over 4
1.191     harris41 13783: 
                   13784: =item *
                   13785: 
1.243     albertel 13786: writecoursepref($courseid,%prefs) : write preferences (environment
                   13787: database) for a course
1.191     harris41 13788: 
                   13789: =item *
                   13790: 
1.1011    raeburn  13791: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13792: 
                   13793: =item *
                   13794: 
1.1038    raeburn  13795: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13796: 
1.1167    droeschl 13797: =item *
                   13798: 
                   13799: is_course($courseid), is_course($cdom, $cnum)
                   13800: 
                   13801: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13802: two component version $cdom, $cnum. It checks if the specified course exists.
                   13803: 
                   13804: Returns:
                   13805:     undef if the course doesn't exist, otherwise
                   13806:     in scalar context the combined courseid.
                   13807:     in list context the two components of the course identifier, domain and 
                   13808:     courseid.    
                   13809: 
1.243     albertel 13810: =back
                   13811: 
                   13812: =head2 Resource Subroutines
                   13813: 
                   13814: =over 4
1.191     harris41 13815: 
                   13816: =item *
                   13817: 
1.243     albertel 13818: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13819: 
                   13820: =item *
                   13821: 
1.243     albertel 13822: repcopy($filename) : subscribes to the requested file, and attempts to
                   13823: replicate from the owning library server, Might return
1.607     raeburn  13824: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13825: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13826: resource. Expects the local filesystem pathname
                   13827: (/home/httpd/html/res/....)
                   13828: 
                   13829: =back
                   13830: 
                   13831: =head2 Resource Information
                   13832: 
                   13833: =over 4
1.191     harris41 13834: 
                   13835: =item *
                   13836: 
1.1228    raeburn  13837: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13838: and returns the value of a variety of different possible values,
                   13839: $varname should be a request string, and the other parameters can be
                   13840: used to specify who and what one is asking about. Ordinarily, $cid 
                   13841: does not need to be specified, as it is retrived from 
                   13842: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13843: within lonuserstate::loadmap() when initializing a course, before
                   13844: $env{'request.course.id'} has been set, so it needs to be provided
                   13845: in that one case.
1.243     albertel 13846: 
                   13847: Possible values for $varname are environment.lastname (or other item
                   13848: from the envirnment hash), user.name (or someother aspect about the
                   13849: user), resource.0.maxtries (or some other part and parameter of a
                   13850: resource)
1.204     albertel 13851: 
                   13852: =item *
                   13853: 
1.243     albertel 13854: directcondval($number) : get current value of a condition; reads from a state
                   13855: string
1.204     albertel 13856: 
                   13857: =item *
                   13858: 
1.243     albertel 13859: condval($condidx) : value of condition index based on state
1.204     albertel 13860: 
                   13861: =item *
                   13862: 
1.243     albertel 13863: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13864: resource's metadata, $what should be either a specific key, or either
                   13865: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13866: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13867: 
                   13868: this function automatically caches all requests
1.191     harris41 13869: 
                   13870: =item *
                   13871: 
1.243     albertel 13872: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13873: network of library servers; returns file handle of where SQL and regex results
                   13874: will be stored for query
1.191     harris41 13875: 
                   13876: =item *
                   13877: 
1.1282    raeburn  13878: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   13879: return symbolic list entry (all arguments optional). 
                   13880: 
                   13881: Args: filename is the filename (including path) for the file for which a symb 
                   13882: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   13883: to check access status if more than one resource was found in the bighash 
                   13884: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   13885: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   13886: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13887: cause possible symbs to be checked to determine if they are subject to content
                   13888: blocking, if so they will not be included as possible symbs; possibles is a
                   13889: ref to a hash, which, as a side effect, will be populated with all possible 
                   13890: symbs (content blocking not tested).
                   13891:  
1.243     albertel 13892: returns the data handle
1.191     harris41 13893: 
                   13894: =item *
                   13895: 
1.1190    raeburn  13896: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13897: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13898: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13899: on failure, user must be in a course, as it assumes the existence of
                   13900: the course initial hash, and uses $env('request.course.id'}.  The third
                   13901: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13902: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13903: encrypted; otherwise it will be null.  
1.191     harris41 13904: 
                   13905: =item *
                   13906: 
1.243     albertel 13907: symbclean($symb) : removes versions numbers from a symb, returns the
                   13908: cleaned symb
1.191     harris41 13909: 
                   13910: =item *
                   13911: 
1.243     albertel 13912: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13913: course map, user must be in a course for it to work.
1.191     harris41 13914: 
                   13915: =item *
                   13916: 
1.243     albertel 13917: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13918: 
                   13919: =item *
                   13920: 
1.243     albertel 13921: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13922: a random seed, all arguments are optional, if they aren't sent it uses the
                   13923: environment to derive them. Note: if symb isn't sent and it can't get one
                   13924: from &symbread it will use the current time as its return value
1.191     harris41 13925: 
                   13926: =item *
                   13927: 
1.243     albertel 13928: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13929: unfakeable, receipt
1.191     harris41 13930: 
                   13931: =item *
                   13932: 
1.620     albertel 13933: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13934: 
                   13935: =item *
                   13936: 
1.243     albertel 13937: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13938: 
                   13939: =item *
                   13940: 
1.243     albertel 13941: 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 13942: 
                   13943: =item *
                   13944: 
1.243     albertel 13945: 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 13946: 
                   13947: =item *
                   13948: 
1.243     albertel 13949: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13950: 
                   13951: =item *
                   13952: 
1.243     albertel 13953: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13954: forcing spreadsheet to reevaluate the resource scores next time.
                   13955: 
1.1195    raeburn  13956: =item * 
                   13957: 
1.1196    raeburn  13958: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13959: when viewing in course context.
1.1195    raeburn  13960: 
1.1196    raeburn  13961:  input: six args -- filename (decluttered), course number, course domain,
                   13962:                     url, symb (if registered) and group (if this is a 
                   13963:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13964: 
1.1196    raeburn  13965:  output: array of five scalars --
1.1195    raeburn  13966:          $cfile -- url for file editing if editable on current server
                   13967:          $home -- homeserver of resource (i.e., for author if published,
                   13968:                                           or course if uploaded.).
                   13969:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13970:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13971:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13972: 
                   13973: =item *
                   13974: 
                   13975: is_course_upload($file,$cnum,$cdom)
                   13976: 
                   13977: Used in course context to determine if current file was uploaded to 
                   13978: the course (i.e., would be found in /userfiles/docs on the course's 
                   13979: homeserver.
                   13980: 
                   13981:   input: 3 args -- filename (decluttered), course number and course domain.
                   13982:   output: boolean -- 1 if file was uploaded.
                   13983: 
1.243     albertel 13984: =back
                   13985: 
                   13986: =head2 Storing/Retreiving Data
                   13987: 
                   13988: =over 4
1.191     harris41 13989: 
                   13990: =item *
                   13991: 
1.1269    raeburn  13992: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   13993: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13994: the remaining args aren't required and if they aren't passed or are '' they will
                   13995: be derived from the env (with the exception of $laststore, which is an 
                   13996: optional arg used when a user's submission is stored in grading).
                   13997: $laststore is $version=$timestamp, where $version is the most recent version
                   13998: number retrieved for the corresponding $symb in the $namespace db file, and
                   13999: $timestamp is the timestamp for that transaction (UNIX time).
                   14000: $laststore is currently only passed when cstore() is called by 
                   14001: structuretags::finalize_storage().
1.191     harris41 14002: 
                   14003: =item *
                   14004: 
1.1269    raeburn  14005: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14006: but uses critical subroutine
1.191     harris41 14007: 
                   14008: =item *
                   14009: 
1.243     albertel 14010: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14011: all args are optional
1.191     harris41 14012: 
                   14013: =item *
                   14014: 
1.717     albertel 14015: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14016: dumps the complete (or key matching regexp) namespace into a hash
                   14017: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14018: normally &store()ed into
                   14019: 
                   14020: $range should be either an integer '100' (give me the first 100
                   14021:                                            matching records)
                   14022:               or be  two integers sperated by a - with no spaces
                   14023:                  '30-50' (give me the 30th through the 50th matching
                   14024:                           records)
                   14025: 
                   14026: 
                   14027: =item *
                   14028: 
1.1269    raeburn  14029: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14030: replaces a &store() version of data with a replacement set of data
                   14031: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14032: reference. If $tolog is true, the transaction is logged in the courselog
                   14033: with an action=PUTSTORE.
1.717     albertel 14034: 
                   14035: =item *
                   14036: 
1.243     albertel 14037: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14038: works very similar to store/cstore, but all data is stored in a
                   14039: temporary location and can be reset using tmpreset, $storehash should
                   14040: be a hash reference, returns nothing on success
1.191     harris41 14041: 
                   14042: =item *
                   14043: 
1.243     albertel 14044: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14045: similar to restore, but all data is stored in a temporary location and
                   14046: can be reset using tmpreset. Returns a hash of values on success,
                   14047: error string otherwise.
1.191     harris41 14048: 
                   14049: =item *
                   14050: 
1.243     albertel 14051: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14052: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14053: 
                   14054: =item *
                   14055: 
1.243     albertel 14056: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14057: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14058: 
                   14059: =item *
                   14060: 
1.243     albertel 14061: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14062: namesp ($udom and $uname are optional)
1.191     harris41 14063: 
                   14064: =item *
                   14065: 
1.702     albertel 14066: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14067: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14068: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14069: 
1.702     albertel 14070: $range should be either an integer '100' (give me the first 100
                   14071:                                            matching records)
                   14072:               or be  two integers sperated by a - with no spaces
                   14073:                  '30-50' (give me the 30th through the 50th matching
                   14074:                           records)
1.449     matthew  14075: =item *
                   14076: 
                   14077: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14078: $store can be a scalar, an array reference, or if the amount to be 
                   14079: incremented is > 1, a hash reference.
                   14080: 
                   14081: ($udom and $uname are optional)
1.191     harris41 14082: 
                   14083: =item *
                   14084: 
1.243     albertel 14085: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14086: ($udom and $uname are optional)
1.191     harris41 14087: 
                   14088: =item *
                   14089: 
1.243     albertel 14090: cput($namespace,$storehash,$udom,$uname) : critical put
                   14091: ($udom and $uname are optional)
1.191     harris41 14092: 
                   14093: =item *
                   14094: 
1.748     albertel 14095: newput($namespace,$storehash,$udom,$uname) :
                   14096: 
                   14097: Attempts to store the items in the $storehash, but only if they don't
                   14098: currently exist, if this succeeds you can be certain that you have 
                   14099: successfully created a new key value pair in the $namespace db.
                   14100: 
                   14101: 
                   14102: Args:
                   14103:  $namespace: name of database to store values to
                   14104:  $storehash: hashref to store to the db
                   14105:  $udom: (optional) domain of user containing the db
                   14106:  $uname: (optional) name of user caontaining the db
                   14107: 
                   14108: Returns:
                   14109:  'ok' -> succeeded in storing all keys of $storehash
                   14110:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14111:                         least <key> already existed in the db (other
                   14112:                         requested keys may also already exist)
1.967     bisitz   14113:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14114:  'con_lost' -> unable to contact request server
                   14115:  'refused' -> action was not allowed by remote machine
                   14116: 
                   14117: 
                   14118: =item *
                   14119: 
1.243     albertel 14120: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14121: reference filled in from namesp (encrypts the return communication)
                   14122: ($udom and $uname are optional)
1.191     harris41 14123: 
                   14124: =item *
                   14125: 
1.243     albertel 14126: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14127: critical subroutine
                   14128: 
1.806     raeburn  14129: =item *
                   14130: 
1.860     raeburn  14131: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14132: array reference filled in from namespace found in domain level on either
                   14133: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14134: 
                   14135: =item *
                   14136: 
1.860     raeburn  14137: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14138: domain level either on specified domain server ($uhome) or primary domain 
                   14139: server ($udom and $uhome are optional)
1.806     raeburn  14140: 
1.943     raeburn  14141: =item * 
                   14142: 
1.1240    raeburn  14143: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14144: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14145: the target domain.
                   14146: 
                   14147: May also include additional key => value pairs for the following groups:
                   14148: 
                   14149: =over
                   14150: 
                   14151: =item
                   14152: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14153: 
                   14154: =over
                   14155: 
                   14156: =item defaultquota, authorquota
                   14157: 
                   14158: =back
                   14159: 
                   14160: =item
                   14161: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14162: portfolio for users).
                   14163: 
                   14164: =over
                   14165: 
                   14166: =item
                   14167: aboutme, blog, webdav, portfolio
                   14168: 
                   14169: =back
                   14170: 
                   14171: =item
                   14172: requestcourses: ability to request courses, and how requests are processed.
                   14173: 
                   14174: =over
                   14175: 
                   14176: =item
1.1305    raeburn  14177: official, unofficial, community, textbook, placement
1.1240    raeburn  14178: 
                   14179: =back
                   14180: 
                   14181: =item
                   14182: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14183: 
                   14184: =over
                   14185: 
                   14186: =item
1.1256    raeburn  14187: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14188: 
                   14189: =back
                   14190: 
                   14191: =item
                   14192: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14193: for course's uploaded content.
                   14194: 
                   14195: =over
                   14196: 
                   14197: =item
1.1246    raeburn  14198: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14199: communityquota, textbookquota, placementquota
1.1240    raeburn  14200: 
                   14201: =back
                   14202: 
                   14203: =item
                   14204: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14205: on your servers.
                   14206: 
                   14207: =over
                   14208: 
                   14209: =item 
                   14210: remotesessions, hostedsessions
                   14211: 
                   14212: =back
                   14213: 
                   14214: =back
                   14215: 
                   14216: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14217: utility to create a configuration.db file on a domain's primary library server 
                   14218: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14219: -- corresponding values are authentication type (internal, krb4, krb5,
                   14220: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14221: will be available. Values are retrieved from cache (if current), unless the
                   14222: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14223: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14224: 
                   14225: Typical usage:
1.943     raeburn  14226: 
1.1240    raeburn  14227: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14228: 
1.243     albertel 14229: =back
                   14230: 
                   14231: =head2 Network Status Functions
                   14232: 
                   14233: =over 4
1.191     harris41 14234: 
                   14235: =item *
                   14236: 
1.1137    raeburn  14237: dirlist() : return directory list based on URI (first arg).
                   14238: 
                   14239: Inputs: 1 required, 5 optional.
                   14240: 
                   14241: =over
                   14242: 
                   14243: =item 
                   14244: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14245: 
                   14246: =item
                   14247: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14248: 
                   14249: =item
                   14250: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14251: 
                   14252: =item
                   14253: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14254: 
                   14255: =item
                   14256: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14257: 
                   14258: =item 
                   14259: $alternateRoot - path to prepend in place of path from $uri.
                   14260: 
                   14261: =back
                   14262: 
                   14263: Returns: Array of up to two items.
                   14264: 
                   14265: =over
                   14266: 
                   14267: a reference to an array of files/subdirectories
                   14268: 
                   14269: =over
                   14270: 
                   14271: Each element in the array of files/subdirectories is a & separated list of
                   14272: item name and the result of running stat on the item.  If dirlist was requested
                   14273: for a file instead of a directory, the item name will be ''. For a directory 
                   14274: listing, if the item is a metadata file, the element will end &N&M 
                   14275: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14276: default copyright set (1).  
                   14277: 
                   14278: =back
                   14279: 
                   14280: a scalar containing error condition (if encountered).
                   14281: 
                   14282: =over
                   14283: 
                   14284: =item 
                   14285: no_host (no homeserver identified for $username:$domain).
                   14286: 
                   14287: =item 
                   14288: no_such_host (server contacted for listing not identified as valid host).
                   14289: 
                   14290: =item 
                   14291: con_lost (connection to remote server failed).
                   14292: 
                   14293: =item 
                   14294: refused (invalid $username:$domain received on lond side).
                   14295: 
                   14296: =item 
                   14297: no_such_dir (directory at specified path on lond side does not exist). 
                   14298: 
                   14299: =item 
                   14300: empty (directory at specified path on lond side is empty).
                   14301: 
                   14302: =over
                   14303: 
                   14304: This is currently not encountered because the &ls3, &ls2, 
                   14305: &ls (_handler) routines on the lond side do not filter out
                   14306: . and .. from a directory listing. 
                   14307: 
                   14308: =back
                   14309: 
                   14310: =back
                   14311: 
                   14312: =back
1.191     harris41 14313: 
                   14314: =item *
                   14315: 
1.243     albertel 14316: spareserver() : find server with least workload from spare.tab
                   14317: 
1.986     foxr     14318: 
                   14319: =item *
                   14320: 
                   14321: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14322: if there is no corresponding loncapa host.
                   14323: 
1.243     albertel 14324: =back
                   14325: 
1.986     foxr     14326: 
1.243     albertel 14327: =head2 Apache Request
                   14328: 
                   14329: =over 4
1.191     harris41 14330: 
                   14331: =item *
                   14332: 
1.243     albertel 14333: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14334: localhost, posts hash
                   14335: 
                   14336: =back
                   14337: 
                   14338: =head2 Data to String to Data
                   14339: 
                   14340: =over 4
1.191     harris41 14341: 
                   14342: =item *
                   14343: 
1.243     albertel 14344: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14345: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14346: 
                   14347: =item *
                   14348: 
1.243     albertel 14349: hashref2str($hashref) : convert a hashref into a string complete with
                   14350: escaping and '=' and '&' separators, supports elements that are
                   14351: arrayrefs and hashrefs
1.191     harris41 14352: 
                   14353: =item *
                   14354: 
1.243     albertel 14355: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14356: with escaping and '&' separators, supports elements that are arrayrefs
                   14357: and hashrefs
1.191     harris41 14358: 
                   14359: =item *
                   14360: 
1.243     albertel 14361: str2hash($string) : convert string to hash using unescaping and
                   14362: splitting on '=' and '&', supports elements that are arrayrefs and
                   14363: hashrefs
1.191     harris41 14364: 
                   14365: =item *
                   14366: 
1.243     albertel 14367: str2array($string) : convert string to hash using unescaping and
                   14368: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14369: 
                   14370: =back
                   14371: 
                   14372: =head2 Logging Routines
                   14373: 
                   14374: 
                   14375: These routines allow one to make log messages in the lonnet.log and
                   14376: lonnet.perm logfiles.
1.191     harris41 14377: 
1.1119    foxr     14378: =over 4
                   14379: 
1.191     harris41 14380: =item *
                   14381: 
1.243     albertel 14382: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14383: 
                   14384: =item *
                   14385: 
1.243     albertel 14386: logthis() : append message to the normal lonnet.log file, it gets
                   14387: preiodically rolled over and deleted.
1.191     harris41 14388: 
                   14389: =item *
                   14390: 
1.243     albertel 14391: logperm() : append a permanent message to lonnet.perm.log, this log
                   14392: file never gets deleted by any automated portion of the system, only
                   14393: messages of critical importance should go in here.
                   14394: 
1.1119    foxr     14395: 
1.243     albertel 14396: =back
                   14397: 
                   14398: =head2 General File Helper Routines
                   14399: 
                   14400: =over 4
1.191     harris41 14401: 
                   14402: =item *
                   14403: 
1.481     raeburn  14404: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14405: (a) files in /uploaded
                   14406:   (i) If a local copy of the file exists - 
                   14407:       compares modification date of local copy with last-modified date for 
                   14408:       definitive version stored on home server for course. If local copy is 
                   14409:       stale, requests a new version from the home server and stores it. 
                   14410:       If the original has been removed from the home server, then local copy 
                   14411:       is unlinked.
                   14412:   (ii) If local copy does not exist -
                   14413:       requests the file from the home server and stores it. 
                   14414:   
                   14415:   If $caller is 'uploadrep':  
                   14416:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14417:     for request for files originally uploaded via DOCS. 
                   14418:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14419:   
                   14420:   Otherwise:
                   14421:      This indicates a call from the content generation phase of the request.
                   14422:      -  returns the entire contents of the file or -1.
                   14423:      
                   14424: (b) files in /res
                   14425:    - returns the entire contents of a file or -1; 
                   14426:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14427: 
1.712     albertel 14428: 
                   14429: =item *
                   14430: 
                   14431: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14432:                   reference
                   14433: 
                   14434: returns either a stat() list of data about the file or an empty list
                   14435: if the file doesn't exist or couldn't find out about it (connection
                   14436: problems or user unknown)
                   14437: 
1.191     harris41 14438: =item *
                   14439: 
1.243     albertel 14440: filelocation($dir,$file) : returns file system location of a file
                   14441: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14442: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14443: and a file of ../bob will become /a/bob)
1.191     harris41 14444: 
                   14445: =item *
                   14446: 
                   14447: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14448: filelocation except for hrefs
                   14449: 
                   14450: =item *
                   14451: 
1.1261    raeburn  14452: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14453: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14454: 
1.243     albertel 14455: =back
                   14456: 
1.608     albertel 14457: =head2 Usererfile file routines (/uploaded*)
                   14458: 
                   14459: =over 4
                   14460: 
                   14461: =item *
                   14462: 
                   14463: userfileupload(): main rotine for putting a file in a user or course's
                   14464:                   filespace, arguments are,
                   14465: 
1.620     albertel 14466:  formname - required - this is the name of the element in $env where the
1.608     albertel 14467:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14468:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14469:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14470:  context - if coursedoc, store the file in the course of the active role
                   14471:              of the current user; 
                   14472:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14473:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14474:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14475:          if undefined, it will be placed in "unknown"
                   14476: 
                   14477:  (This routine calls clean_filename() to remove any dangerous
                   14478:  characters from the filename, and then calls finuserfileupload() to
                   14479:  complete the transaction)
                   14480: 
                   14481:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14482:  and /adm/notfound.html if unsuccessful
                   14483: 
                   14484: =item *
                   14485: 
                   14486: clean_filename(): routine for cleaing a filename up for storage in
                   14487:                  userfile space, argument is:
                   14488: 
                   14489:  filename - proposed filename
                   14490: 
                   14491: returns: the new clean filename
                   14492: 
                   14493: =item *
                   14494: 
1.1090    raeburn  14495: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14496: userspace, probably shouldn't be called directly
                   14497: 
                   14498:   docuname: username or courseid of destination for the file
                   14499:   docudom: domain of user/course of destination for the file
                   14500:   formname: same as for userfileupload()
1.1090    raeburn  14501:   fname: filename (including subdirectories) for the file
                   14502:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14503:   allfiles: reference to hash used to store objects found by parser
                   14504:   codebase: reference to hash used for codebases of java objects found by parser
                   14505:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14506:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14507:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14508:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14509:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14510:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14511:   mimetype: reference to scalar to accommodate mime type determined
                   14512:             from File::MMagic if $parser = parse.
1.608     albertel 14513: 
                   14514:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14515:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14516:  was 'overwrite').
                   14517:  
1.608     albertel 14518: 
                   14519: =item *
                   14520: 
                   14521: renameuserfile(): renames an existing userfile to a new name
                   14522: 
                   14523:   Args:
                   14524:    docuname: username or courseid of destination for the file
                   14525:    docudom: domain of user/course of destination for the file
                   14526:    old: current file name (including any subdirs under userfiles)
                   14527:    new: desired file name (including any subdirs under userfiles)
                   14528: 
                   14529: =item *
                   14530: 
                   14531: mkdiruserfile(): creates a directory is a userfiles dir
                   14532: 
                   14533:   Args:
                   14534:    docuname: username or courseid of destination for the file
                   14535:    docudom: domain of user/course of destination for the file
                   14536:    dir: dir to create (including any subdirs under userfiles)
                   14537: 
                   14538: =item *
                   14539: 
                   14540: removeuserfile(): removes a file that exists in userfiles
                   14541: 
                   14542:   Args:
                   14543:    docuname: username or courseid of destination for the file
                   14544:    docudom: domain of user/course of destination for the file
                   14545:    fname: filname to delete (including any subdirs under userfiles)
                   14546: 
                   14547: =item *
                   14548: 
                   14549: removeuploadedurl(): convience function for removeuserfile()
                   14550: 
                   14551:   Args:
                   14552:    url:  a full /uploaded/... url to delete
                   14553: 
1.747     albertel 14554: =item * 
                   14555: 
                   14556: get_portfile_permissions():
                   14557:   Args:
                   14558:     domain: domain of user or course contain the portfolio files
                   14559:     user: name of user or num of course contain the portfolio files
                   14560:   Returns:
                   14561:     hashref of a dump of the proper file_permissions.db
                   14562:    
                   14563: 
                   14564: =item * 
                   14565: 
                   14566: get_access_controls():
                   14567: 
                   14568: Args:
                   14569:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14570:   group: (optional) the group you want the files associated with
                   14571:   file: (optional) the file you want access info on
                   14572: 
                   14573: Returns:
1.749     raeburn  14574:     a hash (keys are file names) of hashes containing
                   14575:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14576:         values are XML containing access control settings (see below) 
1.747     albertel 14577: 
                   14578: Internal notes:
                   14579: 
1.749     raeburn  14580:  access controls are stored in file_permissions.db as key=value pairs.
                   14581:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14582:         where scope -> public,guest,course,group,domains or users.
                   14583:               end -> UNIX time for end of access (0 -> no end date)
                   14584:               start -> UNIX time for start of access
                   14585: 
                   14586:     value -> XML description of access control
                   14587:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14588:             <start></start>
                   14589:             <end></end>
                   14590: 
                   14591:             <password></password>  for scope type = guest
                   14592: 
                   14593:             <domain></domain>     for scope type = course or group
                   14594:             <number></number>
                   14595:             <roles id="">
                   14596:              <role></role>
                   14597:              <access></access>
                   14598:              <section></section>
                   14599:              <group></group>
                   14600:             </roles>
                   14601: 
                   14602:             <dom></dom>         for scope type = domains
                   14603: 
                   14604:             <users>             for scope type = users
                   14605:              <user>
                   14606:               <uname></uname>
                   14607:               <udom></udom>
                   14608:              </user>
                   14609:             </users>
                   14610:            </scope> 
                   14611:               
                   14612:  Access data is also aggregated for each file in an additional key=value pair:
                   14613:  key -> path to file/file_name\0accesscontrol 
                   14614:  value -> reference to hash
                   14615:           hash contains key = value pairs
                   14616:           where key = uniqueID:scope_end_start
                   14617:                 value = UNIX time record was last updated
                   14618: 
                   14619:           Used to improve speed of look-ups of access controls for each file.  
                   14620:  
                   14621:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14622: 
1.1198    raeburn  14623: =item *
                   14624: 
1.749     raeburn  14625: modify_access_controls():
                   14626: 
                   14627: Modifies access controls for a portfolio file
                   14628: Args
                   14629: 1. file name
                   14630: 2. reference to hash of required changes,
                   14631: 3. domain
                   14632: 4. username
                   14633:   where domain,username are the domain of the portfolio owner 
                   14634:   (either a user or a course) 
                   14635: 
                   14636: Returns:
                   14637: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14638: 2. result of deletions ('ok' or 'error', with error message).
                   14639: 3. reference to hash of any new or updated access controls.
                   14640: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14641:    key = integer (inbound ID)
1.1198    raeburn  14642:    value = uniqueID
                   14643: 
                   14644: =item *
                   14645: 
                   14646: get_timebased_id():
                   14647: 
                   14648: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14649: course via the Course Editor (e.g., folders, composite pages, 
                   14650: group bulletin boards).
                   14651: 
                   14652: Args: (first three required; six others optional)
                   14653: 
                   14654: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14655:    docssequence, or name of group
                   14656: 
                   14657: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14658:    e.g., num, boardids
                   14659: 
                   14660: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14661:    file will be named nohist_namespace.db
                   14662: 
                   14663: 4. cdom: domain of course; default is current course domain from %env
                   14664: 
                   14665: 5. cnum: course number; default is current course number from %env
                   14666: 
                   14667: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14668:    unix timestamp to form the suffix, if the plain timestamp is already
                   14669:    in use.  Default is to not do this, but simply increment the unix 
                   14670:    timestamp by 1 until a unique key is obtained.
                   14671: 
                   14672: 7. who: holder of locking key; defaults to user:domain for user.
                   14673: 
                   14674: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14675:    retrying); default is 3.
                   14676: 
                   14677: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14678: 
                   14679: Returns:
                   14680: 
                   14681: 1. suffix obtained (numeric)
                   14682: 
                   14683: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14684: 
                   14685: 3. error: contains (localized) error message if an error occurred.
                   14686: 
1.747     albertel 14687: 
1.608     albertel 14688: =back
                   14689: 
1.243     albertel 14690: =head2 HTTP Helper Routines
                   14691: 
                   14692: =over 4
                   14693: 
1.191     harris41 14694: =item *
                   14695: 
                   14696: escape() : unpack non-word characters into CGI-compatible hex codes
                   14697: 
                   14698: =item *
                   14699: 
                   14700: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14701: 
1.243     albertel 14702: =back
                   14703: 
                   14704: =head1 PRIVATE SUBROUTINES
                   14705: 
                   14706: =head2 Underlying communication routines (Shouldn't call)
                   14707: 
                   14708: =over 4
                   14709: 
                   14710: =item *
                   14711: 
                   14712: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14713: 
                   14714: =item *
                   14715: 
                   14716: reply() : uses subreply to send a message to remote machine, logs all failures
                   14717: 
                   14718: =item *
                   14719: 
                   14720: critical() : passes a critical message to another server; if cannot
                   14721: get through then place message in connection buffer directory and
                   14722: returns con_delayed, if incapable of saving message, returns
                   14723: con_failed
                   14724: 
                   14725: =item *
                   14726: 
                   14727: reconlonc() : tries to reconnect lonc client processes.
                   14728: 
                   14729: =back
                   14730: 
                   14731: =head2 Resource Access Logging
                   14732: 
                   14733: =over 4
                   14734: 
                   14735: =item *
                   14736: 
                   14737: flushcourselogs() : flush (save) buffer logs and access logs
                   14738: 
                   14739: =item *
                   14740: 
                   14741: courselog($what) : save message for course in hash
                   14742: 
                   14743: =item *
                   14744: 
                   14745: courseacclog($what) : save message for course using &courselog().  Perform
                   14746: special processing for specific resource types (problems, exams, quizzes, etc).
                   14747: 
1.191     harris41 14748: =item *
                   14749: 
                   14750: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14751: as a PerlChildExitHandler
1.243     albertel 14752: 
                   14753: =back
                   14754: 
                   14755: =head2 Other
                   14756: 
                   14757: =over 4
                   14758: 
                   14759: =item *
                   14760: 
                   14761: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14762: 
                   14763: =back
                   14764: 
                   14765: =cut
1.877     foxr     14766: 

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